file_name
stringlengths 71
779k
| comments
stringlengths 20
182k
| code_string
stringlengths 20
36.9M
| __index_level_0__
int64 0
17.2M
| input_ids
sequence | attention_mask
sequence | labels
sequence |
---|---|---|---|---|---|---|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "./interfaces/IPunkCrushers.sol";
/**
* @title PunkCrushers NFTs
* @dev Implementation of the {IPunkCrushers} interface.
* @author Ahmed Ali Bhatti <github.com/ahmedali8>
*/
contract PunkCrushers is IPunkCrushers, Ownable, ERC721Enumerable {
using Counters for Counters.Counter;
using Strings for uint256;
// tokenId tracker using lib
Counters.Counter private _tokenIdTracker;
string private _baseTokenURI;
// flag for updating {baseURI} only once.
bool private _uriUpdated = false;
/**
* @dev See {IPunkCrushers-MAX_SUPPLY}.
*/
uint256 public constant override MAX_SUPPLY = 10000;
/**
* @dev See {IPunkCrushers-PRICE_PER_TOKEN_FOR_1}.
*/
uint256 public constant override PRICE_PER_TOKEN_FOR_1 = 0.085 ether;
/**
* @dev See {IPunkCrushers-PRICE_PER_TOKEN_FOR_3}.
*/
uint256 public constant override PRICE_PER_TOKEN_FOR_3 = 0.075 ether;
/**
* @dev See {IPunkCrushers-PRICE_PER_TOKEN_FOR_5}.
*/
uint256 public constant override PRICE_PER_TOKEN_FOR_5 = 0.065 ether;
/**
* @dev See {IPunkCrushers-PRICE_PER_TOKEN_FOR_10}.
*/
uint256 public constant override PRICE_PER_TOKEN_FOR_10 = 0.055 ether;
/**
* @dev See {IPunkCrushers-PRICE_PER_TOKEN_FOR_20}.
*/
uint256 public constant override PRICE_PER_TOKEN_FOR_20 = 0.045 ether;
/**
* @dev See {IPunkCrushers-presaleActive}.
*/
bool public override presaleActive = true;
/**
* @dev See {IPunkCrushers-dev}.
*/
address public override dev;
/**
* @dev Sets {dev}, {_initialBaseURI} and {ERC721-constructor}.
*/
constructor(address _dev, string memory _initialBaseURI)
ERC721("Punk Crushers", "PKCS")
{
_baseTokenURI = _initialBaseURI;
dev = _dev;
}
/**
* @dev See {IPunkCrushers-baseURI}.
*/
function baseURI() public view override returns (string memory) {
return _baseURI();
}
/**
* @dev See {IPunkCrushers-tokenExists}.
*/
function tokenExists(uint256 _tokenId) public view override returns (bool) {
return _exists(_tokenId);
}
/**
* @dev See {IPunkCrushers-tokensPrice}.
*/
function tokensPrice(uint256 _noOfTokens)
public
pure
override
returns (uint256)
{
if (_noOfTokens == 3) return _noOfTokens * PRICE_PER_TOKEN_FOR_3;
if (_noOfTokens == 5) return _noOfTokens * PRICE_PER_TOKEN_FOR_5;
if (_noOfTokens == 10) return _noOfTokens * PRICE_PER_TOKEN_FOR_10;
if (_noOfTokens == 20) return _noOfTokens * PRICE_PER_TOKEN_FOR_20;
return _noOfTokens * PRICE_PER_TOKEN_FOR_1;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 _tokenId)
public
view
virtual
override
returns (string memory)
{
super.tokenURI(_tokenId);
return
(bytes(baseURI()).length > 0)
? string(
abi.encodePacked(baseURI(), _tokenId.toString(), ".json")
)
: "";
}
/**
* @dev See {IPunkCrushers-presaleMint}.
*
* Emits a {NFTMinted} event indicating the mint of a new NFT.
*
* @param _noOfTokens - no of tokens `caller` wants to mint.
*
* Requirements:
*
* - presale must be active.
* - `_noOfTokens` must be less than 20.
*/
function presaleMint(uint256 _noOfTokens) public payable override {
require(presaleActive, "PresaleMint: presale inactive");
require(_noOfTokens <= 20, "PresaleMint: max 20 per transaction");
_mint(_noOfTokens, msg.value);
}
/**
* @dev See {IPunkCrushers-mint}.
*
* Emits a {NFTMinted} event indicating the mint of a new NFT.
*
* @param _noOfTokens - no of tokens `caller` wants to mint.
*
* Requirements:
*
* - `_noOfTokens` must be less than 10.
*/
function mint(uint256 _noOfTokens) public payable override {
require(_noOfTokens <= 10, "Mint: max 10 per transaction");
_mint(_noOfTokens, msg.value);
}
/**
* @dev See {IPunkCrushers-reserveTokens}.
*
* Emits a {NFTMinted} event indicating the mint of a new NFT.
*
* @param _noOfTokens - no of tokens {owner} wants to mint.
*
* Requirements:
*
* - `_noOfTokens` must be less than 30.
* - caller must be {owner}.
*/
function reserveTokens(uint256 _noOfTokens) public override onlyOwner {
require(_noOfTokens <= 30, "ReserveTokens: max 30 per transaction");
_supplyValidator(_noOfTokens);
for (uint8 i = 0; i < _noOfTokens; i++) {
// incrementing by 1
_tokenIdTracker.increment();
uint256 _tokenId = _tokenIdTracker.current();
// mint nft
_safeMint(_msgSender(), _tokenId);
emit NFTMinted(_tokenId, _msgSender());
}
}
/**
* @dev See {IPunkCrushers-togglePresale}.
*
* Requirements:
*
* - caller must be {owner}.
*/
function togglePresale() public override onlyOwner {
presaleActive = !presaleActive;
}
/**
* @dev See {IPunkCrushers-setBaseURI}.
*
* Emits a {BaseURIUpdated} event indicating change of {baseURI}.
*
* @param _newBaseTokenURI - new base URI string.
*
* Requirements:
* - `_newBaseTokenURI` must be in format: "ipfs://{hash}/"
* - `_noOfTokens` must be less than 30.
* - caller must be {owner}.
*/
function setBaseURI(string memory _newBaseTokenURI)
public
override
onlyOwner
{
require(
!_uriUpdated,
"setBaseURI: uri cannot be updated more than once"
);
_baseTokenURI = _newBaseTokenURI;
_uriUpdated = true;
emit BaseURIUpdated(_newBaseTokenURI);
}
/**
* @dev Internal function called in {presaleMint} and {mint}.
* mints tokens and transfers to `caller`.
*
* Emits a {FundsTransferred} event indicating transfer of funds.
*
* @param _noOfTokens - no of tokens {owner} wants to mint.
* @param _value - ether price paid for token minting.
*
* Requirements:
* - {totalSupply} must not max out {MAX_SUPPLY}.
* - `_value` must be equal to correct tokenPrice.
*/
function _mint(uint256 _noOfTokens, uint256 _value) internal {
_supplyValidator(_noOfTokens);
require(_value == tokensPrice(_noOfTokens), "Mint: invalid price");
for (uint256 i = 0; i < _noOfTokens; i++) {
// incrementing
_tokenIdTracker.increment();
uint256 _tokenId = _tokenIdTracker.current();
// mint nft
_safeMint(_msgSender(), _tokenId);
emit NFTMinted(_tokenId, _msgSender());
}
// transfer funds to owner and dev
_transferFunds(_value);
}
/**
* @dev Internal function called in {_mint} and {reserveTokens}.
*
* @param _noOfTokens - no of tokens `caller` wants to mint.
*
* Requirements:
* - {totalSupply} must not max out {MAX_SUPPLY}.
*/
function _supplyValidator(uint256 _noOfTokens) internal view {
require(
totalSupply() + _noOfTokens <= MAX_SUPPLY,
"SupplyValidator: max limit reached"
);
}
/**
* @dev Internal function called in {_mint}.
* transfers funds to {owner} and {dev}.
*
* Emits a {FundsTransferred} event indicating transfer of funds.
*
* @param _value - ether price paid for token minting.
*/
function _transferFunds(uint256 _value) internal {
address payable _owner = payable(owner());
uint256 _ownerShare = (_value * 70) / 100;
Address.sendValue(_owner, _ownerShare);
emit FundsTransferred(_owner, _ownerShare);
address payable _dev = payable(dev);
uint256 _devShare = (_value * 30) / 100;
Address.sendValue(_dev, _devShare);
emit FundsTransferred(_dev, _devShare);
}
/**
* @dev See {ERC721-_baseURI}
*
*/
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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;
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.9;
/**
* @dev Interface of the PunkCrushers.
* @author Ahmed Ali Bhatti <github.com/ahmedali8>
*/
interface IPunkCrushers {
/**
* @dev Emitted when `baseURI` is changed.
*/
event BaseURIUpdated(string baseURI);
/**
* @dev Emitted when a new token is minted.
*/
event NFTMinted(uint256 indexed tokenId, address indexed beneficiary);
/**
* @dev Emitted when `amount` ether are send to `beneficiary`.
*/
event FundsTransferred(address indexed beneficiary, uint256 amount);
/**
* @dev Returns the max allowed supply i.e. 10,000.
*/
function MAX_SUPPLY() external view returns (uint256);
/**
* @dev Returns the price per token if `1` token is to be minted.
*/
function PRICE_PER_TOKEN_FOR_1() external view returns (uint256);
/**
* @dev Returns the price per token if `3` tokens is to be minted.
*/
function PRICE_PER_TOKEN_FOR_3() external view returns (uint256);
/**
* @dev Returns the price per token if `5` tokens is to be minted.
*/
function PRICE_PER_TOKEN_FOR_5() external view returns (uint256);
/**
* @dev Returns the price per token if `10` tokens is to be minted.
*/
function PRICE_PER_TOKEN_FOR_10() external view returns (uint256);
/**
* @dev Returns the price per token if `20` tokens is to be minted.
*
* Note: only for {presaleMint}.
*/
function PRICE_PER_TOKEN_FOR_20() external view returns (uint256);
/**
* @dev Returns bool flag if presale is active or not.
*/
function presaleActive() external view returns (bool);
/**
* @dev Returns the address of {dev}.
*/
function dev() external view returns (address);
/**
* @dev Returns the string value of {baseURI}.
*/
function baseURI() external view returns (string calldata);
/**
* @dev Returns bool flag is token exists.
*/
function tokenExists(uint256 _tokenId) external view returns (bool);
/**
* @dev Returns the price for `_noOfTokens`.
*/
function tokensPrice(uint256 _noOfTokens) external pure returns (uint256);
/**
* @dev Mints `_noOfTokens` and transfers to `caller`.
*
* Note:
* - that only callable if {presaleActive} is true.
* - that only 20 NFTs can be minted per transaction.
*
* Emits a {NFTMinted} and {FundsTransferred} events.
*/
function presaleMint(uint256 _noOfTokens) external payable;
/**
* @dev Mints `_noOfTokens` and transfers to `caller`.
*
* Note: that only 10 NFTs can be minted per transaction.
*
* Emits a {NFTMinted} and {FundsTransferred} events.
*/
function mint(uint256 _noOfTokens) external payable;
/**
* @dev Reserves/Mints `_noOfTokens` and transfers to `owner`.
*
* Note
* - that caller must be {owner}.
* - that only 30 NFTs can be minted per transaction.
*
* Emits a {NFTMinted} and {FundsTransferred} events.
*/
function reserveTokens(uint256 _noOfTokens) external;
/**
* @dev Toggles presale active or inactive.
*
* Note that caller must be {owner}.
*/
function togglePresale() external;
/**
* @dev Sets {baseURI} to `_newBaseTokenURI`.
*
* Note
* - `_newBaseTokenURI` must be in format: "ipfs://{hash}/"
* - that caller must be {owner}.
* - that only callable once.
*
* Emits a {BaseURIUpdated} event.
*/
function setBaseURI(string calldata _newBaseTokenURI) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../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 "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
| * @dev See {IPunkCrushers-presaleMint}. Emits a {NFTMinted} event indicating the mint of a new NFT. @param _noOfTokens - no of tokens `caller` wants to mint. Requirements: - presale must be active. - `_noOfTokens` must be less than 20./ | function presaleMint(uint256 _noOfTokens) public payable override {
require(presaleActive, "PresaleMint: presale inactive");
require(_noOfTokens <= 20, "PresaleMint: max 20 per transaction");
_mint(_noOfTokens, msg.value);
}
| 1,494,189 | [
1,
9704,
288,
2579,
1683,
12893,
1218,
414,
17,
12202,
5349,
49,
474,
5496,
7377,
1282,
279,
288,
50,
4464,
49,
474,
329,
97,
871,
11193,
326,
312,
474,
434,
279,
394,
423,
4464,
18,
225,
389,
2135,
951,
5157,
300,
1158,
434,
2430,
1375,
16140,
68,
14805,
358,
312,
474,
18,
29076,
30,
300,
4075,
5349,
1297,
506,
2695,
18,
300,
1375,
67,
2135,
951,
5157,
68,
1297,
506,
5242,
2353,
4200,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4075,
5349,
49,
474,
12,
11890,
5034,
389,
2135,
951,
5157,
13,
1071,
8843,
429,
3849,
288,
203,
3639,
2583,
12,
12202,
5349,
3896,
16,
315,
12236,
5349,
49,
474,
30,
4075,
5349,
16838,
8863,
203,
3639,
2583,
24899,
2135,
951,
5157,
1648,
4200,
16,
315,
12236,
5349,
49,
474,
30,
943,
4200,
1534,
2492,
8863,
203,
203,
3639,
389,
81,
474,
24899,
2135,
951,
5157,
16,
1234,
18,
1132,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.6.0;
// import Ownable.sol
import "./Ownable.sol";
// import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol";
// import "./github/OpenZeppelin/openzeppelin-contracts/contracts/access/Ownable.sol";
// import SafeMath.sol
// import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol";
// import "./github/OpenZeppelin/openzeppelin-contracts/contracts/math/SafeMath.sol";
import "./SafeMath.sol";
//import Roles.sol
// import "https://github.com/hiddentao/openzeppelin-solidity/blob/master/contracts/access/Roles.sol";
import "./Roles.sol";
contract MunicipalityWasteTaxesRBAC is Ownable {
// to be able to use the functions defined inside the Roles and SafeMath libraries we need to use the `using` keyword
// use SafemMath for uints and integers
using SafeMath for uint;
using SafeMath for int;
// use Roles for Role. Roles is the name of the library while Role is the name of the struct defined there
using Roles for Roles.Role;
// define the roles we will use in this contract. We make them private so that outsiders cannot easily read their content
// create a role for citizens
Roles.Role private citizenRole;
// create a role for garbage collectors
Roles.Role private garbageCollectorRole;
// create a role for the person managing the municipality. This role will be the equivalent of the admin
Roles.Role private municipalityManagers;
// add a contructor that will allow us to set the initial admin, otherwise we will not be able to assign any other role
// the constructor will be called only once when the contract is deployed by the municipality
constructor() public {
// give the deployer of this contract the role of municipality manager
// add() is a function defined inside the Roles library and can be used on instances of Roles.Role
municipalityManagers.add(msg.sender);
}
// create a function to give some addresses the role of citizens. This function will take an ethereum address as input
// this function will be private, so it will be possible to call it only inside this contract
function _addCitizenRole(address _newCitizen) private {
citizenRole.add(_newCitizen);
}
// create a function to give some specific addresses the role of garbage collectors. This function will take an ethereum address as input
// only addresses having the municipalityManagers role will be able to call this function
function _addGarbageCollectorRole(address _newGarbageCollector) private onlyMunicipalityManager() {
garbageCollectorRole.add(_newGarbageCollector);
}
// initially we can assume that the municipality is managed by a single address but this may not always be the case so
// we also create a function to give some other addresses the role of municipality.
// This function will take again an ethereum address as input
// only addresses already having the municipalityRole will be able to call this function
function _addMunicipalityManager(address _newMunicipalityManager) external onlyMunicipalityManager() {
municipalityManagers.add(_newMunicipalityManager);
}
// create a function to remove an address from the citizenRole
// only addresses having the municipalityManagers role will be able to call this function
function _removeCitizenRole(address _oldCitizen) external onlyMunicipalityManager() {
// remove() is a function defined inside the Roles library and can be used on instances of Roles.Role
citizenRole.remove(_oldCitizen);
}
// create a function to remove an address from the garbageCollectorRole
// only addresses having the municipalityManagers role will be able to call this function
function _removeGarbageCollectorRole(address _oldGarbageCollector) external onlyMunicipalityManager() {
garbageCollectorRole.remove(_oldGarbageCollector);
}
// create a function to remove an address from the municipalityManagers role
// only addresses already having the municipalityManagers role will be able to call this function
function _removeMunicipalityManagers(address _oldMunicipalityManagers) external onlyMunicipalityManager() {
municipalityManagers.remove(_oldMunicipalityManagers);
}
// define a modifier than makes sure that only addresses with the municipalityManagers role can call some sensitive functions
modifier onlyMunicipalityManager() {
// check that the address calling a function is a municipalityManagers otherwise raise an error
// to do so we can use the has() function defined inside the Roles library
// that returns true if an address has a specific role and false otherwise
require(municipalityManagers.has(msg.sender) == true, "Must have the municipalityManagers permission!");
// if the above requirement is satisfied continue with the function call
_;
}
// define a modifier than makes sure that only addresses with the garbageCollectorRole can call some functions
modifier onlyGarbageCollector() {
// check that the address calling a function has the garbageCollectorRole otherwise raise an error
require(garbageCollectorRole.has(msg.sender) == true, "Must have the garbageCollectorRole permission!");
// if the above requirement is satisfied continue with the function call
_;
}
// define a modifier than makes sure that only addresses with the citizenRole can call some functions
modifier onlyCitizenRole() {
// check that the address calling a function has the citizenRole otherwise raise an error
require(citizenRole.has(msg.sender) == true, "Must have the citizenRole permission!");
// if the above requirement is satisfied continue with the function call
_;
}
// create a modifier to check whether a citizen has already paid the deposit
// the idea is that only a citizen who already paid the deposit should be able to generate a trash bag
modifier isDepositPaid() {
// check whether the citizen has already paid the deposit otherwise raise raise an error
require(citizens[msg.sender].paidDeposit == true, "You have to pay the deposit before you can continue!");
_;
}
// create a modifier to check whether a citizen has already paid the deposit
// this time the idea is that only a citizen who has not already paid the deposit should be allowed to pay it
// it's basically the opposite of the isDepositPaid() modifier
modifier canIPayDeposit() {
// check whether the citizen has not paid the deposit otherwise raise raise an error
require(citizens[msg.sender].paidDeposit == false, "You have to pay the deposit before you can continue!");
_;
}
// create a modifier so that people cannot call the addCitizen() function twice
modifier isntCitizenYet() {
// check if the addressExists field of the citizen calling this function is false
require(citizens[msg.sender].addressExists == false);
_;
}
// declare variables that will be stored in the blockchain
// declare the initial deposit the every citizen will have to pay
// for now we set it to approximately 1/10 ETH ~ 50 €
uint constant deposit = 1 * 10 ** 17 wei;
// since we defined `deposit` as a unit we cannot subtract it from the amount of taxes due by a citizen when he actually pays the deposit
// therefore we also decleare the negative of the deposit as a int to be used for that specific computation
int constant negativeDeposit = - 1 * 10 ** 17 wei;
// declare a mapping that contains many instances of Citizen. As a key we need to use something that is specific
// to the singular citizen so we can use either the ethereum address of the citizen or the fiscalCode
// for now we decided to use the ethereum address
// this mapping will be called citizens
mapping(address => Citizen) citizens;
// create a struct where to store data regarding the individual citizens
struct Citizen {
// adding the address here is redundant
// address citizenAddress; // the ethereum address of the citizen, uniquely identifies a citizen
// we don't really need the fiscal code
// string fiscalCode; // this variable can also uniquely identify each citizen
// maybe its better to use bytes32 data type for this variable.
bool paidDeposit; // checks whether the citizen paid the deposit or not
// we can add a check to make sure the citizen paid the deposit during the current year
int taxesDue; // the amount of taxes the citizen needs to pay to the Municipality
// since each citizen pays an initial deposit this number can also be negative
uint totalRecyclableWaste; // keep track of the recycable waste produced the particular citizen
uint totalNonRecyclableWaste; // keep track of the unrecycable waste produced the particular citizen
uint trashBagCount; // how many trash bags the citizen produced so far. This is not used to keep track of how many
// trash bags the citizen produced because it will eventually overflow. Instead, it's used
// as a component to compute the unique id of each trash bag
bool addressExists; // we will use this variable to make sure citizens can call the addCitizen() function only once
// if we look up an address in the citizens mapping that was not previusly added this variable
// will be false by default so that
}
// create a function to instantiate citizens and add them to the citizens mapping
// it will be external so that it can be called from outside this contract
// anyone will be able to call this function and will be assigned the citizenRole by default
// however every citizen should be allowed to call this function only once
function addCitizen() external isntCitizenYet() {
// create an instance of Citizen and pass the variables explicitely
Citizen memory citizen = Citizen({
// OLD: citizenAddress: msg.sender, // the address calling this function will be saved as the citizenAddress
// OLD: fiscalCode: _fiscalCode, // set the fiscalCode to the one provided by the citizen
paidDeposit: false, // initially set the paidDeposit variable to false
taxesDue: 0, // initially set taxesDue to 0
totalRecyclableWaste: 0,
totalNonRecyclableWaste: 0,
trashBagCount: 0, // start the trash bag count to zero
addressExists: true // set the value to true so that when we look up this address we know it was created
});
// add the instance of Citizen we just created to the mapping containing all the instances of citizens that is saved on the blockchain.
// as the key of the mapping we use the ethereum address of the citizen and the value associated with it
// is the instance itself of the Citizen struct we just created
citizens[msg.sender] = citizen;
// OLD: citizens[citizen.citizenAddress] = citizen;
// give the caller of this function the citizenRole
_addCitizenRole(msg.sender);
}
// create a function that can be called by individual citizens in order to pay the initial deposit.
// To do so, it will need to be external and payable
// the amount will be sent to this contract that is owned by the municipality
// the isDepositPaid() modifier makes sure that a citizen pays the deposit only once
// {potentially expand it so that one citizen can pay the deposit of another citizen}
function payDeposit() external payable canIPayDeposit() {
// make sure that the amount sent using this function is at least equal to the deposit required (1/10 ETH)
// otherwise revert the transaction
// the value sent can be accessed using msg.value
if(msg.value >= deposit){
// change the paidDeposit variable of the citizen who paid the deposit to true
citizens[msg.sender].paidDeposit = true;
// remove the deposit from the taxesDue by this citizen. WARNING: SafaMath only works with uint256 so we cannot use it here
citizens[msg.sender].taxesDue += negativeDeposit;
} else {
// revert the transaction
revert("The amount you are sending is not enough to cover the deposit");
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// TRASH BAGS MANAGEMENT
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// NEW ADDITIONS
// create an enum to define the type of waste in a given trash bag
// initially we will include types such as Nonrecyclable, Paper, Palstic, Organic, Glass but it can be easily expanded
enum WasteType {Nonrecyclable, Paper, Plastic, Organic, Glass} //lifecycle of the trash bag
// We cannot trust that citizens will tell the truth about the type of waste their are putting out
// indeed, they will always have incentives to say that the type is anything other than `Unkown` or `Nonrecyclable`
struct Truck {
uint totWeight;
uint depositedStation;
WasteType wasteType;
}
mapping(address => Truck) trucks;
function addTruck(address _newTruck, WasteType _wasteType) external onlyMunicipalityManager() {
Truck memory myTruck = Truck(0, 0, _wasteType);
trucks[_newTruck] = myTruck;
_addGarbageCollectorRole(_newTruck);
}
// Struct to define the gps coordinates of a station. Since latitudes and longitudes are floats (with 13 numbers after the dot),
// we basically store the information about latitude and longitude by multiplying the respective values by the variable SCALE = 10**13
uint256 private constant SCALE = 10 ** 13;
struct Station {
int latitude;
int longitude;
WasteType allowedWasteType;
}
// Mapping of stations defined by the municipality
mapping (address => Station) stations;
Roles.Role private disposalStationRole;
function _addDisposalStationRole(address _newDisposalStation) private onlyMunicipalityManager() {
disposalStationRole.add(_newDisposalStation);
}
function _removeDisposalStationRole(address _oldDisposalStation) private onlyMunicipalityManager() {
disposalStationRole.remove(_oldDisposalStation);
}
function addStation(address _newStation, int _latitude, int _longitude, WasteType _wasteType) external onlyMunicipalityManager() {
Station memory myStation = Station(_latitude, _longitude, _wasteType);
stations[_newStation] = myStation;
_addDisposalStationRole(_newStation);
}
modifier onlyDisposalStationRole() {
// check that the address calling a function has the disposalStationRole otherwise raise an error
require(disposalStationRole.has(msg.sender) == true, "Must have the disposalStationRole permission!");
// if the above requirement is satisfied continue with the function call
_;
}
// creates events for each possible state to be communicated outside the chain
// each event will communicate to the external world the unique id of the trash bag and other relevant information
// because of the scalability issues we decided to take an approach based on events.
// the first event communicates that the trash bag has been collected.
// in particular it logs the ethereum address of the citizen who generated the trash bag,
// the ethereum address of the garbage collector, the time in which the trash bag was picked up, the weight of the trash bag
// and the type of waste it contains
event PickedUp(address transporter, WasteType wasteType, bytes32 bagId, address generator, uint wasteWeight, uint pickUpTime);
// the second event communicates that the disposal plant received the trashbag
event Deposited(address transporter, WasteType wasteType, uint totWeight, address disposalPlant);
event Received(address disposalStation, address transporter);
// create a function to compute the unique id of each bag
// to get a unique id for a trash bag we can take the hash of the address of the citizen who generated the bag, the time in which
// it was generated and the number of bags generated by that citizen.
// Since we will pass the necessary data as parameters it wil be a pure function
function _computeUniqueIdTrashBag(address _generator, uint _pickUpTime, uint _trashBagCount) private pure returns(bytes32) {
// return the hash of the address who generated the trash bag, the time in which the bag was generated
// and the number of bash the citizen generated so far
// in order to pass elements of different tyoe into the keccak256 function we first need to call abi.encodePacked()
return keccak256(abi.encodePacked(_generator, _pickUpTime, _trashBagCount));
}
// create a function only addresses having the garbageCollectorRole can call
// We assume that this function is able to read from a sensor present on the trash bag the ethereum address of the citizen who generated it
// Moreover, it will get the weight of the trash bag while the garbage collector checks its content (plastic, paper, organic)
// Then, it will increase either the totalNonRecyclableWaste or totalRecyclableWaste field of the citizen who generated the trash bag
// Finally it will emit an event containing all the previous information plus the ethereum address of the garbage collector
function pickFromBin(address _generator, uint _wasteWeight) external onlyGarbageCollector() {
// create placeholder for the arguments the function takes as input
// these variables will be stored in memory and not on the blockchain
//address generator;
//uint wasteWeight;
//WasteType wasteType;
// assign the values to the placeholders created above
//generator = _generator;
//wasteWeight = _wasteWeight;
//wasteType = _wasteType;
// this variable is not stored on the blockchain but will be used when emitting the event
bytes32 uniqueBagId;
// compute the uniqueBagId using the function defined above
uniqueBagId = _computeUniqueIdTrashBag(_generator, now, citizens[_generator].trashBagCount);
// Type of waste the truck is carrying
WasteType _wasteType = trucks[msg.sender].wasteType;
// Increase the total weight that the truck is carrying
trucks[msg.sender].totWeight = trucks[msg.sender].totWeight.add(_wasteWeight);
// if the WasteType of the trash bag is Nonrecyclable, increment the totalNonRecyclableWaste field of the citizen by the weight of trash bag
if(_wasteType == WasteType.Nonrecyclable){
//citizens[_generator].totalNonRecyclableWaste += _wasteWeight;
// ideally we would use the SafeMath method .add() for this addition
citizens[_generator].totalNonRecyclableWaste.add(_wasteWeight);
} else {
// increment the totalRecyclableWaste field of the citizen by the weight of trash bag
//citizens[_generator].totalRecyclableWaste += wasteWeight;
// ideally we would use the SafeMath method .add() for this addition
citizens[_generator].totalRecyclableWaste.add(_wasteWeight);
}
// emit the PickedUp event containing the information regarding the citizen who generated the trash bag, the address of the
// garbage collector, the time in which the trash bas was collected, its weight and its type
emit PickedUp(msg.sender, _wasteType, uniqueBagId, _generator, _wasteWeight, now);
}
function dropAtStation(address _disposalStation, int _latitudeTruck, int _longitudeTruck) external onlyGarbageCollector() {
//check gps coordinates
require(stations[_disposalStation].latitude == _latitudeTruck && stations[_disposalStation].longitude == _longitudeTruck, "You are in the worng place!");
// check WasteType
require(trucks[msg.sender].wasteType == stations[_disposalStation].allowedWasteType, "You are at the wrong station!");
emit Deposited(msg.sender, trucks[msg.sender].wasteType, trucks[msg.sender].totWeight, _disposalStation);
trucks[msg.sender].depositedStation = trucks[msg.sender].totWeight;
trucks[msg.sender].totWeight = 0;
}
function receivedWaste(uint _wasteReceived, address _truck) external onlyDisposalStationRole() {
require(_wasteReceived == trucks[_truck].depositedStation, "the truck is fooling you!");
trucks[_truck].depositedStation = 0;
emit Received(msg.sender, _truck);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// create a function that returns the total amount of money sent to this contract by a citizen
// since it does not modify the data it will be a view function
function getTotalTaxesPaid() external view onlyMunicipalityManager() returns(uint) {
return address(this).balance;
}
// create a function to check the balance of taxes due by a citizen so far
// since it does not modify any data it will be a view function
function getTaxesDue() external view returns(int) {
// we assume that the address calling this function is the oen of the citizen itself
return citizens[msg.sender].taxesDue;
}
// create some functions to access the variables inside the struct of a citizen
// create functions to check if you paid the deposit
function didIPayDeposit() external view returns(bool) {
return citizens[msg.sender].paidDeposit;
}
// create a function to check the amount of recyclabe waste you produced so far
function getAmountRecyclableWaste() external view returns (uint) {
return citizens[msg.sender].totalRecyclableWaste;
}
// create a function to check the amount of non-recyclabe waste you produced so far
function getAmountNonRecyclableWaste() external view returns (uint) {
return citizens[msg.sender].totalNonRecyclableWaste;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// OLD FUNCTIONS AND IDEAS
// get the fiscal code
// function getFiscalCode() external view returns(string) {
// return citizens[msg.sender].fiscalCode;
// }
// // create a function that modify the totalRecyclableWaste associate with a citizen
// // since totalRecyclableWaste directly affect the taxes that a citizen will pay,
// // only the people managing the municipality should be able to call it
// // to achieve this we can use the onlyMunicipalityManager modifier we defined above
// function _addRecyclableWaste () private onlyMunicipalityManager() {
// }
// create an enum to define the state in which a trashbag can be found
// enum TrashBagState {ToPickUp, PickedUp, Deposited} //lifecycle of the trash bag
// create an instance of TrashBagState that in which the state is set to `ToPickUp`
// TrashBagState constant defaultTrashBagState = TrashBagState.ToPickUp;
////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
// POTENTIAL EXPANSIONS
// create a function that can be executed only by the owner of the contract (the unicipality itself in our case)
// at the end of the year that sets the paidDeposit field for every citizen to false
////////////////////////////////////////////////////////////////////////////////////////////////////////
}
| emit the PickedUp event containing the information regarding the citizen who generated the trash bag, the address of the garbage collector, the time in which the trash bas was collected, its weight and its type | emit PickedUp(msg.sender, _wasteType, uniqueBagId, _generator, _wasteWeight, now);
| 12,812,183 | [
1,
18356,
326,
23038,
329,
1211,
871,
4191,
326,
1779,
29012,
326,
276,
305,
452,
275,
10354,
4374,
326,
20703,
13189,
16,
326,
1758,
434,
326,
15340,
8543,
16,
326,
813,
316,
1492,
326,
20703,
2580,
1703,
12230,
16,
2097,
3119,
471,
2097,
618,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
3626,
23038,
329,
1211,
12,
3576,
18,
15330,
16,
389,
91,
14725,
559,
16,
3089,
5013,
548,
16,
389,
8812,
16,
389,
91,
14725,
6544,
16,
2037,
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
] |
// SPDX-License-Identifier: AGPL-3.0-only
/*
Distributor.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.8.11;
import "@openzeppelin/contracts/utils/introspection/IERC1820Registry.sol";
import "@openzeppelin/contracts/token/ERC777/IERC777Recipient.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@skalenetwork/skale-manager-interfaces/delegation/IDistributor.sol";
import "@skalenetwork/skale-manager-interfaces/delegation/IValidatorService.sol";
import "@skalenetwork/skale-manager-interfaces/delegation/IDelegationController.sol";
import "@skalenetwork/skale-manager-interfaces/delegation/ITimeHelpers.sol";
import "../Permissions.sol";
import "../ConstantsHolder.sol";
import "../utils/MathUtils.sol";
/**
* @title Distributor
* @dev This contract handles all distribution functions of bounty and fee
* payments.
*/
contract Distributor is Permissions, IERC777Recipient, IDistributor {
using MathUtils for uint;
IERC1820Registry private _erc1820;
// validatorId => month => token
mapping (uint => mapping (uint => uint)) private _bountyPaid;
// validatorId => month => token
mapping (uint => mapping (uint => uint)) private _feePaid;
// holder => validatorId => month
mapping (address => mapping (uint => uint)) private _firstUnwithdrawnMonth;
// validatorId => month
mapping (uint => uint) private _firstUnwithdrawnMonthForValidator;
/**
* @dev Return and update the amount of earned bounty from a validator.
*/
function getAndUpdateEarnedBountyAmount(uint validatorId) external override returns (uint earned, uint endMonth) {
return getAndUpdateEarnedBountyAmountOf(msg.sender, validatorId);
}
/**
* @dev Allows msg.sender to withdraw earned bounty. Bounties are locked
* until launchTimestamp and BOUNTY_LOCKUP_MONTHS have both passed.
*
* Emits a {WithdrawBounty} event.
*
* Requirements:
*
* - Bounty must be unlocked.
*/
function withdrawBounty(uint validatorId, address to) external override {
ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers"));
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
require(block.timestamp >= timeHelpers.addMonths(
constantsHolder.launchTimestamp(),
constantsHolder.BOUNTY_LOCKUP_MONTHS()
), "Bounty is locked");
uint bounty;
uint endMonth;
(bounty, endMonth) = getAndUpdateEarnedBountyAmountOf(msg.sender, validatorId);
_firstUnwithdrawnMonth[msg.sender][validatorId] = endMonth;
IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken"));
require(skaleToken.transfer(to, bounty), "Failed to transfer tokens");
emit WithdrawBounty(
msg.sender,
validatorId,
to,
bounty
);
}
/**
* @dev Allows `msg.sender` to withdraw earned validator fees. Fees are
* locked until launchTimestamp and BOUNTY_LOCKUP_MONTHS both have passed.
*
* Emits a {WithdrawFee} event.
*
* Requirements:
*
* - Fee must be unlocked.
*/
function withdrawFee(address to) external override {
IValidatorService validatorService = IValidatorService(contractManager.getContract("ValidatorService"));
IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken"));
ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers"));
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
require(block.timestamp >= timeHelpers.addMonths(
constantsHolder.launchTimestamp(),
constantsHolder.BOUNTY_LOCKUP_MONTHS()
), "Fee is locked");
// check Validator Exist inside getValidatorId
uint validatorId = validatorService.getValidatorId(msg.sender);
uint fee;
uint endMonth;
(fee, endMonth) = getEarnedFeeAmountOf(validatorId);
_firstUnwithdrawnMonthForValidator[validatorId] = endMonth;
require(skaleToken.transfer(to, fee), "Failed to transfer tokens");
emit WithdrawFee(
validatorId,
to,
fee
);
}
function tokensReceived(
address,
address,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata
)
external
override
allow("SkaleToken")
{
require(to == address(this), "Receiver is incorrect");
require(userData.length == 32, "Data length is incorrect");
uint validatorId = abi.decode(userData, (uint));
_distributeBounty(amount, validatorId);
}
/**
* @dev Return the amount of earned validator fees of `msg.sender`.
*/
function getEarnedFeeAmount() external view override returns (uint earned, uint endMonth) {
IValidatorService validatorService = IValidatorService(contractManager.getContract("ValidatorService"));
return getEarnedFeeAmountOf(validatorService.getValidatorId(msg.sender));
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
_erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
_erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this));
}
/**
* @dev Return and update the amount of earned bounties.
*/
function getAndUpdateEarnedBountyAmountOf(address wallet, uint validatorId)
public
override
returns (uint earned, uint endMonth)
{
IDelegationController delegationController = IDelegationController(
contractManager.getContract("DelegationController"));
ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers"));
uint currentMonth = timeHelpers.getCurrentMonth();
uint startMonth = _firstUnwithdrawnMonth[wallet][validatorId];
if (startMonth == 0) {
startMonth = delegationController.getFirstDelegationMonth(wallet, validatorId);
if (startMonth == 0) {
return (0, 0);
}
}
earned = 0;
endMonth = currentMonth;
if (endMonth > startMonth + 12) {
endMonth = startMonth + 12;
}
for (uint i = startMonth; i < endMonth; ++i) {
uint effectiveDelegatedToValidator =
delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, i);
if (effectiveDelegatedToValidator.muchGreater(0)) {
earned = earned +
_bountyPaid[validatorId][i] *
delegationController.getAndUpdateEffectiveDelegatedByHolderToValidator(wallet, validatorId, i) /
effectiveDelegatedToValidator;
}
}
}
/**
* @dev Return the amount of earned fees by validator ID.
*/
function getEarnedFeeAmountOf(uint validatorId) public view override returns (uint earned, uint endMonth) {
ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers"));
uint currentMonth = timeHelpers.getCurrentMonth();
uint startMonth = _firstUnwithdrawnMonthForValidator[validatorId];
if (startMonth == 0) {
return (0, 0);
}
earned = 0;
endMonth = currentMonth;
if (endMonth > startMonth + 12) {
endMonth = startMonth + 12;
}
for (uint i = startMonth; i < endMonth; ++i) {
earned = earned + _feePaid[validatorId][i];
}
}
// private
/**
* @dev Distributes bounties to delegators.
*
* Emits a {BountyWasPaid} event.
*/
function _distributeBounty(uint amount, uint validatorId) private {
ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers"));
IValidatorService validatorService = IValidatorService(contractManager.getContract("ValidatorService"));
uint currentMonth = timeHelpers.getCurrentMonth();
uint feeRate = validatorService.getValidator(validatorId).feeRate;
uint fee = amount * feeRate / 1000;
uint bounty = amount - fee;
_bountyPaid[validatorId][currentMonth] = _bountyPaid[validatorId][currentMonth] + bounty;
_feePaid[validatorId][currentMonth] = _feePaid[validatorId][currentMonth] + fee;
if (_firstUnwithdrawnMonthForValidator[validatorId] == 0) {
_firstUnwithdrawnMonthForValidator[validatorId] = currentMonth;
}
emit BountyWasPaid(validatorId, amount);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC1820Registry.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the global ERC1820 Registry, as defined in the
* https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register
* implementers for interfaces in this registry, as well as query support.
*
* Implementers may be shared by multiple accounts, and can also implement more
* than a single interface for each account. Contracts can implement interfaces
* for themselves, but externally-owned accounts (EOA) must delegate this to a
* contract.
*
* {IERC165} interfaces can also be queried via the registry.
*
* For an in-depth explanation and source code analysis, see the EIP text.
*/
interface IERC1820Registry {
/**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/
function setManager(address account, address newManager) external;
/**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/
function getManager(address account) external view returns (address);
/**
* @dev Sets the `implementer` contract as ``account``'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
* - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function setInterfaceImplementer(
address account,
bytes32 _interfaceHash,
address implementer
) external;
/**
* @dev Returns the implementer of `interfaceHash` for `account`. If no such
* implementer is registered, returns the zero address.
*
* If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/
function getInterfaceImplementer(address account, bytes32 _interfaceHash) external view returns (address);
/**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
/**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/
function updateERC165Cache(address account, bytes4 interfaceId) external;
/**
* @notice Checks whether a contract implements an ERC165 interface or not.
* If the result is not cached a direct lookup on the contract address is performed.
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
* {updateERC165Cache} with the contract address.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
/**
* @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
event ManagerChanged(address indexed account, address indexed newManager);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC777/IERC777Recipient.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC777TokensRecipient standard as defined in the EIP.
*
* Accounts can be notified of {IERC777} tokens being sent to them by having a
* contract implement this interface (contract holders can be their own
* implementer) and registering it on the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
*
* See {IERC1820Registry} and {ERC1820Implementer}.
*/
interface IERC777Recipient {
/**
* @dev Called by an {IERC777} token contract whenever tokens are being
* moved or created into a registered account (`to`). The type of operation
* is conveyed by `from` being the zero address or not.
*
* This call occurs _after_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the post-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
// 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: AGPL-3.0-only
/*
IDistributor.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 IDistributor {
/**
* @dev Emitted when bounty is withdrawn.
*/
event WithdrawBounty(
address holder,
uint validatorId,
address destination,
uint amount
);
/**
* @dev Emitted when a validator fee is withdrawn.
*/
event WithdrawFee(
uint validatorId,
address destination,
uint amount
);
/**
* @dev Emitted when bounty is distributed.
*/
event BountyWasPaid(
uint validatorId,
uint amount
);
function getAndUpdateEarnedBountyAmount(uint validatorId) external returns (uint earned, uint endMonth);
function withdrawBounty(uint validatorId, address to) external;
function withdrawFee(address to) external;
function getAndUpdateEarnedBountyAmountOf(address wallet, uint validatorId)
external
returns (uint earned, uint endMonth);
function getEarnedFeeAmount() external view returns (uint earned, uint endMonth);
function getEarnedFeeAmountOf(uint validatorId) external view returns (uint earned, uint endMonth);
}
// 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
/*
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
/*
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
/*
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
/*
ConstantsHolder.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/IConstantsHolder.sol";
import "./Permissions.sol";
/**
* @title ConstantsHolder
* @dev Contract contains constants and common variables for the SKALE Network.
*/
contract ConstantsHolder is Permissions, IConstantsHolder {
// initial price for creating Node (100 SKL)
uint public constant NODE_DEPOSIT = 100 * 1e18;
uint8 public constant TOTAL_SPACE_ON_NODE = 128;
// part of Node for Small Skale-chain (1/128 of Node)
uint8 public constant SMALL_DIVISOR = 128;
// part of Node for Medium Skale-chain (1/32 of Node)
uint8 public constant MEDIUM_DIVISOR = 32;
// part of Node for Large Skale-chain (full Node)
uint8 public constant LARGE_DIVISOR = 1;
// part of Node for Medium Test Skale-chain (1/4 of Node)
uint8 public constant MEDIUM_TEST_DIVISOR = 4;
// typically number of Nodes for Skale-chain (16 Nodes)
uint public constant NUMBER_OF_NODES_FOR_SCHAIN = 16;
// number of Nodes for Test Skale-chain (2 Nodes)
uint public constant NUMBER_OF_NODES_FOR_TEST_SCHAIN = 2;
// number of Nodes for Test Skale-chain (4 Nodes)
uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4;
// number of seconds in one year
uint32 public constant SECONDS_TO_YEAR = 31622400;
// initial number of monitors
uint public constant NUMBER_OF_MONITORS = 24;
uint public constant OPTIMAL_LOAD_PERCENTAGE = 80;
uint public constant ADJUSTMENT_SPEED = 1000;
uint public constant COOLDOWN_TIME = 60;
uint public constant MIN_PRICE = 10**6;
uint public constant MSR_REDUCING_COEFFICIENT = 2;
uint public constant DOWNTIME_THRESHOLD_PART = 30;
uint public constant BOUNTY_LOCKUP_MONTHS = 2;
uint public constant ALRIGHT_DELTA = 134161;
uint public constant BROADCAST_DELTA = 177490;
uint public constant COMPLAINT_BAD_DATA_DELTA = 80995;
uint public constant PRE_RESPONSE_DELTA = 100061;
uint public constant COMPLAINT_DELTA = 104611;
uint public constant RESPONSE_DELTA = 49132;
// MSR - Minimum staking requirement
uint public msr;
// Reward period - 30 days (each 30 days Node would be granted for bounty)
uint32 public rewardPeriod;
// Allowable latency - 150000 ms by default
uint32 public allowableLatency;
/**
* Delta period - 1 hour (1 hour before Reward period became Monitors need
* to send Verdicts and 1 hour after Reward period became Node need to come
* and get Bounty)
*/
uint32 public deltaPeriod;
/**
* Check time - 2 minutes (every 2 minutes monitors should check metrics
* from checked nodes)
*/
uint public checkTime;
//Need to add minimal allowed parameters for verdicts
uint public launchTimestamp;
uint public rotationDelay;
uint public proofOfUseLockUpPeriodDays;
uint public proofOfUseDelegationPercentage;
uint public limitValidatorsPerDelegator;
uint256 public firstDelegationsMonth; // deprecated
// date when schains will be allowed for creation
uint public schainCreationTimeStamp;
uint public minimalSchainLifetime;
uint public complaintTimeLimit;
bytes32 public constant CONSTANTS_HOLDER_MANAGER_ROLE = keccak256("CONSTANTS_HOLDER_MANAGER_ROLE");
modifier onlyConstantsHolderManager() {
require(hasRole(CONSTANTS_HOLDER_MANAGER_ROLE, msg.sender), "CONSTANTS_HOLDER_MANAGER_ROLE is required");
_;
}
/**
* @dev Allows the Owner to set new reward and delta periods
* This function is only for tests.
*/
function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external override onlyConstantsHolderManager {
require(
newRewardPeriod >= newDeltaPeriod && newRewardPeriod - newDeltaPeriod >= checkTime,
"Incorrect Periods"
);
emit ConstantUpdated(
keccak256(abi.encodePacked("RewardPeriod")),
uint(rewardPeriod),
uint(newRewardPeriod)
);
rewardPeriod = newRewardPeriod;
emit ConstantUpdated(
keccak256(abi.encodePacked("DeltaPeriod")),
uint(deltaPeriod),
uint(newDeltaPeriod)
);
deltaPeriod = newDeltaPeriod;
}
/**
* @dev Allows the Owner to set the new check time.
* This function is only for tests.
*/
function setCheckTime(uint newCheckTime) external override onlyConstantsHolderManager {
require(rewardPeriod - deltaPeriod >= checkTime, "Incorrect check time");
emit ConstantUpdated(
keccak256(abi.encodePacked("CheckTime")),
uint(checkTime),
uint(newCheckTime)
);
checkTime = newCheckTime;
}
/**
* @dev Allows the Owner to set the allowable latency in milliseconds.
* This function is only for testing purposes.
*/
function setLatency(uint32 newAllowableLatency) external override onlyConstantsHolderManager {
emit ConstantUpdated(
keccak256(abi.encodePacked("AllowableLatency")),
uint(allowableLatency),
uint(newAllowableLatency)
);
allowableLatency = newAllowableLatency;
}
/**
* @dev Allows the Owner to set the minimum stake requirement.
*/
function setMSR(uint newMSR) external override onlyConstantsHolderManager {
emit ConstantUpdated(
keccak256(abi.encodePacked("MSR")),
uint(msr),
uint(newMSR)
);
msr = newMSR;
}
/**
* @dev Allows the Owner to set the launch timestamp.
*/
function setLaunchTimestamp(uint timestamp) external override onlyConstantsHolderManager {
require(
block.timestamp < launchTimestamp,
"Cannot set network launch timestamp because network is already launched"
);
emit ConstantUpdated(
keccak256(abi.encodePacked("LaunchTimestamp")),
uint(launchTimestamp),
uint(timestamp)
);
launchTimestamp = timestamp;
}
/**
* @dev Allows the Owner to set the node rotation delay.
*/
function setRotationDelay(uint newDelay) external override onlyConstantsHolderManager {
emit ConstantUpdated(
keccak256(abi.encodePacked("RotationDelay")),
uint(rotationDelay),
uint(newDelay)
);
rotationDelay = newDelay;
}
/**
* @dev Allows the Owner to set the proof-of-use lockup period.
*/
function setProofOfUseLockUpPeriod(uint periodDays) external override onlyConstantsHolderManager {
emit ConstantUpdated(
keccak256(abi.encodePacked("ProofOfUseLockUpPeriodDays")),
uint(proofOfUseLockUpPeriodDays),
uint(periodDays)
);
proofOfUseLockUpPeriodDays = periodDays;
}
/**
* @dev Allows the Owner to set the proof-of-use delegation percentage
* requirement.
*/
function setProofOfUseDelegationPercentage(uint percentage) external override onlyConstantsHolderManager {
require(percentage <= 100, "Percentage value is incorrect");
emit ConstantUpdated(
keccak256(abi.encodePacked("ProofOfUseDelegationPercentage")),
uint(proofOfUseDelegationPercentage),
uint(percentage)
);
proofOfUseDelegationPercentage = percentage;
}
/**
* @dev Allows the Owner to set the maximum number of validators that a
* single delegator can delegate to.
*/
function setLimitValidatorsPerDelegator(uint newLimit) external override onlyConstantsHolderManager {
emit ConstantUpdated(
keccak256(abi.encodePacked("LimitValidatorsPerDelegator")),
uint(limitValidatorsPerDelegator),
uint(newLimit)
);
limitValidatorsPerDelegator = newLimit;
}
function setSchainCreationTimeStamp(uint timestamp) external override onlyConstantsHolderManager {
emit ConstantUpdated(
keccak256(abi.encodePacked("SchainCreationTimeStamp")),
uint(schainCreationTimeStamp),
uint(timestamp)
);
schainCreationTimeStamp = timestamp;
}
function setMinimalSchainLifetime(uint lifetime) external override onlyConstantsHolderManager {
emit ConstantUpdated(
keccak256(abi.encodePacked("MinimalSchainLifetime")),
uint(minimalSchainLifetime),
uint(lifetime)
);
minimalSchainLifetime = lifetime;
}
function setComplaintTimeLimit(uint timeLimit) external override onlyConstantsHolderManager {
emit ConstantUpdated(
keccak256(abi.encodePacked("ComplaintTimeLimit")),
uint(complaintTimeLimit),
uint(timeLimit)
);
complaintTimeLimit = timeLimit;
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
msr = 0;
rewardPeriod = 2592000;
allowableLatency = 150000;
deltaPeriod = 3600;
checkTime = 300;
launchTimestamp = type(uint).max;
rotationDelay = 12 hours;
proofOfUseLockUpPeriodDays = 90;
proofOfUseDelegationPercentage = 50;
limitValidatorsPerDelegator = 20;
firstDelegationsMonth = 0;
complaintTimeLimit = 1800;
}
}
// 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
/*
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);
}
}
}
}
// 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);
} | * @dev Allows the Owner to set the maximum number of validators that a single delegator can delegate to./ | function setLimitValidatorsPerDelegator(uint newLimit) external override onlyConstantsHolderManager {
emit ConstantUpdated(
keccak256(abi.encodePacked("LimitValidatorsPerDelegator")),
uint(limitValidatorsPerDelegator),
uint(newLimit)
);
limitValidatorsPerDelegator = newLimit;
}
| 268,432 | [
1,
19132,
326,
16837,
358,
444,
326,
4207,
1300,
434,
11632,
716,
279,
2202,
11158,
639,
848,
7152,
358,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
444,
3039,
19420,
2173,
15608,
639,
12,
11890,
394,
3039,
13,
3903,
3849,
1338,
2918,
6064,
1318,
288,
203,
3639,
3626,
10551,
7381,
12,
203,
5411,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
2932,
3039,
19420,
2173,
15608,
639,
7923,
3631,
203,
5411,
2254,
12,
3595,
19420,
2173,
15608,
639,
3631,
203,
5411,
2254,
12,
2704,
3039,
13,
203,
3639,
11272,
203,
3639,
1800,
19420,
2173,
15608,
639,
273,
394,
3039,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.0;
contract LandRegistry {
// event for new re
event NewRegistration(string landId, address owner, uint256 timestamp);
event NewRegistrationFailed(string landId, address owner, uint256 timestamp);
event OwnershipTransferred(string landId, address owner, address receiver, uint256 timestamp);
event OwnershipTransferFailed(string landId, address owner, address receiver, uint256 timestamp);
event BuyRequest(string requestId, string landId, address requester, address owner, uint256 amount, uint256 timestamp);
event BuyRequestFailed(string requestId, string landId, address requester, address owner, uint256 amount, uint256 timestamp);
event AcceptBuyRequest(string requestId, address acceptor, uint256 timestamp);
event AcceptBuyRequestFailed(string requestId, address acceptor, uint256 timestamp);
event Withdrawal(string requestId, address withdrawer, uint256 timestamp);
event WithdrawalFailed(string requestId, address withdrawer, uint256 timestamp);
event Transfer(string requestId, uint256 timestamp);
event TransferFailed(string requestId, uint256 timestamp);
// struct for buy request of land
struct Buy {
string landId;
address payable buyer;
address payable owner;
uint requestPlacedTimestamp;
uint256 amount;
bool buyerOK;
bool ownerOK;
bool closed;
}
// registrar is the authorized person to transfer land
address public registrar;
// owner of the land
mapping(string => address payable) owner;
// buy order from buyer for the land
mapping(string => Buy) buyOrder;
// modifier to check address is null or not
modifier notNullAddress(address someAddress) {
require(someAddress != address(0));
_;
}
// modifier to check message sender in null or nut
modifier onlyRegistrar {
require(msg.sender == registrar);
_;
}
// constructor of the contract which initialized the registrar
constructor(address _registrar) public notNullAddress (msg.sender) {
registrar = _registrar;
}
// function to register the new land using land id and the owner address by only the authorized person registrar
function register(string memory landId, address payable _owner) public onlyRegistrar notNullAddress(_owner) {
if (owner[landId] != address(0)) { // new registration failed if land already exists
emit NewRegistrationFailed(landId, _owner, now);
} else {
owner[landId] = _owner;
emit NewRegistration(landId, _owner, now); // new registration event
}
}
// internal function to transfer the land from old owner to new owner by the registrar of the land office
function transfer(string memory landId, address payable oldOwner, address payable newOwner) internal notNullAddress(oldOwner) notNullAddress(newOwner) returns (bool) {
if (owner[landId] == oldOwner) {
emit OwnershipTransferred(landId, owner[landId], newOwner, now);
owner[landId] = newOwner;
return true;
} else {
emit OwnershipTransferFailed(landId, owner[landId], newOwner, now);
}
return false;
}
// function to place buy order of a land and deposit some amount in the contract
function buyRequest(string memory requestId, string memory landId) public payable notNullAddress(msg.sender) {
if (owner[landId] != address(0)) {
buyOrder[requestId] = Buy(landId, msg.sender, owner[landId], now, msg.value, true, false, false);
emit BuyRequest(requestId, landId, msg.sender, owner[landId], msg.value, now);
} else {
emit BuyRequestFailed(requestId, landId, msg.sender, owner[landId], msg.value, now);
}
}
// function where land owner agrees on a land buy request
function acceptBuyRequest(string memory requestId) public notNullAddress(msg.sender) {
Buy storage buy = buyOrder[requestId];
if (msg.sender == owner[buy.landId] && owner[buy.landId] == buy.owner) {
if(!buy.closed) {
buy.ownerOK = true;
emit AcceptBuyRequest(requestId, msg.sender, now);
return;
}
}
emit AcceptBuyRequestFailed(requestId, msg.sender, now);
}
// function to withdraw the amount from the buy request of the land by the buyer
function withdrawBuyRequest(string memory requestId) public notNullAddress(msg.sender) {
Buy storage buy = buyOrder[requestId];
if (msg.sender == buy.buyer && !buy.closed) {
buy.closed = true;
buy.buyer.transfer(buy.amount);
emit Withdrawal(requestId, msg.sender, now);
} else {
emit WithdrawalFailed(requestId, msg.sender, now);
}
}
// function to transfer, if both owner and buyer are ok by the registrar of the land office
function transfer(string memory requestId) public onlyRegistrar {
Buy storage buy = buyOrder[requestId];
if (!buy.closed && buy.buyerOK && buy.ownerOK) {
buy.closed = true;
emit Transfer(requestId, now);
if(transfer(buy.landId, buy.owner, buy.buyer)) {
buy.owner.transfer(buy.amount);
}
} else {
emit TransferFailed(requestId, now);
}
}
// function to get owner of the land id
function getOwner(string memory landId) public view returns (address) {
return owner[landId];
}
// function to get details of the land buy order request
function getBuyOrder(string memory requestId) public view returns (string memory, address, address, uint256, uint256, bool, bool, bool) {
Buy storage buy = buyOrder[requestId];
return (buy.landId, buy.owner, buy.buyer, buy.requestPlacedTimestamp, buy.amount, buy.buyerOK, buy.ownerOK, buy.closed);
}
} | modifier to check message sender in null or nut | modifier onlyRegistrar {
require(msg.sender == registrar);
_;
}
| 2,550,642 | [
1,
20597,
358,
866,
883,
5793,
316,
446,
578,
290,
322,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
9606,
1338,
30855,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
17450,
297,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2020-02-11
*/
// File: @aragon/os/contracts/common/EtherTokenConstant.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
// aragonOS and aragon-apps rely on address(0) to denote native ETH, in
// contracts where both tokens and ETH are accepted
contract EtherTokenConstant {
address internal constant ETH = address(0);
}
// File: @aragon/apps-agent/contracts/standards/ERC1271.sol
pragma solidity 0.4.24;
// ERC1271 on Feb 12th, 2019: https://github.com/ethereum/EIPs/blob/a97dc434930d0ccc4461c97d8c7a920dc585adf2/EIPS/eip-1271.md
// Using `isValidSignature(bytes32,bytes)` even though the standard still hasn't been modified
// Rationale: https://github.com/ethereum/EIPs/issues/1271#issuecomment-462719728
contract ERC1271 {
bytes4 constant public ERC1271_INTERFACE_ID = 0xfb855dc9; // this.isValidSignature.selector
bytes4 constant public ERC1271_RETURN_VALID_SIGNATURE = 0x20c13b0b; // TODO: Likely needs to be updated
bytes4 constant public ERC1271_RETURN_INVALID_SIGNATURE = 0x00000000;
/**
* @dev Function must be implemented by deriving contract
* @param _hash Arbitrary length data signed on the behalf of address(this)
* @param _signature Signature byte array associated with _data
* @return A bytes4 magic value 0x20c13b0b if the signature check passes, 0x00000000 if not
*
* MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)
* MUST allow external calls
*/
function isValidSignature(bytes32 _hash, bytes memory _signature) public view returns (bytes4);
function returnIsValidSignatureMagicNumber(bool isValid) internal pure returns (bytes4) {
return isValid ? ERC1271_RETURN_VALID_SIGNATURE : ERC1271_RETURN_INVALID_SIGNATURE;
}
}
contract ERC1271Bytes is ERC1271 {
/**
* @dev Default behavior of `isValidSignature(bytes,bytes)`, can be overloaded for custom validation
* @param _data Arbitrary length data signed on the behalf of address(this)
* @param _signature Signature byte array associated with _data
* @return A bytes4 magic value 0x20c13b0b if the signature check passes, 0x00000000 if not
*
* MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)
* MUST allow external calls
*/
function isValidSignature(bytes _data, bytes _signature) public view returns (bytes4) {
return isValidSignature(keccak256(_data), _signature);
}
}
// File: @aragon/apps-agent/contracts/SignatureValidator.sol
pragma solidity 0.4.24;
// Inspired by https://github.com/horizon-games/multi-token-standard/blob/319740cf2a78b8816269ae49a09c537b3fd7303b/contracts/utils/SignatureValidator.sol
// This should probably be moved into aOS: https://github.com/aragon/aragonOS/pull/442
library SignatureValidator {
enum SignatureMode {
Invalid, // 0x00
EIP712, // 0x01
EthSign, // 0x02
ERC1271, // 0x03
NMode // 0x04, to check if mode is specified, leave at the end
}
// bytes4(keccak256("isValidSignature(bytes,bytes)")
bytes4 public constant ERC1271_RETURN_VALID_SIGNATURE = 0x20c13b0b;
uint256 internal constant ERC1271_ISVALIDSIG_MAX_GAS = 250000;
string private constant ERROR_INVALID_LENGTH_POP_BYTE = "SIGVAL_INVALID_LENGTH_POP_BYTE";
/// @dev Validates that a hash was signed by a specified signer.
/// @param hash Hash which was signed.
/// @param signer Address of the signer.
/// @param signature ECDSA signature along with the mode (0 = Invalid, 1 = EIP712, 2 = EthSign, 3 = ERC1271) {mode}{r}{s}{v}.
/// @return Returns whether signature is from a specified user.
function isValidSignature(bytes32 hash, address signer, bytes signature) internal view returns (bool) {
if (signature.length == 0) {
return false;
}
uint8 modeByte = uint8(signature[0]);
if (modeByte >= uint8(SignatureMode.NMode)) {
return false;
}
SignatureMode mode = SignatureMode(modeByte);
if (mode == SignatureMode.EIP712) {
return ecVerify(hash, signer, signature);
} else if (mode == SignatureMode.EthSign) {
return ecVerify(
keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)),
signer,
signature
);
} else if (mode == SignatureMode.ERC1271) {
// Pop the mode byte before sending it down the validation chain
return safeIsValidSignature(signer, hash, popFirstByte(signature));
} else {
return false;
}
}
function ecVerify(bytes32 hash, address signer, bytes memory signature) private pure returns (bool) {
(bool badSig, bytes32 r, bytes32 s, uint8 v) = unpackEcSig(signature);
if (badSig) {
return false;
}
return signer == ecrecover(hash, v, r, s);
}
function unpackEcSig(bytes memory signature) private pure returns (bool badSig, bytes32 r, bytes32 s, uint8 v) {
if (signature.length != 66) {
badSig = true;
return;
}
v = uint8(signature[65]);
assembly {
r := mload(add(signature, 33))
s := mload(add(signature, 65))
}
// Allow signature version to be 0 or 1
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
badSig = true;
}
}
function popFirstByte(bytes memory input) private pure returns (bytes memory output) {
uint256 inputLength = input.length;
require(inputLength > 0, ERROR_INVALID_LENGTH_POP_BYTE);
output = new bytes(inputLength - 1);
if (output.length == 0) {
return output;
}
uint256 inputPointer;
uint256 outputPointer;
assembly {
inputPointer := add(input, 0x21)
outputPointer := add(output, 0x20)
}
memcpy(outputPointer, inputPointer, output.length);
}
function safeIsValidSignature(address validator, bytes32 hash, bytes memory signature) private view returns (bool) {
bytes memory data = abi.encodeWithSelector(ERC1271(validator).isValidSignature.selector, hash, signature);
bytes4 erc1271Return = safeBytes4StaticCall(validator, data, ERC1271_ISVALIDSIG_MAX_GAS);
return erc1271Return == ERC1271_RETURN_VALID_SIGNATURE;
}
function safeBytes4StaticCall(address target, bytes data, uint256 maxGas) private view returns (bytes4 ret) {
uint256 gasLeft = gasleft();
uint256 callGas = gasLeft > maxGas ? maxGas : gasLeft;
bool ok;
assembly {
ok := staticcall(callGas, target, add(data, 0x20), mload(data), 0, 0)
}
if (!ok) {
return;
}
uint256 size;
assembly { size := returndatasize }
if (size != 32) {
return;
}
assembly {
let ptr := mload(0x40) // get next free memory ptr
returndatacopy(ptr, 0, size) // copy return from above `staticcall`
ret := mload(ptr) // read data at ptr and set it to be returned
}
return ret;
}
// From: https://github.com/Arachnid/solidity-stringutils/blob/01e955c1d6/src/strings.sol
function memcpy(uint256 dest, uint256 src, uint256 len) private pure {
// Copy word-length chunks while possible
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
}
// File: @aragon/apps-agent/contracts/standards/IERC165.sol
pragma solidity 0.4.24;
interface IERC165 {
function supportsInterface(bytes4 interfaceId) external pure returns (bool);
}
// File: @aragon/os/contracts/common/UnstructuredStorage.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
library UnstructuredStorage {
function getStorageBool(bytes32 position) internal view returns (bool data) {
assembly { data := sload(position) }
}
function getStorageAddress(bytes32 position) internal view returns (address data) {
assembly { data := sload(position) }
}
function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) {
assembly { data := sload(position) }
}
function getStorageUint256(bytes32 position) internal view returns (uint256 data) {
assembly { data := sload(position) }
}
function setStorageBool(bytes32 position, bool data) internal {
assembly { sstore(position, data) }
}
function setStorageAddress(bytes32 position, address data) internal {
assembly { sstore(position, data) }
}
function setStorageBytes32(bytes32 position, bytes32 data) internal {
assembly { sstore(position, data) }
}
function setStorageUint256(bytes32 position, uint256 data) internal {
assembly { sstore(position, data) }
}
}
// File: @aragon/os/contracts/acl/IACL.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
interface IACL {
function initialize(address permissionsCreator) external;
// TODO: this should be external
// See https://github.com/ethereum/solidity/issues/4832
function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
}
// File: @aragon/os/contracts/common/IVaultRecoverable.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
interface IVaultRecoverable {
event RecoverToVault(address indexed vault, address indexed token, uint256 amount);
function transferToVault(address token) external;
function allowRecoverability(address token) external view returns (bool);
function getRecoveryVault() external view returns (address);
}
// File: @aragon/os/contracts/kernel/IKernel.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
interface IKernelEvents {
event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app);
}
// This should be an interface, but interfaces can't inherit yet :(
contract IKernel is IKernelEvents, IVaultRecoverable {
function acl() public view returns (IACL);
function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
function setApp(bytes32 namespace, bytes32 appId, address app) public;
function getApp(bytes32 namespace, bytes32 appId) public view returns (address);
}
// File: @aragon/os/contracts/apps/AppStorage.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract AppStorage {
using UnstructuredStorage for bytes32;
/* Hardcoded constants to save gas
bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel");
bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId");
*/
bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b;
bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b;
function kernel() public view returns (IKernel) {
return IKernel(KERNEL_POSITION.getStorageAddress());
}
function appId() public view returns (bytes32) {
return APP_ID_POSITION.getStorageBytes32();
}
function setKernel(IKernel _kernel) internal {
KERNEL_POSITION.setStorageAddress(address(_kernel));
}
function setAppId(bytes32 _appId) internal {
APP_ID_POSITION.setStorageBytes32(_appId);
}
}
// File: @aragon/os/contracts/acl/ACLSyntaxSugar.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract ACLSyntaxSugar {
function arr() internal pure returns (uint256[]) {
return new uint256[](0);
}
function arr(bytes32 _a) internal pure returns (uint256[] r) {
return arr(uint256(_a));
}
function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b));
}
function arr(address _a) internal pure returns (uint256[] r) {
return arr(uint256(_a));
}
function arr(address _a, address _b) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b));
}
function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) {
return arr(uint256(_a), _b, _c);
}
function arr(address _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) {
return arr(uint256(_a), _b, _c, _d);
}
function arr(address _a, uint256 _b) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b));
}
function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b), _c, _d, _e);
}
function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b), uint256(_c));
}
function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b), uint256(_c));
}
function arr(uint256 _a) internal pure returns (uint256[] r) {
r = new uint256[](1);
r[0] = _a;
}
function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) {
r = new uint256[](2);
r[0] = _a;
r[1] = _b;
}
function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) {
r = new uint256[](3);
r[0] = _a;
r[1] = _b;
r[2] = _c;
}
function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) {
r = new uint256[](4);
r[0] = _a;
r[1] = _b;
r[2] = _c;
r[3] = _d;
}
function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) {
r = new uint256[](5);
r[0] = _a;
r[1] = _b;
r[2] = _c;
r[3] = _d;
r[4] = _e;
}
}
contract ACLHelpers {
function decodeParamOp(uint256 _x) internal pure returns (uint8 b) {
return uint8(_x >> (8 * 30));
}
function decodeParamId(uint256 _x) internal pure returns (uint8 b) {
return uint8(_x >> (8 * 31));
}
function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) {
a = uint32(_x);
b = uint32(_x >> (8 * 4));
c = uint32(_x >> (8 * 8));
}
}
// File: @aragon/os/contracts/common/Uint256Helpers.sol
pragma solidity ^0.4.24;
library Uint256Helpers {
uint256 private constant MAX_UINT64 = uint64(-1);
string private constant ERROR_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG";
function toUint64(uint256 a) internal pure returns (uint64) {
require(a <= MAX_UINT64, ERROR_NUMBER_TOO_BIG);
return uint64(a);
}
}
// File: @aragon/os/contracts/common/TimeHelpers.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract TimeHelpers {
using Uint256Helpers for uint256;
/**
* @dev Returns the current block number.
* Using a function rather than `block.number` allows us to easily mock the block number in
* tests.
*/
function getBlockNumber() internal view returns (uint256) {
return block.number;
}
/**
* @dev Returns the current block number, converted to uint64.
* Using a function rather than `block.number` allows us to easily mock the block number in
* tests.
*/
function getBlockNumber64() internal view returns (uint64) {
return getBlockNumber().toUint64();
}
/**
* @dev Returns the current timestamp.
* Using a function rather than `block.timestamp` allows us to easily mock it in
* tests.
*/
function getTimestamp() internal view returns (uint256) {
return block.timestamp; // solium-disable-line security/no-block-members
}
/**
* @dev Returns the current timestamp, converted to uint64.
* Using a function rather than `block.timestamp` allows us to easily mock it in
* tests.
*/
function getTimestamp64() internal view returns (uint64) {
return getTimestamp().toUint64();
}
}
// File: @aragon/os/contracts/common/Initializable.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract Initializable is TimeHelpers {
using UnstructuredStorage for bytes32;
// keccak256("aragonOS.initializable.initializationBlock")
bytes32 internal constant INITIALIZATION_BLOCK_POSITION = 0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e;
string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED";
string private constant ERROR_NOT_INITIALIZED = "INIT_NOT_INITIALIZED";
modifier onlyInit {
require(getInitializationBlock() == 0, ERROR_ALREADY_INITIALIZED);
_;
}
modifier isInitialized {
require(hasInitialized(), ERROR_NOT_INITIALIZED);
_;
}
/**
* @return Block number in which the contract was initialized
*/
function getInitializationBlock() public view returns (uint256) {
return INITIALIZATION_BLOCK_POSITION.getStorageUint256();
}
/**
* @return Whether the contract has been initialized by the time of the current block
*/
function hasInitialized() public view returns (bool) {
uint256 initializationBlock = getInitializationBlock();
return initializationBlock != 0 && getBlockNumber() >= initializationBlock;
}
/**
* @dev Function to be called by top level contract after initialization has finished.
*/
function initialized() internal onlyInit {
INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber());
}
/**
* @dev Function to be called by top level contract after initialization to enable the contract
* at a future block number rather than immediately.
*/
function initializedAt(uint256 _blockNumber) internal onlyInit {
INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber);
}
}
// File: @aragon/os/contracts/common/Petrifiable.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract Petrifiable is Initializable {
// Use block UINT256_MAX (which should be never) as the initializable date
uint256 internal constant PETRIFIED_BLOCK = uint256(-1);
function isPetrified() public view returns (bool) {
return getInitializationBlock() == PETRIFIED_BLOCK;
}
/**
* @dev Function to be called by top level contract to prevent being initialized.
* Useful for freezing base contracts when they're used behind proxies.
*/
function petrify() internal onlyInit {
initializedAt(PETRIFIED_BLOCK);
}
}
// File: @aragon/os/contracts/common/Autopetrified.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract Autopetrified is Petrifiable {
constructor() public {
// Immediately petrify base (non-proxy) instances of inherited contracts on deploy.
// This renders them uninitializable (and unusable without a proxy).
petrify();
}
}
// File: @aragon/os/contracts/common/ConversionHelpers.sol
pragma solidity ^0.4.24;
library ConversionHelpers {
string private constant ERROR_IMPROPER_LENGTH = "CONVERSION_IMPROPER_LENGTH";
function dangerouslyCastUintArrayToBytes(uint256[] memory _input) internal pure returns (bytes memory output) {
// Force cast the uint256[] into a bytes array, by overwriting its length
// Note that the bytes array doesn't need to be initialized as we immediately overwrite it
// with the input and a new length. The input becomes invalid from this point forward.
uint256 byteLength = _input.length * 32;
assembly {
output := _input
mstore(output, byteLength)
}
}
function dangerouslyCastBytesToUintArray(bytes memory _input) internal pure returns (uint256[] memory output) {
// Force cast the bytes array into a uint256[], by overwriting its length
// Note that the uint256[] doesn't need to be initialized as we immediately overwrite it
// with the input and a new length. The input becomes invalid from this point forward.
uint256 intsLength = _input.length / 32;
require(_input.length == intsLength * 32, ERROR_IMPROPER_LENGTH);
assembly {
output := _input
mstore(output, intsLength)
}
}
}
// File: @aragon/os/contracts/common/ReentrancyGuard.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract ReentrancyGuard {
using UnstructuredStorage for bytes32;
/* Hardcoded constants to save gas
bytes32 internal constant REENTRANCY_MUTEX_POSITION = keccak256("aragonOS.reentrancyGuard.mutex");
*/
bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb;
string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL";
modifier nonReentrant() {
// Ensure mutex is unlocked
require(!REENTRANCY_MUTEX_POSITION.getStorageBool(), ERROR_REENTRANT);
// Lock mutex before function call
REENTRANCY_MUTEX_POSITION.setStorageBool(true);
// Perform function call
_;
// Unlock mutex after function call
REENTRANCY_MUTEX_POSITION.setStorageBool(false);
}
}
// File: @aragon/os/contracts/lib/token/ERC20.sol
// See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.4.24;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function allowance(address _owner, address _spender)
public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
function approve(address _spender, uint256 _value)
public returns (bool);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: @aragon/os/contracts/common/IsContract.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract IsContract {
/*
* NOTE: this should NEVER be used for authentication
* (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize).
*
* This is only intended to be used as a sanity check that an address is actually a contract,
* RATHER THAN an address not being a contract.
*/
function isContract(address _target) internal view returns (bool) {
if (_target == address(0)) {
return false;
}
uint256 size;
assembly { size := extcodesize(_target) }
return size > 0;
}
}
// File: @aragon/os/contracts/common/SafeERC20.sol
// Inspired by AdEx (https://github.com/AdExNetwork/adex-protocol-eth/blob/b9df617829661a7518ee10f4cb6c4108659dd6d5/contracts/libs/SafeERC20.sol)
// and 0x (https://github.com/0xProject/0x-monorepo/blob/737d1dc54d72872e24abce5a1dbe1b66d35fa21a/contracts/protocol/contracts/protocol/AssetProxy/ERC20Proxy.sol#L143)
pragma solidity ^0.4.24;
library SafeERC20 {
// Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`:
// https://github.com/ethereum/solidity/issues/3544
bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb;
string private constant ERROR_TOKEN_BALANCE_REVERTED = "SAFE_ERC_20_BALANCE_REVERTED";
string private constant ERROR_TOKEN_ALLOWANCE_REVERTED = "SAFE_ERC_20_ALLOWANCE_REVERTED";
function invokeAndCheckSuccess(address _addr, bytes memory _calldata)
private
returns (bool)
{
bool ret;
assembly {
let ptr := mload(0x40) // free memory pointer
let success := call(
gas, // forward all gas
_addr, // address
0, // no value
add(_calldata, 0x20), // calldata start
mload(_calldata), // calldata length
ptr, // write output over free memory
0x20 // uint256 return
)
if gt(success, 0) {
// Check number of bytes returned from last function call
switch returndatasize
// No bytes returned: assume success
case 0 {
ret := 1
}
// 32 bytes returned: check if non-zero
case 0x20 {
// Only return success if returned data was true
// Already have output in ptr
ret := eq(mload(ptr), 1)
}
// Not sure what was returned: don't mark as success
default { }
}
}
return ret;
}
function staticInvoke(address _addr, bytes memory _calldata)
private
view
returns (bool, uint256)
{
bool success;
uint256 ret;
assembly {
let ptr := mload(0x40) // free memory pointer
success := staticcall(
gas, // forward all gas
_addr, // address
add(_calldata, 0x20), // calldata start
mload(_calldata), // calldata length
ptr, // write output over free memory
0x20 // uint256 return
)
if gt(success, 0) {
ret := mload(ptr)
}
}
return (success, ret);
}
/**
* @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false).
* Note that this makes an external call to the token.
*/
function safeTransfer(ERC20 _token, address _to, uint256 _amount) internal returns (bool) {
bytes memory transferCallData = abi.encodeWithSelector(
TRANSFER_SELECTOR,
_to,
_amount
);
return invokeAndCheckSuccess(_token, transferCallData);
}
/**
* @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false).
* Note that this makes an external call to the token.
*/
function safeTransferFrom(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) {
bytes memory transferFromCallData = abi.encodeWithSelector(
_token.transferFrom.selector,
_from,
_to,
_amount
);
return invokeAndCheckSuccess(_token, transferFromCallData);
}
/**
* @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false).
* Note that this makes an external call to the token.
*/
function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) {
bytes memory approveCallData = abi.encodeWithSelector(
_token.approve.selector,
_spender,
_amount
);
return invokeAndCheckSuccess(_token, approveCallData);
}
/**
* @dev Static call into ERC20.balanceOf().
* Reverts if the call fails for some reason (should never fail).
*/
function staticBalanceOf(ERC20 _token, address _owner) internal view returns (uint256) {
bytes memory balanceOfCallData = abi.encodeWithSelector(
_token.balanceOf.selector,
_owner
);
(bool success, uint256 tokenBalance) = staticInvoke(_token, balanceOfCallData);
require(success, ERROR_TOKEN_BALANCE_REVERTED);
return tokenBalance;
}
/**
* @dev Static call into ERC20.allowance().
* Reverts if the call fails for some reason (should never fail).
*/
function staticAllowance(ERC20 _token, address _owner, address _spender) internal view returns (uint256) {
bytes memory allowanceCallData = abi.encodeWithSelector(
_token.allowance.selector,
_owner,
_spender
);
(bool success, uint256 allowance) = staticInvoke(_token, allowanceCallData);
require(success, ERROR_TOKEN_ALLOWANCE_REVERTED);
return allowance;
}
}
// File: @aragon/os/contracts/common/VaultRecoverable.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract VaultRecoverable is IVaultRecoverable, EtherTokenConstant, IsContract {
using SafeERC20 for ERC20;
string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED";
string private constant ERROR_VAULT_NOT_CONTRACT = "RECOVER_VAULT_NOT_CONTRACT";
string private constant ERROR_TOKEN_TRANSFER_FAILED = "RECOVER_TOKEN_TRANSFER_FAILED";
/**
* @notice Send funds to recovery Vault. This contract should never receive funds,
* but in case it does, this function allows one to recover them.
* @param _token Token balance to be sent to recovery vault.
*/
function transferToVault(address _token) external {
require(allowRecoverability(_token), ERROR_DISALLOWED);
address vault = getRecoveryVault();
require(isContract(vault), ERROR_VAULT_NOT_CONTRACT);
uint256 balance;
if (_token == ETH) {
balance = address(this).balance;
vault.transfer(balance);
} else {
ERC20 token = ERC20(_token);
balance = token.staticBalanceOf(this);
require(token.safeTransfer(vault, balance), ERROR_TOKEN_TRANSFER_FAILED);
}
emit RecoverToVault(vault, _token, balance);
}
/**
* @dev By default deriving from AragonApp makes it recoverable
* @param token Token address that would be recovered
* @return bool whether the app allows the recovery
*/
function allowRecoverability(address token) public view returns (bool) {
return true;
}
// Cast non-implemented interface to be public so we can use it internally
function getRecoveryVault() public view returns (address);
}
// File: @aragon/os/contracts/evmscript/IEVMScriptExecutor.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
interface IEVMScriptExecutor {
function execScript(bytes script, bytes input, address[] blacklist) external returns (bytes);
function executorType() external pure returns (bytes32);
}
// File: @aragon/os/contracts/evmscript/IEVMScriptRegistry.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract EVMScriptRegistryConstants {
/* Hardcoded constants to save gas
bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = apmNamehash("evmreg");
*/
bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = 0xddbcfd564f642ab5627cf68b9b7d374fb4f8a36e941a75d89c87998cef03bd61;
}
interface IEVMScriptRegistry {
function addScriptExecutor(IEVMScriptExecutor executor) external returns (uint id);
function disableScriptExecutor(uint256 executorId) external;
// TODO: this should be external
// See https://github.com/ethereum/solidity/issues/4832
function getScriptExecutor(bytes script) public view returns (IEVMScriptExecutor);
}
// File: @aragon/os/contracts/kernel/KernelConstants.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract KernelAppIds {
/* Hardcoded constants to save gas
bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel");
bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl");
bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault");
*/
bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c;
bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a;
bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1;
}
contract KernelNamespaceConstants {
/* Hardcoded constants to save gas
bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core");
bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base");
bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app");
*/
bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8;
bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f;
bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb;
}
// File: @aragon/os/contracts/evmscript/EVMScriptRunner.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract EVMScriptRunner is AppStorage, Initializable, EVMScriptRegistryConstants, KernelNamespaceConstants {
string private constant ERROR_EXECUTOR_UNAVAILABLE = "EVMRUN_EXECUTOR_UNAVAILABLE";
string private constant ERROR_PROTECTED_STATE_MODIFIED = "EVMRUN_PROTECTED_STATE_MODIFIED";
/* This is manually crafted in assembly
string private constant ERROR_EXECUTOR_INVALID_RETURN = "EVMRUN_EXECUTOR_INVALID_RETURN";
*/
event ScriptResult(address indexed executor, bytes script, bytes input, bytes returnData);
function getEVMScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) {
return IEVMScriptExecutor(getEVMScriptRegistry().getScriptExecutor(_script));
}
function getEVMScriptRegistry() public view returns (IEVMScriptRegistry) {
address registryAddr = kernel().getApp(KERNEL_APP_ADDR_NAMESPACE, EVMSCRIPT_REGISTRY_APP_ID);
return IEVMScriptRegistry(registryAddr);
}
function runScript(bytes _script, bytes _input, address[] _blacklist)
internal
isInitialized
protectState
returns (bytes)
{
IEVMScriptExecutor executor = getEVMScriptExecutor(_script);
require(address(executor) != address(0), ERROR_EXECUTOR_UNAVAILABLE);
bytes4 sig = executor.execScript.selector;
bytes memory data = abi.encodeWithSelector(sig, _script, _input, _blacklist);
bytes memory output;
assembly {
let success := delegatecall(
gas, // forward all gas
executor, // address
add(data, 0x20), // calldata start
mload(data), // calldata length
0, // don't write output (we'll handle this ourselves)
0 // don't write output
)
output := mload(0x40) // free mem ptr get
switch success
case 0 {
// If the call errored, forward its full error data
returndatacopy(output, 0, returndatasize)
revert(output, returndatasize)
}
default {
switch gt(returndatasize, 0x3f)
case 0 {
// Need at least 0x40 bytes returned for properly ABI-encoded bytes values,
// revert with "EVMRUN_EXECUTOR_INVALID_RETURN"
// See remix: doing a `revert("EVMRUN_EXECUTOR_INVALID_RETURN")` always results in
// this memory layout
mstore(output, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier
mstore(add(output, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset
mstore(add(output, 0x24), 0x000000000000000000000000000000000000000000000000000000000000001e) // reason length
mstore(add(output, 0x44), 0x45564d52554e5f4558454355544f525f494e56414c49445f52455455524e0000) // reason
revert(output, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error)
}
default {
// Copy result
//
// Needs to perform an ABI decode for the expected `bytes` return type of
// `executor.execScript()` as solidity will automatically ABI encode the returned bytes as:
// [ position of the first dynamic length return value = 0x20 (32 bytes) ]
// [ output length (32 bytes) ]
// [ output content (N bytes) ]
//
// Perform the ABI decode by ignoring the first 32 bytes of the return data
let copysize := sub(returndatasize, 0x20)
returndatacopy(output, 0x20, copysize)
mstore(0x40, add(output, copysize)) // free mem ptr set
}
}
}
emit ScriptResult(address(executor), _script, _input, output);
return output;
}
modifier protectState {
address preKernel = address(kernel());
bytes32 preAppId = appId();
_; // exec
require(address(kernel()) == preKernel, ERROR_PROTECTED_STATE_MODIFIED);
require(appId() == preAppId, ERROR_PROTECTED_STATE_MODIFIED);
}
}
// File: @aragon/os/contracts/apps/AragonApp.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
// Contracts inheriting from AragonApp are, by default, immediately petrified upon deployment so
// that they can never be initialized.
// Unless overriden, this behaviour enforces those contracts to be usable only behind an AppProxy.
// ReentrancyGuard, EVMScriptRunner, and ACLSyntaxSugar are not directly used by this contract, but
// are included so that they are automatically usable by subclassing contracts
contract AragonApp is AppStorage, Autopetrified, VaultRecoverable, ReentrancyGuard, EVMScriptRunner, ACLSyntaxSugar {
string private constant ERROR_AUTH_FAILED = "APP_AUTH_FAILED";
modifier auth(bytes32 _role) {
require(canPerform(msg.sender, _role, new uint256[](0)), ERROR_AUTH_FAILED);
_;
}
modifier authP(bytes32 _role, uint256[] _params) {
require(canPerform(msg.sender, _role, _params), ERROR_AUTH_FAILED);
_;
}
/**
* @dev Check whether an action can be performed by a sender for a particular role on this app
* @param _sender Sender of the call
* @param _role Role on this app
* @param _params Permission params for the role
* @return Boolean indicating whether the sender has the permissions to perform the action.
* Always returns false if the app hasn't been initialized yet.
*/
function canPerform(address _sender, bytes32 _role, uint256[] _params) public view returns (bool) {
if (!hasInitialized()) {
return false;
}
IKernel linkedKernel = kernel();
if (address(linkedKernel) == address(0)) {
return false;
}
return linkedKernel.hasPermission(
_sender,
address(this),
_role,
ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)
);
}
/**
* @dev Get the recovery vault for the app
* @return Recovery vault address for the app
*/
function getRecoveryVault() public view returns (address) {
// Funds recovery via a vault is only available when used with a kernel
return kernel().getRecoveryVault(); // if kernel is not set, it will revert
}
}
// File: @aragon/os/contracts/common/DepositableStorage.sol
pragma solidity 0.4.24;
contract DepositableStorage {
using UnstructuredStorage for bytes32;
// keccak256("aragonOS.depositableStorage.depositable")
bytes32 internal constant DEPOSITABLE_POSITION = 0x665fd576fbbe6f247aff98f5c94a561e3f71ec2d3c988d56f12d342396c50cea;
function isDepositable() public view returns (bool) {
return DEPOSITABLE_POSITION.getStorageBool();
}
function setDepositable(bool _depositable) internal {
DEPOSITABLE_POSITION.setStorageBool(_depositable);
}
}
// File: @aragon/apps-vault/contracts/Vault.sol
pragma solidity 0.4.24;
contract Vault is EtherTokenConstant, AragonApp, DepositableStorage {
using SafeERC20 for ERC20;
bytes32 public constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE");
string private constant ERROR_DATA_NON_ZERO = "VAULT_DATA_NON_ZERO";
string private constant ERROR_NOT_DEPOSITABLE = "VAULT_NOT_DEPOSITABLE";
string private constant ERROR_DEPOSIT_VALUE_ZERO = "VAULT_DEPOSIT_VALUE_ZERO";
string private constant ERROR_TRANSFER_VALUE_ZERO = "VAULT_TRANSFER_VALUE_ZERO";
string private constant ERROR_SEND_REVERTED = "VAULT_SEND_REVERTED";
string private constant ERROR_VALUE_MISMATCH = "VAULT_VALUE_MISMATCH";
string private constant ERROR_TOKEN_TRANSFER_FROM_REVERTED = "VAULT_TOKEN_TRANSFER_FROM_REVERT";
string private constant ERROR_TOKEN_TRANSFER_REVERTED = "VAULT_TOKEN_TRANSFER_REVERTED";
event VaultTransfer(address indexed token, address indexed to, uint256 amount);
event VaultDeposit(address indexed token, address indexed sender, uint256 amount);
/**
* @dev On a normal send() or transfer() this fallback is never executed as it will be
* intercepted by the Proxy (see aragonOS#281)
*/
function () external payable isInitialized {
require(msg.data.length == 0, ERROR_DATA_NON_ZERO);
_deposit(ETH, msg.value);
}
/**
* @notice Initialize Vault app
* @dev As an AragonApp it needs to be initialized in order for roles (`auth` and `authP`) to work
*/
function initialize() external onlyInit {
initialized();
setDepositable(true);
}
/**
* @notice Deposit `_value` `_token` to the vault
* @param _token Address of the token being transferred
* @param _value Amount of tokens being transferred
*/
function deposit(address _token, uint256 _value) external payable isInitialized {
_deposit(_token, _value);
}
/**
* @notice Transfer `_value` `_token` from the Vault to `_to`
* @param _token Address of the token being transferred
* @param _to Address of the recipient of tokens
* @param _value Amount of tokens being transferred
*/
/* solium-disable-next-line function-order */
function transfer(address _token, address _to, uint256 _value)
external
authP(TRANSFER_ROLE, arr(_token, _to, _value))
{
require(_value > 0, ERROR_TRANSFER_VALUE_ZERO);
if (_token == ETH) {
require(_to.send(_value), ERROR_SEND_REVERTED);
} else {
require(ERC20(_token).safeTransfer(_to, _value), ERROR_TOKEN_TRANSFER_REVERTED);
}
emit VaultTransfer(_token, _to, _value);
}
function balance(address _token) public view returns (uint256) {
if (_token == ETH) {
return address(this).balance;
} else {
return ERC20(_token).staticBalanceOf(address(this));
}
}
/**
* @dev Disable recovery escape hatch, as it could be used
* maliciously to transfer funds away from the vault
*/
function allowRecoverability(address) public view returns (bool) {
return false;
}
function _deposit(address _token, uint256 _value) internal {
require(isDepositable(), ERROR_NOT_DEPOSITABLE);
require(_value > 0, ERROR_DEPOSIT_VALUE_ZERO);
if (_token == ETH) {
// Deposit is implicit in this case
require(msg.value == _value, ERROR_VALUE_MISMATCH);
} else {
require(
ERC20(_token).safeTransferFrom(msg.sender, address(this), _value),
ERROR_TOKEN_TRANSFER_FROM_REVERTED
);
}
emit VaultDeposit(_token, msg.sender, _value);
}
}
// File: @aragon/os/contracts/common/IForwarder.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
interface IForwarder {
function isForwarder() external pure returns (bool);
// TODO: this should be external
// See https://github.com/ethereum/solidity/issues/4832
function canForward(address sender, bytes evmCallScript) public view returns (bool);
// TODO: this should be external
// See https://github.com/ethereum/solidity/issues/4832
function forward(bytes evmCallScript) public;
}
// File: @aragon/apps-agent/contracts/Agent.sol
/*
* SPDX-License-Identitifer: GPL-3.0-or-later
*/
pragma solidity 0.4.24;
contract Agent is IERC165, ERC1271Bytes, IForwarder, IsContract, Vault {
/* Hardcoded constants to save gas
bytes32 public constant EXECUTE_ROLE = keccak256("EXECUTE_ROLE");
bytes32 public constant SAFE_EXECUTE_ROLE = keccak256("SAFE_EXECUTE_ROLE");
bytes32 public constant ADD_PROTECTED_TOKEN_ROLE = keccak256("ADD_PROTECTED_TOKEN_ROLE");
bytes32 public constant REMOVE_PROTECTED_TOKEN_ROLE = keccak256("REMOVE_PROTECTED_TOKEN_ROLE");
bytes32 public constant ADD_PRESIGNED_HASH_ROLE = keccak256("ADD_PRESIGNED_HASH_ROLE");
bytes32 public constant DESIGNATE_SIGNER_ROLE = keccak256("DESIGNATE_SIGNER_ROLE");
bytes32 public constant RUN_SCRIPT_ROLE = keccak256("RUN_SCRIPT_ROLE");
*/
bytes32 public constant EXECUTE_ROLE = 0xcebf517aa4440d1d125e0355aae64401211d0848a23c02cc5d29a14822580ba4;
bytes32 public constant SAFE_EXECUTE_ROLE = 0x0a1ad7b87f5846153c6d5a1f761d71c7d0cfd122384f56066cd33239b7933694;
bytes32 public constant ADD_PROTECTED_TOKEN_ROLE = 0x6eb2a499556bfa2872f5aa15812b956cc4a71b4d64eb3553f7073c7e41415aaa;
bytes32 public constant REMOVE_PROTECTED_TOKEN_ROLE = 0x71eee93d500f6f065e38b27d242a756466a00a52a1dbcd6b4260f01a8640402a;
bytes32 public constant ADD_PRESIGNED_HASH_ROLE = 0x0b29780bb523a130b3b01f231ef49ed2fa2781645591a0b0a44ca98f15a5994c;
bytes32 public constant DESIGNATE_SIGNER_ROLE = 0x23ce341656c3f14df6692eebd4757791e33662b7dcf9970c8308303da5472b7c;
bytes32 public constant RUN_SCRIPT_ROLE = 0xb421f7ad7646747f3051c50c0b8e2377839296cd4973e27f63821d73e390338f;
uint256 public constant PROTECTED_TOKENS_CAP = 10;
bytes4 private constant ERC165_INTERFACE_ID = 0x01ffc9a7;
string private constant ERROR_TARGET_PROTECTED = "AGENT_TARGET_PROTECTED";
string private constant ERROR_PROTECTED_TOKENS_MODIFIED = "AGENT_PROTECTED_TOKENS_MODIFIED";
string private constant ERROR_PROTECTED_BALANCE_LOWERED = "AGENT_PROTECTED_BALANCE_LOWERED";
string private constant ERROR_TOKENS_CAP_REACHED = "AGENT_TOKENS_CAP_REACHED";
string private constant ERROR_TOKEN_NOT_ERC20 = "AGENT_TOKEN_NOT_ERC20";
string private constant ERROR_TOKEN_ALREADY_PROTECTED = "AGENT_TOKEN_ALREADY_PROTECTED";
string private constant ERROR_TOKEN_NOT_PROTECTED = "AGENT_TOKEN_NOT_PROTECTED";
string private constant ERROR_DESIGNATED_TO_SELF = "AGENT_DESIGNATED_TO_SELF";
string private constant ERROR_CAN_NOT_FORWARD = "AGENT_CAN_NOT_FORWARD";
mapping (bytes32 => bool) public isPresigned;
address public designatedSigner;
address[] public protectedTokens;
event SafeExecute(address indexed sender, address indexed target, bytes data);
event Execute(address indexed sender, address indexed target, uint256 ethValue, bytes data);
event AddProtectedToken(address indexed token);
event RemoveProtectedToken(address indexed token);
event PresignHash(address indexed sender, bytes32 indexed hash);
event SetDesignatedSigner(address indexed sender, address indexed oldSigner, address indexed newSigner);
/**
* @notice Execute '`@radspec(_target, _data)`' on `_target``_ethValue == 0 ? '' : ' (Sending' + @tokenAmount(0x0000000000000000000000000000000000000000, _ethValue) + ')'`
* @param _target Address where the action is being executed
* @param _ethValue Amount of ETH from the contract that is sent with the action
* @param _data Calldata for the action
* @return Exits call frame forwarding the return data of the executed call (either error or success data)
*/
function execute(address _target, uint256 _ethValue, bytes _data)
external // This function MUST always be external as the function performs a low level return, exiting the Agent app execution context
authP(EXECUTE_ROLE, arr(_target, _ethValue, uint256(_getSig(_data)))) // bytes4 casted as uint256 sets the bytes as the LSBs
{
bool result = _target.call.value(_ethValue)(_data);
if (result) {
emit Execute(msg.sender, _target, _ethValue, _data);
}
assembly {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize)
// revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas.
// if the call returned error data, forward it
switch result case 0 { revert(ptr, returndatasize) }
default { return(ptr, returndatasize) }
}
}
/**
* @notice Execute '`@radspec(_target, _data)`' on `_target` ensuring that protected tokens can't be spent
* @param _target Address where the action is being executed
* @param _data Calldata for the action
* @return Exits call frame forwarding the return data of the executed call (either error or success data)
*/
function safeExecute(address _target, bytes _data)
external // This function MUST always be external as the function performs a low level return, exiting the Agent app execution context
authP(SAFE_EXECUTE_ROLE, arr(_target, uint256(_getSig(_data)))) // bytes4 casted as uint256 sets the bytes as the LSBs
{
uint256 protectedTokensLength = protectedTokens.length;
address[] memory protectedTokens_ = new address[](protectedTokensLength);
uint256[] memory balances = new uint256[](protectedTokensLength);
for (uint256 i = 0; i < protectedTokensLength; i++) {
address token = protectedTokens[i];
require(_target != token, ERROR_TARGET_PROTECTED);
// we copy the protected tokens array to check whether the storage array has been modified during the underlying call
protectedTokens_[i] = token;
// we copy the balances to check whether they have been modified during the underlying call
balances[i] = balance(token);
}
bool result = _target.call(_data);
bytes32 ptr;
uint256 size;
assembly {
size := returndatasize
ptr := mload(0x40)
mstore(0x40, add(ptr, returndatasize))
returndatacopy(ptr, 0, returndatasize)
}
if (result) {
// if the underlying call has succeeded, we check that the protected tokens
// and their balances have not been modified and return the call's return data
require(protectedTokens.length == protectedTokensLength, ERROR_PROTECTED_TOKENS_MODIFIED);
for (uint256 j = 0; j < protectedTokensLength; j++) {
require(protectedTokens[j] == protectedTokens_[j], ERROR_PROTECTED_TOKENS_MODIFIED);
require(balance(protectedTokens[j]) >= balances[j], ERROR_PROTECTED_BALANCE_LOWERED);
}
emit SafeExecute(msg.sender, _target, _data);
assembly {
return(ptr, size)
}
} else {
// if the underlying call has failed, we revert and forward returned error data
assembly {
revert(ptr, size)
}
}
}
/**
* @notice Add `_token.symbol(): string` to the list of protected tokens
* @param _token Address of the token to be protected
*/
function addProtectedToken(address _token) external authP(ADD_PROTECTED_TOKEN_ROLE, arr(_token)) {
require(protectedTokens.length < PROTECTED_TOKENS_CAP, ERROR_TOKENS_CAP_REACHED);
require(_isERC20(_token), ERROR_TOKEN_NOT_ERC20);
require(!_tokenIsProtected(_token), ERROR_TOKEN_ALREADY_PROTECTED);
_addProtectedToken(_token);
}
/**
* @notice Remove `_token.symbol(): string` from the list of protected tokens
* @param _token Address of the token to be unprotected
*/
function removeProtectedToken(address _token) external authP(REMOVE_PROTECTED_TOKEN_ROLE, arr(_token)) {
require(_tokenIsProtected(_token), ERROR_TOKEN_NOT_PROTECTED);
_removeProtectedToken(_token);
}
/**
* @notice Pre-sign hash `_hash`
* @param _hash Hash that will be considered signed regardless of the signature checked with 'isValidSignature()'
*/
function presignHash(bytes32 _hash)
external
authP(ADD_PRESIGNED_HASH_ROLE, arr(_hash))
{
isPresigned[_hash] = true;
emit PresignHash(msg.sender, _hash);
}
/**
* @notice Set `_designatedSigner` as the designated signer of the app, which will be able to sign messages on behalf of the app
* @param _designatedSigner Address that will be able to sign messages on behalf of the app
*/
function setDesignatedSigner(address _designatedSigner)
external
authP(DESIGNATE_SIGNER_ROLE, arr(_designatedSigner))
{
// Prevent an infinite loop by setting the app itself as its designated signer.
// An undetectable loop can be created by setting a different contract as the
// designated signer which calls back into `isValidSignature`.
// Given that `isValidSignature` is always called with just 50k gas, the max
// damage of the loop is wasting 50k gas.
require(_designatedSigner != address(this), ERROR_DESIGNATED_TO_SELF);
address oldDesignatedSigner = designatedSigner;
designatedSigner = _designatedSigner;
emit SetDesignatedSigner(msg.sender, oldDesignatedSigner, _designatedSigner);
}
// Forwarding fns
/**
* @notice Tells whether the Agent app is a forwarder or not
* @dev IForwarder interface conformance
* @return Always true
*/
function isForwarder() external pure returns (bool) {
return true;
}
/**
* @notice Execute the script as the Agent app
* @dev IForwarder interface conformance. Forwards any token holder action.
* @param _evmScript Script being executed
*/
function forward(bytes _evmScript) public {
require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD);
bytes memory input = ""; // no input
address[] memory blacklist = new address[](0); // no addr blacklist, can interact with anything
runScript(_evmScript, input, blacklist);
// We don't need to emit an event here as EVMScriptRunner will emit ScriptResult if successful
}
/**
* @notice Tells whether `_sender` can forward actions or not
* @dev IForwarder interface conformance
* @param _sender Address of the account intending to forward an action
* @return True if the given address can run scripts, false otherwise
*/
function canForward(address _sender, bytes _evmScript) public view returns (bool) {
// Note that `canPerform()` implicitly does an initialization check itself
return canPerform(_sender, RUN_SCRIPT_ROLE, arr(_getScriptACLParam(_evmScript)));
}
// ERC-165 conformance
/**
* @notice Tells whether this contract supports a given ERC-165 interface
* @param _interfaceId Interface bytes to check
* @return True if this contract supports the interface
*/
function supportsInterface(bytes4 _interfaceId) external pure returns (bool) {
return
_interfaceId == ERC1271_INTERFACE_ID ||
_interfaceId == ERC165_INTERFACE_ID;
}
// ERC-1271 conformance
/**
* @notice Tells whether a signature is seen as valid by this contract through ERC-1271
* @param _hash Arbitrary length data signed on the behalf of address (this)
* @param _signature Signature byte array associated with _data
* @return The ERC-1271 magic value if the signature is valid
*/
function isValidSignature(bytes32 _hash, bytes _signature) public view returns (bytes4) {
// Short-circuit in case the hash was presigned. Optimization as performing calls
// and ecrecover is more expensive than an SLOAD.
if (isPresigned[_hash]) {
return returnIsValidSignatureMagicNumber(true);
}
bool isValid;
if (designatedSigner == address(0)) {
isValid = false;
} else {
isValid = SignatureValidator.isValidSignature(_hash, designatedSigner, _signature);
}
return returnIsValidSignatureMagicNumber(isValid);
}
// Getters
function getProtectedTokensLength() public view isInitialized returns (uint256) {
return protectedTokens.length;
}
// Internal fns
function _addProtectedToken(address _token) internal {
protectedTokens.push(_token);
emit AddProtectedToken(_token);
}
function _removeProtectedToken(address _token) internal {
protectedTokens[_protectedTokenIndex(_token)] = protectedTokens[protectedTokens.length - 1];
protectedTokens.length--;
emit RemoveProtectedToken(_token);
}
function _isERC20(address _token) internal view returns (bool) {
if (!isContract(_token)) {
return false;
}
// Throwaway sanity check to make sure the token's `balanceOf()` does not error (for now)
balance(_token);
return true;
}
function _protectedTokenIndex(address _token) internal view returns (uint256) {
for (uint i = 0; i < protectedTokens.length; i++) {
if (protectedTokens[i] == _token) {
return i;
}
}
revert(ERROR_TOKEN_NOT_PROTECTED);
}
function _tokenIsProtected(address _token) internal view returns (bool) {
for (uint256 i = 0; i < protectedTokens.length; i++) {
if (protectedTokens[i] == _token) {
return true;
}
}
return false;
}
function _getScriptACLParam(bytes _evmScript) internal pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(_evmScript)));
}
function _getSig(bytes _data) internal pure returns (bytes4 sig) {
if (_data.length < 4) {
return;
}
assembly { sig := mload(add(_data, 0x20)) }
}
}
// File: @aragon/os/contracts/lib/math/SafeMath.sol
// See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol
// Adapted to use pragma ^0.4.24 and satisfy our linter rules
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW";
string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW";
string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW";
string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO";
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
uint256 c = _a * _b;
require(c / _a == _b, ERROR_MUL_OVERFLOW);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0
uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b <= _a, ERROR_SUB_UNDERFLOW);
uint256 c = _a - _b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
require(c >= _a, ERROR_ADD_OVERFLOW);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, ERROR_DIV_ZERO);
return a % b;
}
}
// File: @aragon/os/contracts/lib/math/SafeMath64.sol
// See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol
// Adapted for uint64, pragma ^0.4.24, and satisfying our linter rules
// Also optimized the mul() implementation, see https://github.com/aragon/aragonOS/pull/417
pragma solidity ^0.4.24;
/**
* @title SafeMath64
* @dev Math operations for uint64 with safety checks that revert on error
*/
library SafeMath64 {
string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW";
string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW";
string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW";
string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO";
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint64 _a, uint64 _b) internal pure returns (uint64) {
uint256 c = uint256(_a) * uint256(_b);
require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way)
return uint64(c);
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint64 _a, uint64 _b) internal pure returns (uint64) {
require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0
uint64 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint64 _a, uint64 _b) internal pure returns (uint64) {
require(_b <= _a, ERROR_SUB_UNDERFLOW);
uint64 c = _a - _b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint64 _a, uint64 _b) internal pure returns (uint64) {
uint64 c = _a + _b;
require(c >= _a, ERROR_ADD_OVERFLOW);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint64 a, uint64 b) internal pure returns (uint64) {
require(b != 0, ERROR_DIV_ZERO);
return a % b;
}
}
// File: @aragon/apps-shared-minime/contracts/ITokenController.sol
pragma solidity ^0.4.24;
/// @dev The token controller contract must implement these functions
interface ITokenController {
/// @notice Called when `_owner` sends ether to the MiniMe Token contract
/// @param _owner The address that sent the ether to create tokens
/// @return True if the ether is accepted, false if it throws
function proxyPayment(address _owner) external payable returns(bool);
/// @notice Notifies the controller about a token transfer allowing the
/// controller to react if desired
/// @param _from The origin of the transfer
/// @param _to The destination of the transfer
/// @param _amount The amount of the transfer
/// @return False if the controller does not authorize the transfer
function onTransfer(address _from, address _to, uint _amount) external returns(bool);
/// @notice Notifies the controller about an approval allowing the
/// controller to react if desired
/// @param _owner The address that calls `approve()`
/// @param _spender The spender in the `approve()` call
/// @param _amount The amount in the `approve()` call
/// @return False if the controller does not authorize the approval
function onApprove(address _owner, address _spender, uint _amount) external returns(bool);
}
// File: @aragon/apps-shared-minime/contracts/MiniMeToken.sol
pragma solidity ^0.4.24;
/*
Copyright 2016, Jordi Baylina
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// @title MiniMeToken Contract
/// @author Jordi Baylina
/// @dev This token contract's goal is to make it easy for anyone to clone this
/// token using the token distribution at a given block, this will allow DAO's
/// and DApps to upgrade their features in a decentralized manner without
/// affecting the original token
/// @dev It is ERC20 compliant, but still needs to under go further testing.
contract Controlled {
/// @notice The address of the controller is the only address that can call
/// a function with this modifier
modifier onlyController {
require(msg.sender == controller);
_;
}
address public controller;
function Controlled() public { controller = msg.sender;}
/// @notice Changes the controller of the contract
/// @param _newController The new controller of the contract
function changeController(address _newController) onlyController public {
controller = _newController;
}
}
contract ApproveAndCallFallBack {
function receiveApproval(
address from,
uint256 _amount,
address _token,
bytes _data
) public;
}
/// @dev The actual token contract, the default controller is the msg.sender
/// that deploys the contract, so usually this token will be deployed by a
/// token controller contract, which Giveth will call a "Campaign"
contract MiniMeToken is Controlled {
string public name; //The Token's name: e.g. DigixDAO Tokens
uint8 public decimals; //Number of decimals of the smallest unit
string public symbol; //An identifier: e.g. REP
string public version = "MMT_0.1"; //An arbitrary versioning scheme
/// @dev `Checkpoint` is the structure that attaches a block number to a
/// given value, the block number attached is the one that last changed the
/// value
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint128 fromBlock;
// `value` is the amount of tokens at a specific block number
uint128 value;
}
// `parentToken` is the Token address that was cloned to produce this token;
// it will be 0x0 for a token that was not cloned
MiniMeToken public parentToken;
// `parentSnapShotBlock` is the block number from the Parent Token that was
// used to determine the initial distribution of the Clone Token
uint public parentSnapShotBlock;
// `creationBlock` is the block number that the Clone Token was created
uint public creationBlock;
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping (address => Checkpoint[]) balances;
// `allowed` tracks any extra transfer rights as in all ERC20 tokens
mapping (address => mapping (address => uint256)) allowed;
// Tracks the history of the `totalSupply` of the token
Checkpoint[] totalSupplyHistory;
// Flag that determines if the token is transferable or not.
bool public transfersEnabled;
// The factory used to create new clone tokens
MiniMeTokenFactory public tokenFactory;
////////////////
// Constructor
////////////////
/// @notice Constructor to create a MiniMeToken
/// @param _tokenFactory The address of the MiniMeTokenFactory contract that
/// will create the Clone token contracts, the token factory needs to be
/// deployed first
/// @param _parentToken Address of the parent token, set to 0x0 if it is a
/// new token
/// @param _parentSnapShotBlock Block of the parent token that will
/// determine the initial distribution of the clone token, set to 0 if it
/// is a new token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
function MiniMeToken(
MiniMeTokenFactory _tokenFactory,
MiniMeToken _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public
{
tokenFactory = _tokenFactory;
name = _tokenName; // Set the name
decimals = _decimalUnits; // Set the decimals
symbol = _tokenSymbol; // Set the symbol
parentToken = _parentToken;
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = block.number;
}
///////////////////
// ERC20 Methods
///////////////////
/// @notice Send `_amount` tokens to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
return doTransfer(msg.sender, _to, _amount);
}
/// @notice Send `_amount` tokens to `_to` from `_from` on the condition it
/// is approved by `_from`
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) {
// The controller of this contract can move tokens around at will,
// this is important to recognize! Confirm that you trust the
// controller of this contract, which in most situations should be
// another open source smart contract or 0x0
if (msg.sender != controller) {
require(transfersEnabled);
// The standard ERC 20 transferFrom functionality
if (allowed[_from][msg.sender] < _amount)
return false;
allowed[_from][msg.sender] -= _amount;
}
return doTransfer(_from, _to, _amount);
}
/// @dev This is the actual transfer function in the token contract, it can
/// only be called by other functions in this contract.
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function doTransfer(address _from, address _to, uint _amount) internal returns(bool) {
if (_amount == 0) {
return true;
}
require(parentSnapShotBlock < block.number);
// 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;
}
// Alerts the token controller of the transfer
if (isContract(controller)) {
// Adding the ` == true` makes the linter shut up so...
require(ITokenController(controller).onTransfer(_from, _to, _amount) == true);
}
// 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;
}
/// @param _owner The address that's balance is being requested
/// @return The balance of `_owner` at the current block
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
/// its behalf. This is a modified version of the ERC20 approve function
/// to be a little bit safer
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(address _spender, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender,0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
// Alerts the token controller of the approve function call
if (isContract(controller)) {
// Adding the ` == true` makes the linter shut up so...
require(ITokenController(controller).onApprove(msg.sender, _spender, _amount) == true);
}
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
/// @dev This function makes it easy to read the `allowed[]` map
/// @param _owner The address of the account that owns the token
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens of _owner that _spender is allowed
/// to spend
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @notice `msg.sender` approves `_spender` to send `_amount` tokens on
/// its behalf, and then a function is triggered in the contract that is
/// being approved, `_spender`. This allows users to use their tokens to
/// interact with contracts in one function call instead of two
/// @param _spender The address of the contract able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the function call was successful
function approveAndCall(ApproveAndCallFallBack _spender, uint256 _amount, bytes _extraData) public returns (bool success) {
require(approve(_spender, _amount));
_spender.receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
/// @dev This function makes it easy to get the total number of tokens
/// @return The total number of tokens
function totalSupply() public constant returns (uint) {
return totalSupplyAt(block.number);
}
////////////////
// Query balance and totalSupply in History
////////////////
/// @dev Queries the balance of `_owner` at a specific `_blockNumber`
/// @param _owner The address from which the balance will be retrieved
/// @param _blockNumber The block number when the balance is queried
/// @return The balance at `_blockNumber`
function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) {
// These next few lines are used when the balance of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.balanceOfAt` be queried at the
// genesis block for that token as this contains initial balance of
// this token
if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
} else {
// Has no parent
return 0;
}
// This will return the expected balance during normal situations
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
/// @notice Total amount of tokens at a specific `_blockNumber`.
/// @param _blockNumber The block number when the totalSupply is queried
/// @return The total amount of tokens at `_blockNumber`
function totalSupplyAt(uint _blockNumber) public constant returns(uint) {
// These next few lines are used when the totalSupply of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.totalSupplyAt` be queried at the
// genesis block for this token as that contains totalSupply of this
// token at this block number.
if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
// This will return the expected totalSupply during normal situations
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
////////////////
// Clone Token Method
////////////////
/// @notice Creates a new clone token with the initial distribution being
/// this token at `_snapshotBlock`
/// @param _cloneTokenName Name of the clone token
/// @param _cloneDecimalUnits Number of decimals of the smallest unit
/// @param _cloneTokenSymbol Symbol of the clone token
/// @param _snapshotBlock Block when the distribution of the parent token is
/// copied to set the initial distribution of the new clone token;
/// if the block is zero than the actual block, the current block is used
/// @param _transfersEnabled True if transfers are allowed in the clone
/// @return The address of the new MiniMeToken Contract
function createCloneToken(
string _cloneTokenName,
uint8 _cloneDecimalUnits,
string _cloneTokenSymbol,
uint _snapshotBlock,
bool _transfersEnabled
) public returns(MiniMeToken)
{
uint256 snapshot = _snapshotBlock == 0 ? block.number - 1 : _snapshotBlock;
MiniMeToken cloneToken = tokenFactory.createCloneToken(
this,
snapshot,
_cloneTokenName,
_cloneDecimalUnits,
_cloneTokenSymbol,
_transfersEnabled
);
cloneToken.changeController(msg.sender);
// An event to make the token easy to find on the blockchain
NewCloneToken(address(cloneToken), snapshot);
return cloneToken;
}
////////////////
// Generate and destroy tokens
////////////////
/// @notice Generates `_amount` tokens that are assigned to `_owner`
/// @param _owner The address that will be assigned the new tokens
/// @param _amount The quantity of tokens generated
/// @return True if the tokens are generated correctly
function generateTokens(address _owner, uint _amount) onlyController public returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_owner], previousBalanceTo + _amount);
Transfer(0, _owner, _amount);
return true;
}
/// @notice Burns `_amount` tokens from `_owner`
/// @param _owner The address that will lose the tokens
/// @param _amount The quantity of tokens to burn
/// @return True if the tokens are burned correctly
function destroyTokens(address _owner, uint _amount) onlyController public returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
Transfer(_owner, 0, _amount);
return true;
}
////////////////
// Enable tokens transfers
////////////////
/// @notice Enables token holders to transfer their tokens freely if true
/// @param _transfersEnabled True if transfers are allowed in the clone
function enableTransfers(bool _transfersEnabled) onlyController public {
transfersEnabled = _transfersEnabled;
}
////////////////
// Internal helper functions to query and set a value in a snapshot array
////////////////
/// @dev `getValueAt` retrieves the number of tokens at a given block number
/// @param checkpoints The history of values being queried
/// @param _block The block number to retrieve the value at
/// @return The number of tokens being queried
function getValueAt(Checkpoint[] storage checkpoints, uint _block) constant internal returns (uint) {
if (checkpoints.length == 0)
return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length-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(Checkpoint[] storage checkpoints, uint _value) internal {
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1];
oldCheckPoint.value = uint128(_value);
}
}
/// @dev Internal function to determine if an address is a contract
/// @param _addr The address being queried
/// @return True if `_addr` is a contract
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0)
return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
/// @dev Helper function to return a min betwen the two uints
function min(uint a, uint b) pure internal returns (uint) {
return a < b ? a : b;
}
/// @notice The fallback function: If the contract's controller has not been
/// set to 0, then the `proxyPayment` method is called which relays the
/// ether and creates tokens as described in the token controller contract
function () external payable {
require(isContract(controller));
// Adding the ` == true` makes the linter shut up so...
require(ITokenController(controller).proxyPayment.value(msg.value)(msg.sender) == true);
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the controller to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address _token) onlyController public {
if (_token == 0x0) {
controller.transfer(this.balance);
return;
}
MiniMeToken token = MiniMeToken(_token);
uint balance = token.balanceOf(this);
token.transfer(controller, balance);
ClaimedTokens(_token, controller, balance);
}
////////////////
// Events
////////////////
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _amount
);
}
////////////////
// MiniMeTokenFactory
////////////////
/// @dev This contract is used to generate clone contracts from a contract.
/// In solidity this is the way to create a contract from a contract of the
/// same class
contract MiniMeTokenFactory {
/// @notice Update the DApp by creating a new token with new functionalities
/// the msg.sender becomes the controller of this clone token
/// @param _parentToken Address of the token being cloned
/// @param _snapshotBlock Block of the parent token that will
/// determine the initial distribution of the clone token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
/// @return The address of the new token contract
function createCloneToken(
MiniMeToken _parentToken,
uint _snapshotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public returns (MiniMeToken)
{
MiniMeToken newToken = new MiniMeToken(
this,
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.changeController(msg.sender);
return newToken;
}
}
// File: @aragon/apps-voting/contracts/Voting.sol
/*
* SPDX-License-Identitifer: GPL-3.0-or-later
*/
pragma solidity 0.4.24;
contract Voting is IForwarder, AragonApp {
using SafeMath for uint256;
using SafeMath64 for uint64;
bytes32 public constant CREATE_VOTES_ROLE = keccak256("CREATE_VOTES_ROLE");
bytes32 public constant MODIFY_SUPPORT_ROLE = keccak256("MODIFY_SUPPORT_ROLE");
bytes32 public constant MODIFY_QUORUM_ROLE = keccak256("MODIFY_QUORUM_ROLE");
uint64 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18
string private constant ERROR_NO_VOTE = "VOTING_NO_VOTE";
string private constant ERROR_INIT_PCTS = "VOTING_INIT_PCTS";
string private constant ERROR_CHANGE_SUPPORT_PCTS = "VOTING_CHANGE_SUPPORT_PCTS";
string private constant ERROR_CHANGE_QUORUM_PCTS = "VOTING_CHANGE_QUORUM_PCTS";
string private constant ERROR_INIT_SUPPORT_TOO_BIG = "VOTING_INIT_SUPPORT_TOO_BIG";
string private constant ERROR_CHANGE_SUPPORT_TOO_BIG = "VOTING_CHANGE_SUPP_TOO_BIG";
string private constant ERROR_CAN_NOT_VOTE = "VOTING_CAN_NOT_VOTE";
string private constant ERROR_CAN_NOT_EXECUTE = "VOTING_CAN_NOT_EXECUTE";
string private constant ERROR_CAN_NOT_FORWARD = "VOTING_CAN_NOT_FORWARD";
string private constant ERROR_NO_VOTING_POWER = "VOTING_NO_VOTING_POWER";
enum VoterState { Absent, Yea, Nay }
struct Vote {
bool executed;
uint64 startDate;
uint64 snapshotBlock;
uint64 supportRequiredPct;
uint64 minAcceptQuorumPct;
uint256 yea;
uint256 nay;
uint256 votingPower;
bytes executionScript;
mapping (address => VoterState) voters;
}
MiniMeToken public token;
uint64 public supportRequiredPct;
uint64 public minAcceptQuorumPct;
uint64 public voteTime;
// We are mimicing an array, we use a mapping instead to make app upgrade more graceful
mapping (uint256 => Vote) internal votes;
uint256 public votesLength;
event StartVote(uint256 indexed voteId, address indexed creator, string metadata);
event CastVote(uint256 indexed voteId, address indexed voter, bool supports, uint256 stake);
event ExecuteVote(uint256 indexed voteId);
event ChangeSupportRequired(uint64 supportRequiredPct);
event ChangeMinQuorum(uint64 minAcceptQuorumPct);
modifier voteExists(uint256 _voteId) {
require(_voteId < votesLength, ERROR_NO_VOTE);
_;
}
/**
* @notice Initialize Voting app with `_token.symbol(): string` for governance, minimum support of `@formatPct(_supportRequiredPct)`%, minimum acceptance quorum of `@formatPct(_minAcceptQuorumPct)`%, and a voting duration of `@transformTime(_voteTime)`
* @param _token MiniMeToken Address that will be used as governance token
* @param _supportRequiredPct Percentage of yeas in casted votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%)
* @param _minAcceptQuorumPct Percentage of yeas in total possible votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%)
* @param _voteTime Seconds that a vote will be open for token holders to vote (unless enough yeas or nays have been cast to make an early decision)
*/
function initialize(
MiniMeToken _token,
uint64 _supportRequiredPct,
uint64 _minAcceptQuorumPct,
uint64 _voteTime
)
external
onlyInit
{
initialized();
require(_minAcceptQuorumPct <= _supportRequiredPct, ERROR_INIT_PCTS);
require(_supportRequiredPct < PCT_BASE, ERROR_INIT_SUPPORT_TOO_BIG);
token = _token;
supportRequiredPct = _supportRequiredPct;
minAcceptQuorumPct = _minAcceptQuorumPct;
voteTime = _voteTime;
}
/**
* @notice Change required support to `@formatPct(_supportRequiredPct)`%
* @param _supportRequiredPct New required support
*/
function changeSupportRequiredPct(uint64 _supportRequiredPct)
external
authP(MODIFY_SUPPORT_ROLE, arr(uint256(_supportRequiredPct), uint256(supportRequiredPct)))
{
require(minAcceptQuorumPct <= _supportRequiredPct, ERROR_CHANGE_SUPPORT_PCTS);
require(_supportRequiredPct < PCT_BASE, ERROR_CHANGE_SUPPORT_TOO_BIG);
supportRequiredPct = _supportRequiredPct;
emit ChangeSupportRequired(_supportRequiredPct);
}
/**
* @notice Change minimum acceptance quorum to `@formatPct(_minAcceptQuorumPct)`%
* @param _minAcceptQuorumPct New acceptance quorum
*/
function changeMinAcceptQuorumPct(uint64 _minAcceptQuorumPct)
external
authP(MODIFY_QUORUM_ROLE, arr(uint256(_minAcceptQuorumPct), uint256(minAcceptQuorumPct)))
{
require(_minAcceptQuorumPct <= supportRequiredPct, ERROR_CHANGE_QUORUM_PCTS);
minAcceptQuorumPct = _minAcceptQuorumPct;
emit ChangeMinQuorum(_minAcceptQuorumPct);
}
/**
* @notice Create a new vote about "`_metadata`"
* @param _executionScript EVM script to be executed on approval
* @param _metadata Vote metadata
* @return voteId Id for newly created vote
*/
function newVote(bytes _executionScript, string _metadata) external auth(CREATE_VOTES_ROLE) returns (uint256 voteId) {
return _newVote(_executionScript, _metadata, true, true);
}
/**
* @notice Create a new vote about "`_metadata`"
* @param _executionScript EVM script to be executed on approval
* @param _metadata Vote metadata
* @param _castVote Whether to also cast newly created vote
* @param _executesIfDecided Whether to also immediately execute newly created vote if decided
* @return voteId id for newly created vote
*/
function newVote(bytes _executionScript, string _metadata, bool _castVote, bool _executesIfDecided)
external
auth(CREATE_VOTES_ROLE)
returns (uint256 voteId)
{
return _newVote(_executionScript, _metadata, _castVote, _executesIfDecided);
}
/**
* @notice Vote `_supports ? 'yes' : 'no'` in vote #`_voteId`
* @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be
* created via `newVote(),` which requires initialization
* @param _voteId Id for vote
* @param _supports Whether voter supports the vote
* @param _executesIfDecided Whether the vote should execute its action if it becomes decided
*/
function vote(uint256 _voteId, bool _supports, bool _executesIfDecided) external voteExists(_voteId) {
require(_canVote(_voteId, msg.sender), ERROR_CAN_NOT_VOTE);
_vote(_voteId, _supports, msg.sender, _executesIfDecided);
}
/**
* @notice Execute vote #`_voteId`
* @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be
* created via `newVote(),` which requires initialization
* @param _voteId Id for vote
*/
function executeVote(uint256 _voteId) external voteExists(_voteId) {
_executeVote(_voteId);
}
// Forwarding fns
function isForwarder() external pure returns (bool) {
return true;
}
/**
* @notice Creates a vote to execute the desired action, and casts a support vote if possible
* @dev IForwarder interface conformance
* @param _evmScript Start vote with script
*/
function forward(bytes _evmScript) public {
require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD);
_newVote(_evmScript, "", true, true);
}
function canForward(address _sender, bytes) public view returns (bool) {
// Note that `canPerform()` implicitly does an initialization check itself
return canPerform(_sender, CREATE_VOTES_ROLE, arr());
}
// Getter fns
/**
* @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be
* created via `newVote(),` which requires initialization
*/
function canExecute(uint256 _voteId) public view voteExists(_voteId) returns (bool) {
return _canExecute(_voteId);
}
/**
* @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be
* created via `newVote(),` which requires initialization
*/
function canVote(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (bool) {
return _canVote(_voteId, _voter);
}
function getVote(uint256 _voteId)
public
view
voteExists(_voteId)
returns (
bool open,
bool executed,
uint64 startDate,
uint64 snapshotBlock,
uint64 supportRequired,
uint64 minAcceptQuorum,
uint256 yea,
uint256 nay,
uint256 votingPower,
bytes script
)
{
Vote storage vote_ = votes[_voteId];
open = _isVoteOpen(vote_);
executed = vote_.executed;
startDate = vote_.startDate;
snapshotBlock = vote_.snapshotBlock;
supportRequired = vote_.supportRequiredPct;
minAcceptQuorum = vote_.minAcceptQuorumPct;
yea = vote_.yea;
nay = vote_.nay;
votingPower = vote_.votingPower;
script = vote_.executionScript;
}
function getVoterState(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (VoterState) {
return votes[_voteId].voters[_voter];
}
// Internal fns
function _newVote(bytes _executionScript, string _metadata, bool _castVote, bool _executesIfDecided)
internal
returns (uint256 voteId)
{
uint64 snapshotBlock = getBlockNumber64() - 1; // avoid double voting in this very block
uint256 votingPower = token.totalSupplyAt(snapshotBlock);
require(votingPower > 0, ERROR_NO_VOTING_POWER);
voteId = votesLength++;
Vote storage vote_ = votes[voteId];
vote_.startDate = getTimestamp64();
vote_.snapshotBlock = snapshotBlock;
vote_.supportRequiredPct = supportRequiredPct;
vote_.minAcceptQuorumPct = minAcceptQuorumPct;
vote_.votingPower = votingPower;
vote_.executionScript = _executionScript;
emit StartVote(voteId, msg.sender, _metadata);
if (_castVote && _canVote(voteId, msg.sender)) {
_vote(voteId, true, msg.sender, _executesIfDecided);
}
}
function _vote(
uint256 _voteId,
bool _supports,
address _voter,
bool _executesIfDecided
) internal
{
Vote storage vote_ = votes[_voteId];
// This could re-enter, though we can assume the governance token is not malicious
uint256 voterStake = token.balanceOfAt(_voter, vote_.snapshotBlock);
VoterState state = vote_.voters[_voter];
// If voter had previously voted, decrease count
if (state == VoterState.Yea) {
vote_.yea = vote_.yea.sub(voterStake);
} else if (state == VoterState.Nay) {
vote_.nay = vote_.nay.sub(voterStake);
}
if (_supports) {
vote_.yea = vote_.yea.add(voterStake);
} else {
vote_.nay = vote_.nay.add(voterStake);
}
vote_.voters[_voter] = _supports ? VoterState.Yea : VoterState.Nay;
emit CastVote(_voteId, _voter, _supports, voterStake);
if (_executesIfDecided && _canExecute(_voteId)) {
// We've already checked if the vote can be executed with `_canExecute()`
_unsafeExecuteVote(_voteId);
}
}
function _executeVote(uint256 _voteId) internal {
require(_canExecute(_voteId), ERROR_CAN_NOT_EXECUTE);
_unsafeExecuteVote(_voteId);
}
/**
* @dev Unsafe version of _executeVote that assumes you have already checked if the vote can be executed
*/
function _unsafeExecuteVote(uint256 _voteId) internal {
Vote storage vote_ = votes[_voteId];
vote_.executed = true;
bytes memory input = new bytes(0); // TODO: Consider input for voting scripts
runScript(vote_.executionScript, input, new address[](0));
emit ExecuteVote(_voteId);
}
function _canExecute(uint256 _voteId) internal view returns (bool) {
Vote storage vote_ = votes[_voteId];
if (vote_.executed) {
return false;
}
// Voting is already decided
if (_isValuePct(vote_.yea, vote_.votingPower, vote_.supportRequiredPct)) {
return true;
}
// Vote ended?
if (_isVoteOpen(vote_)) {
return false;
}
// Has enough support?
uint256 totalVotes = vote_.yea.add(vote_.nay);
if (!_isValuePct(vote_.yea, totalVotes, vote_.supportRequiredPct)) {
return false;
}
// Has min quorum?
if (!_isValuePct(vote_.yea, vote_.votingPower, vote_.minAcceptQuorumPct)) {
return false;
}
return true;
}
function _canVote(uint256 _voteId, address _voter) internal view returns (bool) {
Vote storage vote_ = votes[_voteId];
return _isVoteOpen(vote_) && token.balanceOfAt(_voter, vote_.snapshotBlock) > 0;
}
function _isVoteOpen(Vote storage vote_) internal view returns (bool) {
return getTimestamp64() < vote_.startDate.add(voteTime) && !vote_.executed;
}
/**
* @dev Calculates whether `_value` is more than a percentage `_pct` of `_total`
*/
function _isValuePct(uint256 _value, uint256 _total, uint256 _pct) internal pure returns (bool) {
if (_total == 0) {
return false;
}
uint256 computedPct = _value.mul(PCT_BASE) / _total;
return computedPct > _pct;
}
}
// File: @aragon/ppf-contracts/contracts/IFeed.sol
pragma solidity ^0.4.18;
interface IFeed {
function ratePrecision() external pure returns (uint256);
function get(address base, address quote) external view returns (uint128 xrt, uint64 when);
}
// File: @aragon/apps-finance/contracts/Finance.sol
/*
* SPDX-License-Identitifer: GPL-3.0-or-later
*/
pragma solidity 0.4.24;
contract Finance is EtherTokenConstant, IsContract, AragonApp {
using SafeMath for uint256;
using SafeMath64 for uint64;
using SafeERC20 for ERC20;
bytes32 public constant CREATE_PAYMENTS_ROLE = keccak256("CREATE_PAYMENTS_ROLE");
bytes32 public constant CHANGE_PERIOD_ROLE = keccak256("CHANGE_PERIOD_ROLE");
bytes32 public constant CHANGE_BUDGETS_ROLE = keccak256("CHANGE_BUDGETS_ROLE");
bytes32 public constant EXECUTE_PAYMENTS_ROLE = keccak256("EXECUTE_PAYMENTS_ROLE");
bytes32 public constant MANAGE_PAYMENTS_ROLE = keccak256("MANAGE_PAYMENTS_ROLE");
uint256 internal constant NO_SCHEDULED_PAYMENT = 0;
uint256 internal constant NO_TRANSACTION = 0;
uint256 internal constant MAX_SCHEDULED_PAYMENTS_PER_TX = 20;
uint256 internal constant MAX_UINT256 = uint256(-1);
uint64 internal constant MAX_UINT64 = uint64(-1);
uint64 internal constant MINIMUM_PERIOD = uint64(1 days);
string private constant ERROR_COMPLETE_TRANSITION = "FINANCE_COMPLETE_TRANSITION";
string private constant ERROR_NO_SCHEDULED_PAYMENT = "FINANCE_NO_SCHEDULED_PAYMENT";
string private constant ERROR_NO_TRANSACTION = "FINANCE_NO_TRANSACTION";
string private constant ERROR_NO_PERIOD = "FINANCE_NO_PERIOD";
string private constant ERROR_VAULT_NOT_CONTRACT = "FINANCE_VAULT_NOT_CONTRACT";
string private constant ERROR_SET_PERIOD_TOO_SHORT = "FINANCE_SET_PERIOD_TOO_SHORT";
string private constant ERROR_NEW_PAYMENT_AMOUNT_ZERO = "FINANCE_NEW_PAYMENT_AMOUNT_ZERO";
string private constant ERROR_NEW_PAYMENT_INTERVAL_ZERO = "FINANCE_NEW_PAYMENT_INTRVL_ZERO";
string private constant ERROR_NEW_PAYMENT_EXECS_ZERO = "FINANCE_NEW_PAYMENT_EXECS_ZERO";
string private constant ERROR_NEW_PAYMENT_IMMEDIATE = "FINANCE_NEW_PAYMENT_IMMEDIATE";
string private constant ERROR_RECOVER_AMOUNT_ZERO = "FINANCE_RECOVER_AMOUNT_ZERO";
string private constant ERROR_DEPOSIT_AMOUNT_ZERO = "FINANCE_DEPOSIT_AMOUNT_ZERO";
string private constant ERROR_ETH_VALUE_MISMATCH = "FINANCE_ETH_VALUE_MISMATCH";
string private constant ERROR_BUDGET = "FINANCE_BUDGET";
string private constant ERROR_EXECUTE_PAYMENT_NUM = "FINANCE_EXECUTE_PAYMENT_NUM";
string private constant ERROR_EXECUTE_PAYMENT_TIME = "FINANCE_EXECUTE_PAYMENT_TIME";
string private constant ERROR_PAYMENT_RECEIVER = "FINANCE_PAYMENT_RECEIVER";
string private constant ERROR_TOKEN_TRANSFER_FROM_REVERTED = "FINANCE_TKN_TRANSFER_FROM_REVERT";
string private constant ERROR_TOKEN_APPROVE_FAILED = "FINANCE_TKN_APPROVE_FAILED";
string private constant ERROR_PAYMENT_INACTIVE = "FINANCE_PAYMENT_INACTIVE";
string private constant ERROR_REMAINING_BUDGET = "FINANCE_REMAINING_BUDGET";
// Order optimized for storage
struct ScheduledPayment {
address token;
address receiver;
address createdBy;
bool inactive;
uint256 amount;
uint64 initialPaymentTime;
uint64 interval;
uint64 maxExecutions;
uint64 executions;
}
// Order optimized for storage
struct Transaction {
address token;
address entity;
bool isIncoming;
uint256 amount;
uint256 paymentId;
uint64 paymentExecutionNumber;
uint64 date;
uint64 periodId;
}
struct TokenStatement {
uint256 expenses;
uint256 income;
}
struct Period {
uint64 startTime;
uint64 endTime;
uint256 firstTransactionId;
uint256 lastTransactionId;
mapping (address => TokenStatement) tokenStatement;
}
struct Settings {
uint64 periodDuration;
mapping (address => uint256) budgets;
mapping (address => bool) hasBudget;
}
Vault public vault;
Settings internal settings;
// We are mimicing arrays, we use mappings instead to make app upgrade more graceful
mapping (uint256 => ScheduledPayment) internal scheduledPayments;
// Payments start at index 1, to allow us to use scheduledPayments[0] for transactions that are not
// linked to a scheduled payment
uint256 public paymentsNextIndex;
mapping (uint256 => Transaction) internal transactions;
uint256 public transactionsNextIndex;
mapping (uint64 => Period) internal periods;
uint64 public periodsLength;
event NewPeriod(uint64 indexed periodId, uint64 periodStarts, uint64 periodEnds);
event SetBudget(address indexed token, uint256 amount, bool hasBudget);
event NewPayment(uint256 indexed paymentId, address indexed recipient, uint64 maxExecutions, string reference);
event NewTransaction(uint256 indexed transactionId, bool incoming, address indexed entity, uint256 amount, string reference);
event ChangePaymentState(uint256 indexed paymentId, bool active);
event ChangePeriodDuration(uint64 newDuration);
event PaymentFailure(uint256 paymentId);
// Modifier used by all methods that impact accounting to make sure accounting period
// is changed before the operation if needed
// NOTE: its use **MUST** be accompanied by an initialization check
modifier transitionsPeriod {
bool completeTransition = _tryTransitionAccountingPeriod(getMaxPeriodTransitions());
require(completeTransition, ERROR_COMPLETE_TRANSITION);
_;
}
modifier scheduledPaymentExists(uint256 _paymentId) {
require(_paymentId > 0 && _paymentId < paymentsNextIndex, ERROR_NO_SCHEDULED_PAYMENT);
_;
}
modifier transactionExists(uint256 _transactionId) {
require(_transactionId > 0 && _transactionId < transactionsNextIndex, ERROR_NO_TRANSACTION);
_;
}
modifier periodExists(uint64 _periodId) {
require(_periodId < periodsLength, ERROR_NO_PERIOD);
_;
}
/**
* @notice Deposit ETH to the Vault, to avoid locking them in this Finance app forever
* @dev Send ETH to Vault. Send all the available balance.
*/
function () external payable isInitialized transitionsPeriod {
require(msg.value > 0, ERROR_DEPOSIT_AMOUNT_ZERO);
_deposit(
ETH,
msg.value,
"Ether transfer to Finance app",
msg.sender,
true
);
}
/**
* @notice Initialize Finance app for Vault at `_vault` with period length of `@transformTime(_periodDuration)`
* @param _vault Address of the vault Finance will rely on (non changeable)
* @param _periodDuration Duration in seconds of each period
*/
function initialize(Vault _vault, uint64 _periodDuration) external onlyInit {
initialized();
require(isContract(_vault), ERROR_VAULT_NOT_CONTRACT);
vault = _vault;
require(_periodDuration >= MINIMUM_PERIOD, ERROR_SET_PERIOD_TOO_SHORT);
settings.periodDuration = _periodDuration;
// Reserve the first scheduled payment index as an unused index for transactions not linked
// to a scheduled payment
scheduledPayments[0].inactive = true;
paymentsNextIndex = 1;
// Reserve the first transaction index as an unused index for periods with no transactions
transactionsNextIndex = 1;
// Start the first period
_newPeriod(getTimestamp64());
}
/**
* @notice Deposit `@tokenAmount(_token, _amount)`
* @dev Deposit for approved ERC20 tokens or ETH
* @param _token Address of deposited token
* @param _amount Amount of tokens sent
* @param _reference Reason for payment
*/
function deposit(address _token, uint256 _amount, string _reference) external payable isInitialized transitionsPeriod {
require(_amount > 0, ERROR_DEPOSIT_AMOUNT_ZERO);
if (_token == ETH) {
// Ensure that the ETH sent with the transaction equals the amount in the deposit
require(msg.value == _amount, ERROR_ETH_VALUE_MISMATCH);
}
_deposit(
_token,
_amount,
_reference,
msg.sender,
true
);
}
/**
* @notice Create a new payment of `@tokenAmount(_token, _amount)` to `_receiver` for '`_reference`'
* @dev Note that this function is protected by the `CREATE_PAYMENTS_ROLE` but uses `MAX_UINT256`
* as its interval auth parameter (as a sentinel value for "never repeating").
* While this protects against most cases (you typically want to set a baseline requirement
* for interval time), it does mean users will have to explicitly check for this case when
* granting a permission that includes a upperbound requirement on the interval time.
* @param _token Address of token for payment
* @param _receiver Address that will receive payment
* @param _amount Tokens that are paid every time the payment is due
* @param _reference String detailing payment reason
*/
function newImmediatePayment(address _token, address _receiver, uint256 _amount, string _reference)
external
// Use MAX_UINT256 as the interval parameter, as this payment will never repeat
// Payment time parameter is left as the last param as it was added later
authP(CREATE_PAYMENTS_ROLE, _arr(_token, _receiver, _amount, MAX_UINT256, uint256(1), getTimestamp()))
transitionsPeriod
{
require(_amount > 0, ERROR_NEW_PAYMENT_AMOUNT_ZERO);
_makePaymentTransaction(
_token,
_receiver,
_amount,
NO_SCHEDULED_PAYMENT, // unrelated to any payment id; it isn't created
0, // also unrelated to any payment executions
_reference
);
}
/**
* @notice Create a new payment of `@tokenAmount(_token, _amount)` to `_receiver` for `_reference`, executing `_maxExecutions` times at intervals of `@transformTime(_interval)`
* @dev See `newImmediatePayment()` for limitations on how the interval auth parameter can be used
* @param _token Address of token for payment
* @param _receiver Address that will receive payment
* @param _amount Tokens that are paid every time the payment is due
* @param _initialPaymentTime Timestamp for when the first payment is done
* @param _interval Number of seconds that need to pass between payment transactions
* @param _maxExecutions Maximum instances a payment can be executed
* @param _reference String detailing payment reason
*/
function newScheduledPayment(
address _token,
address _receiver,
uint256 _amount,
uint64 _initialPaymentTime,
uint64 _interval,
uint64 _maxExecutions,
string _reference
)
external
// Payment time parameter is left as the last param as it was added later
authP(CREATE_PAYMENTS_ROLE, _arr(_token, _receiver, _amount, uint256(_interval), uint256(_maxExecutions), uint256(_initialPaymentTime)))
transitionsPeriod
returns (uint256 paymentId)
{
require(_amount > 0, ERROR_NEW_PAYMENT_AMOUNT_ZERO);
require(_interval > 0, ERROR_NEW_PAYMENT_INTERVAL_ZERO);
require(_maxExecutions > 0, ERROR_NEW_PAYMENT_EXECS_ZERO);
// Token budget must not be set at all or allow at least one instance of this payment each period
require(!settings.hasBudget[_token] || settings.budgets[_token] >= _amount, ERROR_BUDGET);
// Don't allow creating single payments that are immediately executable, use `newImmediatePayment()` instead
if (_maxExecutions == 1) {
require(_initialPaymentTime > getTimestamp64(), ERROR_NEW_PAYMENT_IMMEDIATE);
}
paymentId = paymentsNextIndex++;
emit NewPayment(paymentId, _receiver, _maxExecutions, _reference);
ScheduledPayment storage payment = scheduledPayments[paymentId];
payment.token = _token;
payment.receiver = _receiver;
payment.amount = _amount;
payment.initialPaymentTime = _initialPaymentTime;
payment.interval = _interval;
payment.maxExecutions = _maxExecutions;
payment.createdBy = msg.sender;
// We skip checking how many times the new payment was executed to allow creating new
// scheduled payments before having enough vault balance
_executePayment(paymentId);
}
/**
* @notice Change period duration to `@transformTime(_periodDuration)`, effective for next accounting period
* @param _periodDuration Duration in seconds for accounting periods
*/
function setPeriodDuration(uint64 _periodDuration)
external
authP(CHANGE_PERIOD_ROLE, arr(uint256(_periodDuration), uint256(settings.periodDuration)))
transitionsPeriod
{
require(_periodDuration >= MINIMUM_PERIOD, ERROR_SET_PERIOD_TOO_SHORT);
settings.periodDuration = _periodDuration;
emit ChangePeriodDuration(_periodDuration);
}
/**
* @notice Set budget for `_token.symbol(): string` to `@tokenAmount(_token, _amount, false)`, effective immediately
* @param _token Address for token
* @param _amount New budget amount
*/
function setBudget(
address _token,
uint256 _amount
)
external
authP(CHANGE_BUDGETS_ROLE, arr(_token, _amount, settings.budgets[_token], uint256(settings.hasBudget[_token] ? 1 : 0)))
transitionsPeriod
{
settings.budgets[_token] = _amount;
if (!settings.hasBudget[_token]) {
settings.hasBudget[_token] = true;
}
emit SetBudget(_token, _amount, true);
}
/**
* @notice Remove spending limit for `_token.symbol(): string`, effective immediately
* @param _token Address for token
*/
function removeBudget(address _token)
external
authP(CHANGE_BUDGETS_ROLE, arr(_token, uint256(0), settings.budgets[_token], uint256(settings.hasBudget[_token] ? 1 : 0)))
transitionsPeriod
{
settings.budgets[_token] = 0;
settings.hasBudget[_token] = false;
emit SetBudget(_token, 0, false);
}
/**
* @notice Execute pending payment #`_paymentId`
* @dev Executes any payment (requires role)
* @param _paymentId Identifier for payment
*/
function executePayment(uint256 _paymentId)
external
authP(EXECUTE_PAYMENTS_ROLE, arr(_paymentId, scheduledPayments[_paymentId].amount))
scheduledPaymentExists(_paymentId)
transitionsPeriod
{
_executePaymentAtLeastOnce(_paymentId);
}
/**
* @notice Execute pending payment #`_paymentId`
* @dev Always allow receiver of a payment to trigger execution
* Initialization check is implicitly provided by `scheduledPaymentExists()` as new
* scheduled payments can only be created via `newScheduledPayment(),` which requires initialization
* @param _paymentId Identifier for payment
*/
function receiverExecutePayment(uint256 _paymentId) external scheduledPaymentExists(_paymentId) transitionsPeriod {
require(scheduledPayments[_paymentId].receiver == msg.sender, ERROR_PAYMENT_RECEIVER);
_executePaymentAtLeastOnce(_paymentId);
}
/**
* @notice `_active ? 'Activate' : 'Disable'` payment #`_paymentId`
* @dev Note that we do not require this action to transition periods, as it doesn't directly
* impact any accounting periods.
* Not having to transition periods also makes disabling payments easier to prevent funds
* from being pulled out in the event of a breach.
* @param _paymentId Identifier for payment
* @param _active Whether it will be active or inactive
*/
function setPaymentStatus(uint256 _paymentId, bool _active)
external
authP(MANAGE_PAYMENTS_ROLE, arr(_paymentId, uint256(_active ? 1 : 0)))
scheduledPaymentExists(_paymentId)
{
scheduledPayments[_paymentId].inactive = !_active;
emit ChangePaymentState(_paymentId, _active);
}
/**
* @notice Send tokens held in this contract to the Vault
* @dev Allows making a simple payment from this contract to the Vault, to avoid locked tokens.
* This contract should never receive tokens with a simple transfer call, but in case it
* happens, this function allows for their recovery.
* @param _token Token whose balance is going to be transferred.
*/
function recoverToVault(address _token) external isInitialized transitionsPeriod {
uint256 amount = _token == ETH ? address(this).balance : ERC20(_token).staticBalanceOf(address(this));
require(amount > 0, ERROR_RECOVER_AMOUNT_ZERO);
_deposit(
_token,
amount,
"Recover to Vault",
address(this),
false
);
}
/**
* @notice Transition accounting period if needed
* @dev Transitions accounting periods if needed. For preventing OOG attacks, a maxTransitions
* param is provided. If more than the specified number of periods need to be transitioned,
* it will return false.
* @param _maxTransitions Maximum periods that can be transitioned
* @return success Boolean indicating whether the accounting period is the correct one (if false,
* maxTransitions was surpased and another call is needed)
*/
function tryTransitionAccountingPeriod(uint64 _maxTransitions) external isInitialized returns (bool success) {
return _tryTransitionAccountingPeriod(_maxTransitions);
}
// Getter fns
/**
* @dev Disable recovery escape hatch if the app has been initialized, as it could be used
* maliciously to transfer funds in the Finance app to another Vault
* finance#recoverToVault() should be used to recover funds to the Finance's vault
*/
function allowRecoverability(address) public view returns (bool) {
return !hasInitialized();
}
function getPayment(uint256 _paymentId)
public
view
scheduledPaymentExists(_paymentId)
returns (
address token,
address receiver,
uint256 amount,
uint64 initialPaymentTime,
uint64 interval,
uint64 maxExecutions,
bool inactive,
uint64 executions,
address createdBy
)
{
ScheduledPayment storage payment = scheduledPayments[_paymentId];
token = payment.token;
receiver = payment.receiver;
amount = payment.amount;
initialPaymentTime = payment.initialPaymentTime;
interval = payment.interval;
maxExecutions = payment.maxExecutions;
executions = payment.executions;
inactive = payment.inactive;
createdBy = payment.createdBy;
}
function getTransaction(uint256 _transactionId)
public
view
transactionExists(_transactionId)
returns (
uint64 periodId,
uint256 amount,
uint256 paymentId,
uint64 paymentExecutionNumber,
address token,
address entity,
bool isIncoming,
uint64 date
)
{
Transaction storage transaction = transactions[_transactionId];
token = transaction.token;
entity = transaction.entity;
isIncoming = transaction.isIncoming;
date = transaction.date;
periodId = transaction.periodId;
amount = transaction.amount;
paymentId = transaction.paymentId;
paymentExecutionNumber = transaction.paymentExecutionNumber;
}
function getPeriod(uint64 _periodId)
public
view
periodExists(_periodId)
returns (
bool isCurrent,
uint64 startTime,
uint64 endTime,
uint256 firstTransactionId,
uint256 lastTransactionId
)
{
Period storage period = periods[_periodId];
isCurrent = _currentPeriodId() == _periodId;
startTime = period.startTime;
endTime = period.endTime;
firstTransactionId = period.firstTransactionId;
lastTransactionId = period.lastTransactionId;
}
function getPeriodTokenStatement(uint64 _periodId, address _token)
public
view
periodExists(_periodId)
returns (uint256 expenses, uint256 income)
{
TokenStatement storage tokenStatement = periods[_periodId].tokenStatement[_token];
expenses = tokenStatement.expenses;
income = tokenStatement.income;
}
/**
* @dev We have to check for initialization as periods are only valid after initializing
*/
function currentPeriodId() public view isInitialized returns (uint64) {
return _currentPeriodId();
}
/**
* @dev We have to check for initialization as periods are only valid after initializing
*/
function getPeriodDuration() public view isInitialized returns (uint64) {
return settings.periodDuration;
}
/**
* @dev We have to check for initialization as budgets are only valid after initializing
*/
function getBudget(address _token) public view isInitialized returns (uint256 budget, bool hasBudget) {
budget = settings.budgets[_token];
hasBudget = settings.hasBudget[_token];
}
/**
* @dev We have to check for initialization as budgets are only valid after initializing
*/
function getRemainingBudget(address _token) public view isInitialized returns (uint256) {
return _getRemainingBudget(_token);
}
/**
* @dev We have to check for initialization as budgets are only valid after initializing
*/
function canMakePayment(address _token, uint256 _amount) public view isInitialized returns (bool) {
return _canMakePayment(_token, _amount);
}
/**
* @dev Initialization check is implicitly provided by `scheduledPaymentExists()` as new
* scheduled payments can only be created via `newScheduledPayment(),` which requires initialization
*/
function nextPaymentTime(uint256 _paymentId) public view scheduledPaymentExists(_paymentId) returns (uint64) {
return _nextPaymentTime(_paymentId);
}
// Internal fns
function _deposit(address _token, uint256 _amount, string _reference, address _sender, bool _isExternalDeposit) internal {
_recordIncomingTransaction(
_token,
_sender,
_amount,
_reference
);
if (_token == ETH) {
vault.deposit.value(_amount)(ETH, _amount);
} else {
// First, transfer the tokens to Finance if necessary
// External deposit will be false when the assets were already in the Finance app
// and just need to be transferred to the Vault
if (_isExternalDeposit) {
// This assumes the sender has approved the tokens for Finance
require(
ERC20(_token).safeTransferFrom(msg.sender, address(this), _amount),
ERROR_TOKEN_TRANSFER_FROM_REVERTED
);
}
// Approve the tokens for the Vault (it does the actual transferring)
require(ERC20(_token).safeApprove(vault, _amount), ERROR_TOKEN_APPROVE_FAILED);
// Finally, initiate the deposit
vault.deposit(_token, _amount);
}
}
function _executePayment(uint256 _paymentId) internal returns (uint256) {
ScheduledPayment storage payment = scheduledPayments[_paymentId];
require(!payment.inactive, ERROR_PAYMENT_INACTIVE);
uint64 paid = 0;
while (_nextPaymentTime(_paymentId) <= getTimestamp64() && paid < MAX_SCHEDULED_PAYMENTS_PER_TX) {
if (!_canMakePayment(payment.token, payment.amount)) {
emit PaymentFailure(_paymentId);
break;
}
// The while() predicate prevents these two from ever overflowing
payment.executions += 1;
paid += 1;
// We've already checked the remaining budget with `_canMakePayment()`
_unsafeMakePaymentTransaction(
payment.token,
payment.receiver,
payment.amount,
_paymentId,
payment.executions,
""
);
}
return paid;
}
function _executePaymentAtLeastOnce(uint256 _paymentId) internal {
uint256 paid = _executePayment(_paymentId);
if (paid == 0) {
if (_nextPaymentTime(_paymentId) <= getTimestamp64()) {
revert(ERROR_EXECUTE_PAYMENT_NUM);
} else {
revert(ERROR_EXECUTE_PAYMENT_TIME);
}
}
}
function _makePaymentTransaction(
address _token,
address _receiver,
uint256 _amount,
uint256 _paymentId,
uint64 _paymentExecutionNumber,
string _reference
)
internal
{
require(_getRemainingBudget(_token) >= _amount, ERROR_REMAINING_BUDGET);
_unsafeMakePaymentTransaction(_token, _receiver, _amount, _paymentId, _paymentExecutionNumber, _reference);
}
/**
* @dev Unsafe version of _makePaymentTransaction that assumes you have already checked the
* remaining budget
*/
function _unsafeMakePaymentTransaction(
address _token,
address _receiver,
uint256 _amount,
uint256 _paymentId,
uint64 _paymentExecutionNumber,
string _reference
)
internal
{
_recordTransaction(
false,
_token,
_receiver,
_amount,
_paymentId,
_paymentExecutionNumber,
_reference
);
vault.transfer(_token, _receiver, _amount);
}
function _newPeriod(uint64 _startTime) internal returns (Period storage) {
// There should be no way for this to overflow since each period is at least one day
uint64 newPeriodId = periodsLength++;
Period storage period = periods[newPeriodId];
period.startTime = _startTime;
// Be careful here to not overflow; if startTime + periodDuration overflows, we set endTime
// to MAX_UINT64 (let's assume that's the end of time for now).
uint64 endTime = _startTime + settings.periodDuration - 1;
if (endTime < _startTime) { // overflowed
endTime = MAX_UINT64;
}
period.endTime = endTime;
emit NewPeriod(newPeriodId, period.startTime, period.endTime);
return period;
}
function _recordIncomingTransaction(
address _token,
address _sender,
uint256 _amount,
string _reference
)
internal
{
_recordTransaction(
true, // incoming transaction
_token,
_sender,
_amount,
NO_SCHEDULED_PAYMENT, // unrelated to any existing payment
0, // and no payment executions
_reference
);
}
function _recordTransaction(
bool _incoming,
address _token,
address _entity,
uint256 _amount,
uint256 _paymentId,
uint64 _paymentExecutionNumber,
string _reference
)
internal
{
uint64 periodId = _currentPeriodId();
TokenStatement storage tokenStatement = periods[periodId].tokenStatement[_token];
if (_incoming) {
tokenStatement.income = tokenStatement.income.add(_amount);
} else {
tokenStatement.expenses = tokenStatement.expenses.add(_amount);
}
uint256 transactionId = transactionsNextIndex++;
Transaction storage transaction = transactions[transactionId];
transaction.token = _token;
transaction.entity = _entity;
transaction.isIncoming = _incoming;
transaction.amount = _amount;
transaction.paymentId = _paymentId;
transaction.paymentExecutionNumber = _paymentExecutionNumber;
transaction.date = getTimestamp64();
transaction.periodId = periodId;
Period storage period = periods[periodId];
if (period.firstTransactionId == NO_TRANSACTION) {
period.firstTransactionId = transactionId;
}
emit NewTransaction(transactionId, _incoming, _entity, _amount, _reference);
}
function _tryTransitionAccountingPeriod(uint64 _maxTransitions) internal returns (bool success) {
Period storage currentPeriod = periods[_currentPeriodId()];
uint64 timestamp = getTimestamp64();
// Transition periods if necessary
while (timestamp > currentPeriod.endTime) {
if (_maxTransitions == 0) {
// Required number of transitions is over allowed number, return false indicating
// it didn't fully transition
return false;
}
// We're already protected from underflowing above
_maxTransitions -= 1;
// If there were any transactions in period, record which was the last
// In case 0 transactions occured, first and last tx id will be 0
if (currentPeriod.firstTransactionId != NO_TRANSACTION) {
currentPeriod.lastTransactionId = transactionsNextIndex.sub(1);
}
// New period starts at end time + 1
currentPeriod = _newPeriod(currentPeriod.endTime.add(1));
}
return true;
}
function _canMakePayment(address _token, uint256 _amount) internal view returns (bool) {
return _getRemainingBudget(_token) >= _amount && vault.balance(_token) >= _amount;
}
function _currentPeriodId() internal view returns (uint64) {
// There is no way for this to overflow if protected by an initialization check
return periodsLength - 1;
}
function _getRemainingBudget(address _token) internal view returns (uint256) {
if (!settings.hasBudget[_token]) {
return MAX_UINT256;
}
uint256 budget = settings.budgets[_token];
uint256 spent = periods[_currentPeriodId()].tokenStatement[_token].expenses;
// A budget decrease can cause the spent amount to be greater than period budget
// If so, return 0 to not allow more spending during period
if (spent >= budget) {
return 0;
}
// We're already protected from the overflow above
return budget - spent;
}
function _nextPaymentTime(uint256 _paymentId) internal view returns (uint64) {
ScheduledPayment storage payment = scheduledPayments[_paymentId];
if (payment.executions >= payment.maxExecutions) {
return MAX_UINT64; // re-executes in some billions of years time... should not need to worry
}
// Split in multiple lines to circumvent linter warning
uint64 increase = payment.executions.mul(payment.interval);
uint64 nextPayment = payment.initialPaymentTime.add(increase);
return nextPayment;
}
// Syntax sugar
function _arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e, uint256 _f) internal pure returns (uint256[] r) {
r = new uint256[](6);
r[0] = uint256(_a);
r[1] = uint256(_b);
r[2] = _c;
r[3] = _d;
r[4] = _e;
r[5] = _f;
}
// Mocked fns (overrided during testing)
// Must be view for mocking purposes
function getMaxPeriodTransitions() internal view returns (uint64) { return MAX_UINT64; }
}
// File: @aragon/apps-payroll/contracts/Payroll.sol
pragma solidity 0.4.24;
/**
* @title Payroll in multiple currencies
*/
contract Payroll is EtherTokenConstant, IForwarder, IsContract, AragonApp {
using SafeMath for uint256;
using SafeMath64 for uint64;
/* Hardcoded constants to save gas
* bytes32 constant public ADD_EMPLOYEE_ROLE = keccak256("ADD_EMPLOYEE_ROLE");
* bytes32 constant public TERMINATE_EMPLOYEE_ROLE = keccak256("TERMINATE_EMPLOYEE_ROLE");
* bytes32 constant public SET_EMPLOYEE_SALARY_ROLE = keccak256("SET_EMPLOYEE_SALARY_ROLE");
* bytes32 constant public ADD_BONUS_ROLE = keccak256("ADD_BONUS_ROLE");
* bytes32 constant public ADD_REIMBURSEMENT_ROLE = keccak256("ADD_REIMBURSEMENT_ROLE");
* bytes32 constant public MANAGE_ALLOWED_TOKENS_ROLE = keccak256("MANAGE_ALLOWED_TOKENS_ROLE");
* bytes32 constant public MODIFY_PRICE_FEED_ROLE = keccak256("MODIFY_PRICE_FEED_ROLE");
* bytes32 constant public MODIFY_RATE_EXPIRY_ROLE = keccak256("MODIFY_RATE_EXPIRY_ROLE");
*/
bytes32 constant public ADD_EMPLOYEE_ROLE = 0x9ecdc3c63716b45d0756eece5fe1614cae1889ec5a1ce62b3127c1f1f1615d6e;
bytes32 constant public TERMINATE_EMPLOYEE_ROLE = 0x69c67f914d12b6440e7ddf01961214818d9158fbcb19211e0ff42800fdea9242;
bytes32 constant public SET_EMPLOYEE_SALARY_ROLE = 0xea9ac65018da2421cf419ee2152371440c08267a193a33ccc1e39545d197e44d;
bytes32 constant public ADD_BONUS_ROLE = 0xceca7e2f5eb749a87aaf68f3f76d6b9251aa2f4600f13f93c5a4adf7a72df4ae;
bytes32 constant public ADD_REIMBURSEMENT_ROLE = 0x90698b9d54427f1e41636025017309bdb1b55320da960c8845bab0a504b01a16;
bytes32 constant public MANAGE_ALLOWED_TOKENS_ROLE = 0x0be34987c45700ee3fae8c55e270418ba903337decc6bacb1879504be9331c06;
bytes32 constant public MODIFY_PRICE_FEED_ROLE = 0x74350efbcba8b85341c5bbf70cc34e2a585fc1463524773a12fa0a71d4eb9302;
bytes32 constant public MODIFY_RATE_EXPIRY_ROLE = 0x79fe989a8899060dfbdabb174ebb96616fa9f1d9dadd739f8d814cbab452404e;
uint256 internal constant MAX_ALLOWED_TOKENS = 20; // prevent OOG issues with `payday()`
uint64 internal constant MIN_RATE_EXPIRY = uint64(1 minutes); // 1 min == ~4 block window to mine both a price feed update and a payout
uint256 internal constant MAX_UINT256 = uint256(-1);
uint64 internal constant MAX_UINT64 = uint64(-1);
string private constant ERROR_EMPLOYEE_DOESNT_EXIST = "PAYROLL_EMPLOYEE_DOESNT_EXIST";
string private constant ERROR_NON_ACTIVE_EMPLOYEE = "PAYROLL_NON_ACTIVE_EMPLOYEE";
string private constant ERROR_SENDER_DOES_NOT_MATCH = "PAYROLL_SENDER_DOES_NOT_MATCH";
string private constant ERROR_FINANCE_NOT_CONTRACT = "PAYROLL_FINANCE_NOT_CONTRACT";
string private constant ERROR_TOKEN_ALREADY_SET = "PAYROLL_TOKEN_ALREADY_SET";
string private constant ERROR_MAX_ALLOWED_TOKENS = "PAYROLL_MAX_ALLOWED_TOKENS";
string private constant ERROR_MIN_RATES_MISMATCH = "PAYROLL_MIN_RATES_MISMATCH";
string private constant ERROR_TOKEN_ALLOCATION_MISMATCH = "PAYROLL_TOKEN_ALLOCATION_MISMATCH";
string private constant ERROR_NOT_ALLOWED_TOKEN = "PAYROLL_NOT_ALLOWED_TOKEN";
string private constant ERROR_DISTRIBUTION_NOT_FULL = "PAYROLL_DISTRIBUTION_NOT_FULL";
string private constant ERROR_INVALID_PAYMENT_TYPE = "PAYROLL_INVALID_PAYMENT_TYPE";
string private constant ERROR_NOTHING_PAID = "PAYROLL_NOTHING_PAID";
string private constant ERROR_CAN_NOT_FORWARD = "PAYROLL_CAN_NOT_FORWARD";
string private constant ERROR_EMPLOYEE_NULL_ADDRESS = "PAYROLL_EMPLOYEE_NULL_ADDRESS";
string private constant ERROR_EMPLOYEE_ALREADY_EXIST = "PAYROLL_EMPLOYEE_ALREADY_EXIST";
string private constant ERROR_FEED_NOT_CONTRACT = "PAYROLL_FEED_NOT_CONTRACT";
string private constant ERROR_EXPIRY_TIME_TOO_SHORT = "PAYROLL_EXPIRY_TIME_TOO_SHORT";
string private constant ERROR_PAST_TERMINATION_DATE = "PAYROLL_PAST_TERMINATION_DATE";
string private constant ERROR_EXCHANGE_RATE_TOO_LOW = "PAYROLL_EXCHANGE_RATE_TOO_LOW";
string private constant ERROR_LAST_PAYROLL_DATE_TOO_BIG = "PAYROLL_LAST_DATE_TOO_BIG";
string private constant ERROR_INVALID_REQUESTED_AMOUNT = "PAYROLL_INVALID_REQUESTED_AMT";
enum PaymentType { Payroll, Reimbursement, Bonus }
struct Employee {
address accountAddress; // unique, but can be changed over time
uint256 denominationTokenSalary; // salary per second in denomination Token
uint256 accruedSalary; // keep track of any leftover accrued salary when changing salaries
uint256 bonus;
uint256 reimbursements;
uint64 lastPayroll;
uint64 endDate;
address[] allocationTokenAddresses;
mapping(address => uint256) allocationTokens;
}
Finance public finance;
address public denominationToken;
IFeed public feed;
uint64 public rateExpiryTime;
// Employees start at index 1, to allow us to use employees[0] to check for non-existent employees
uint256 public nextEmployee;
mapping(uint256 => Employee) internal employees; // employee ID -> employee
mapping(address => uint256) internal employeeIds; // employee address -> employee ID
mapping(address => bool) internal allowedTokens;
event AddEmployee(
uint256 indexed employeeId,
address indexed accountAddress,
uint256 initialDenominationSalary,
uint64 startDate,
string role
);
event TerminateEmployee(uint256 indexed employeeId, uint64 endDate);
event SetEmployeeSalary(uint256 indexed employeeId, uint256 denominationSalary);
event AddEmployeeAccruedSalary(uint256 indexed employeeId, uint256 amount);
event AddEmployeeBonus(uint256 indexed employeeId, uint256 amount);
event AddEmployeeReimbursement(uint256 indexed employeeId, uint256 amount);
event ChangeAddressByEmployee(uint256 indexed employeeId, address indexed newAccountAddress, address indexed oldAccountAddress);
event DetermineAllocation(uint256 indexed employeeId);
event SendPayment(
uint256 indexed employeeId,
address indexed accountAddress,
address indexed token,
uint256 amount,
uint256 exchangeRate,
string paymentReference
);
event SetAllowedToken(address indexed token, bool allowed);
event SetPriceFeed(address indexed feed);
event SetRateExpiryTime(uint64 time);
// Check employee exists by ID
modifier employeeIdExists(uint256 _employeeId) {
require(_employeeExists(_employeeId), ERROR_EMPLOYEE_DOESNT_EXIST);
_;
}
// Check employee exists and is still active
modifier employeeActive(uint256 _employeeId) {
// No need to check for existence as _isEmployeeIdActive() is false for non-existent employees
require(_isEmployeeIdActive(_employeeId), ERROR_NON_ACTIVE_EMPLOYEE);
_;
}
// Check sender matches an existing employee
modifier employeeMatches {
require(employees[employeeIds[msg.sender]].accountAddress == msg.sender, ERROR_SENDER_DOES_NOT_MATCH);
_;
}
/**
* @notice Initialize Payroll app for Finance at `_finance` and price feed at `_priceFeed`, setting denomination token to `_token` and exchange rate expiry time to `@transformTime(_rateExpiryTime)`
* @dev Note that we do not require _denominationToken to be a contract, as it may be a "fake"
* address used by the price feed to denominate fiat currencies
* @param _finance Address of the Finance app this Payroll app will rely on for payments (non-changeable)
* @param _denominationToken Address of the denomination token used for salary accounting
* @param _priceFeed Address of the price feed
* @param _rateExpiryTime Acceptable expiry time in seconds for the price feed's exchange rates
*/
function initialize(Finance _finance, address _denominationToken, IFeed _priceFeed, uint64 _rateExpiryTime) external onlyInit {
initialized();
require(isContract(_finance), ERROR_FINANCE_NOT_CONTRACT);
finance = _finance;
denominationToken = _denominationToken;
_setPriceFeed(_priceFeed);
_setRateExpiryTime(_rateExpiryTime);
// Employees start at index 1, to allow us to use employees[0] to check for non-existent employees
nextEmployee = 1;
}
/**
* @notice `_allowed ? 'Add' : 'Remove'` `_token.symbol(): string` `_allowed ? 'to' : 'from'` the set of allowed tokens
* @param _token Address of the token to be added or removed from the list of allowed tokens for payments
* @param _allowed Boolean to tell whether the given token should be added or removed from the list
*/
function setAllowedToken(address _token, bool _allowed) external authP(MANAGE_ALLOWED_TOKENS_ROLE, arr(_token)) {
require(allowedTokens[_token] != _allowed, ERROR_TOKEN_ALREADY_SET);
allowedTokens[_token] = _allowed;
emit SetAllowedToken(_token, _allowed);
}
/**
* @notice Set the price feed for exchange rates to `_feed`
* @param _feed Address of the new price feed instance
*/
function setPriceFeed(IFeed _feed) external authP(MODIFY_PRICE_FEED_ROLE, arr(_feed, feed)) {
_setPriceFeed(_feed);
}
/**
* @notice Set the acceptable expiry time for the price feed's exchange rates to `@transformTime(_time)`
* @dev Exchange rates older than the given value won't be accepted for payments and will cause payouts to revert
* @param _time The expiration time in seconds for exchange rates
*/
function setRateExpiryTime(uint64 _time) external authP(MODIFY_RATE_EXPIRY_ROLE, arr(uint256(_time), uint256(rateExpiryTime))) {
_setRateExpiryTime(_time);
}
/**
* @notice Add employee with address `_accountAddress` to payroll with an salary of `_initialDenominationSalary` per second, starting on `@formatDate(_startDate)`
* @param _accountAddress Employee's address to receive payroll
* @param _initialDenominationSalary Employee's salary, per second in denomination token
* @param _startDate Employee's starting timestamp in seconds (it actually sets their initial lastPayroll value)
* @param _role Employee's role
*/
function addEmployee(address _accountAddress, uint256 _initialDenominationSalary, uint64 _startDate, string _role)
external
authP(ADD_EMPLOYEE_ROLE, arr(_accountAddress, _initialDenominationSalary, uint256(_startDate)))
{
_addEmployee(_accountAddress, _initialDenominationSalary, _startDate, _role);
}
/**
* @notice Add `_amount` to bonus for employee #`_employeeId`
* @param _employeeId Employee's identifier
* @param _amount Amount to be added to the employee's bonuses in denomination token
*/
function addBonus(uint256 _employeeId, uint256 _amount)
external
authP(ADD_BONUS_ROLE, arr(_employeeId, _amount))
employeeActive(_employeeId)
{
_addBonus(_employeeId, _amount);
}
/**
* @notice Add `_amount` to reimbursements for employee #`_employeeId`
* @param _employeeId Employee's identifier
* @param _amount Amount to be added to the employee's reimbursements in denomination token
*/
function addReimbursement(uint256 _employeeId, uint256 _amount)
external
authP(ADD_REIMBURSEMENT_ROLE, arr(_employeeId, _amount))
employeeActive(_employeeId)
{
_addReimbursement(_employeeId, _amount);
}
/**
* @notice Set employee #`_employeeId`'s salary to `_denominationSalary` per second
* @dev This reverts if either the employee's owed salary or accrued salary overflows, to avoid
* losing any accrued salary for an employee due to the employer changing their salary.
* @param _employeeId Employee's identifier
* @param _denominationSalary Employee's new salary, per second in denomination token
*/
function setEmployeeSalary(uint256 _employeeId, uint256 _denominationSalary)
external
authP(SET_EMPLOYEE_SALARY_ROLE, arr(_employeeId, _denominationSalary, employees[_employeeId].denominationTokenSalary))
employeeActive(_employeeId)
{
Employee storage employee = employees[_employeeId];
// Accrue employee's owed salary; don't cap to revert on overflow
uint256 owed = _getOwedSalarySinceLastPayroll(employee, false);
_addAccruedSalary(_employeeId, owed);
// Update employee to track the new salary and payment date
employee.lastPayroll = getTimestamp64();
employee.denominationTokenSalary = _denominationSalary;
emit SetEmployeeSalary(_employeeId, _denominationSalary);
}
/**
* @notice Terminate employee #`_employeeId` on `@formatDate(_endDate)`
* @param _employeeId Employee's identifier
* @param _endDate Termination timestamp in seconds
*/
function terminateEmployee(uint256 _employeeId, uint64 _endDate)
external
authP(TERMINATE_EMPLOYEE_ROLE, arr(_employeeId, uint256(_endDate)))
employeeActive(_employeeId)
{
_terminateEmployee(_employeeId, _endDate);
}
/**
* @notice Change your employee account address to `_newAccountAddress`
* @dev Initialization check is implicitly provided by `employeeMatches` as new employees can
* only be added via `addEmployee(),` which requires initialization.
* As the employee is allowed to call this, we enforce non-reentrancy.
* @param _newAccountAddress New address to receive payments for the requesting employee
*/
function changeAddressByEmployee(address _newAccountAddress) external employeeMatches nonReentrant {
uint256 employeeId = employeeIds[msg.sender];
address oldAddress = employees[employeeId].accountAddress;
_setEmployeeAddress(employeeId, _newAccountAddress);
// Don't delete the old address until after setting the new address to check that the
// employee specified a new address
delete employeeIds[oldAddress];
emit ChangeAddressByEmployee(employeeId, _newAccountAddress, oldAddress);
}
/**
* @notice Set the token distribution for your payments
* @dev Initialization check is implicitly provided by `employeeMatches` as new employees can
* only be added via `addEmployee(),` which requires initialization.
* As the employee is allowed to call this, we enforce non-reentrancy.
* @param _tokens Array of token addresses; they must belong to the list of allowed tokens
* @param _distribution Array with each token's corresponding proportions (must be integers summing to 100)
*/
function determineAllocation(address[] _tokens, uint256[] _distribution) external employeeMatches nonReentrant {
// Check array lengthes match
require(_tokens.length <= MAX_ALLOWED_TOKENS, ERROR_MAX_ALLOWED_TOKENS);
require(_tokens.length == _distribution.length, ERROR_TOKEN_ALLOCATION_MISMATCH);
uint256 employeeId = employeeIds[msg.sender];
Employee storage employee = employees[employeeId];
// Delete previous token allocations
address[] memory previousAllowedTokenAddresses = employee.allocationTokenAddresses;
for (uint256 j = 0; j < previousAllowedTokenAddresses.length; j++) {
delete employee.allocationTokens[previousAllowedTokenAddresses[j]];
}
delete employee.allocationTokenAddresses;
// Set distributions only if given tokens are allowed
for (uint256 i = 0; i < _tokens.length; i++) {
employee.allocationTokenAddresses.push(_tokens[i]);
employee.allocationTokens[_tokens[i]] = _distribution[i];
}
_ensureEmployeeTokenAllocationsIsValid(employee);
emit DetermineAllocation(employeeId);
}
/**
* @notice Request your `_type == 0 ? 'salary' : _type == 1 ? 'reimbursements' : 'bonus'`
* @dev Reverts if no payments were made.
* Initialization check is implicitly provided by `employeeMatches` as new employees can
* only be added via `addEmployee(),` which requires initialization.
* As the employee is allowed to call this, we enforce non-reentrancy.
* @param _type Payment type being requested (Payroll, Reimbursement or Bonus)
* @param _requestedAmount Requested amount to pay for the payment type. Must be less than or equal to total owed amount for the payment type, or zero to request all.
* @param _minRates Array of employee's minimum acceptable rates for their allowed payment tokens
*/
function payday(PaymentType _type, uint256 _requestedAmount, uint256[] _minRates) external employeeMatches nonReentrant {
uint256 paymentAmount;
uint256 employeeId = employeeIds[msg.sender];
Employee storage employee = employees[employeeId];
_ensureEmployeeTokenAllocationsIsValid(employee);
require(_minRates.length == 0 || _minRates.length == employee.allocationTokenAddresses.length, ERROR_MIN_RATES_MISMATCH);
// Do internal employee accounting
if (_type == PaymentType.Payroll) {
// Salary is capped here to avoid reverting at this point if it becomes too big
// (so employees aren't DDOSed if their salaries get too large)
// If we do use a capped value, the employee's lastPayroll date will be adjusted accordingly
uint256 totalOwedSalary = _getTotalOwedCappedSalary(employee);
paymentAmount = _ensurePaymentAmount(totalOwedSalary, _requestedAmount);
_updateEmployeeAccountingBasedOnPaidSalary(employee, paymentAmount);
} else if (_type == PaymentType.Reimbursement) {
uint256 owedReimbursements = employee.reimbursements;
paymentAmount = _ensurePaymentAmount(owedReimbursements, _requestedAmount);
employee.reimbursements = owedReimbursements.sub(paymentAmount);
} else if (_type == PaymentType.Bonus) {
uint256 owedBonusAmount = employee.bonus;
paymentAmount = _ensurePaymentAmount(owedBonusAmount, _requestedAmount);
employee.bonus = owedBonusAmount.sub(paymentAmount);
} else {
revert(ERROR_INVALID_PAYMENT_TYPE);
}
// Actually transfer the owed funds
require(_transferTokensAmount(employeeId, _type, paymentAmount, _minRates), ERROR_NOTHING_PAID);
_removeEmployeeIfTerminatedAndPaidOut(employeeId);
}
// Forwarding fns
/**
* @dev IForwarder interface conformance. Tells whether the Payroll app is a forwarder or not.
* @return Always true
*/
function isForwarder() external pure returns (bool) {
return true;
}
/**
* @notice Execute desired action as an active employee
* @dev IForwarder interface conformance. Allows active employees to run EVMScripts in the context of the Payroll app.
* @param _evmScript Script being executed
*/
function forward(bytes _evmScript) public {
require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD);
bytes memory input = new bytes(0); // TODO: Consider input for this
// Add the Finance app to the blacklist to disallow employees from executing actions on the
// Finance app from Payroll's context (since Payroll requires permissions on Finance)
address[] memory blacklist = new address[](1);
blacklist[0] = address(finance);
runScript(_evmScript, input, blacklist);
}
/**
* @dev IForwarder interface conformance. Tells whether a given address can forward actions or not.
* @param _sender Address of the account intending to forward an action
* @return True if the given address is an active employee, false otherwise
*/
function canForward(address _sender, bytes) public view returns (bool) {
return _isEmployeeIdActive(employeeIds[_sender]);
}
// Getter fns
/**
* @dev Return employee's identifier by their account address
* @param _accountAddress Employee's address to receive payments
* @return Employee's identifier
*/
function getEmployeeIdByAddress(address _accountAddress) public view returns (uint256) {
require(employeeIds[_accountAddress] != uint256(0), ERROR_EMPLOYEE_DOESNT_EXIST);
return employeeIds[_accountAddress];
}
/**
* @dev Return all information for employee by their ID
* @param _employeeId Employee's identifier
* @return Employee's address to receive payments
* @return Employee's salary, per second in denomination token
* @return Employee's accrued salary
* @return Employee's bonus amount
* @return Employee's reimbursements amount
* @return Employee's last payment date
* @return Employee's termination date (max uint64 if none)
* @return Employee's allowed payment tokens
*/
function getEmployee(uint256 _employeeId)
public
view
employeeIdExists(_employeeId)
returns (
address accountAddress,
uint256 denominationSalary,
uint256 accruedSalary,
uint256 bonus,
uint256 reimbursements,
uint64 lastPayroll,
uint64 endDate,
address[] allocationTokens
)
{
Employee storage employee = employees[_employeeId];
accountAddress = employee.accountAddress;
denominationSalary = employee.denominationTokenSalary;
accruedSalary = employee.accruedSalary;
bonus = employee.bonus;
reimbursements = employee.reimbursements;
lastPayroll = employee.lastPayroll;
endDate = employee.endDate;
allocationTokens = employee.allocationTokenAddresses;
}
/**
* @dev Get owed salary since last payroll for an employee. It will take into account the accrued salary as well.
* The result will be capped to max uint256 to avoid having an overflow.
* @return Employee's total owed salary: current owed payroll since the last payroll date, plus the accrued salary.
*/
function getTotalOwedSalary(uint256 _employeeId) public view employeeIdExists(_employeeId) returns (uint256) {
return _getTotalOwedCappedSalary(employees[_employeeId]);
}
/**
* @dev Get an employee's payment allocation for a token
* @param _employeeId Employee's identifier
* @param _token Token to query the payment allocation for
* @return Employee's payment allocation for the token being queried
*/
function getAllocation(uint256 _employeeId, address _token) public view employeeIdExists(_employeeId) returns (uint256) {
return employees[_employeeId].allocationTokens[_token];
}
/**
* @dev Check if a token is allowed to be used for payments
* @param _token Address of the token to be checked
* @return True if the given token is allowed, false otherwise
*/
function isTokenAllowed(address _token) public view isInitialized returns (bool) {
return allowedTokens[_token];
}
// Internal fns
/**
* @dev Set the price feed used for exchange rates
* @param _feed Address of the new price feed instance
*/
function _setPriceFeed(IFeed _feed) internal {
require(isContract(_feed), ERROR_FEED_NOT_CONTRACT);
feed = _feed;
emit SetPriceFeed(feed);
}
/**
* @dev Set the exchange rate expiry time in seconds.
* Exchange rates older than the given value won't be accepted for payments and will cause
* payouts to revert.
* @param _time The expiration time in seconds for exchange rates
*/
function _setRateExpiryTime(uint64 _time) internal {
// Require a sane minimum for the rate expiry time
require(_time >= MIN_RATE_EXPIRY, ERROR_EXPIRY_TIME_TOO_SHORT);
rateExpiryTime = _time;
emit SetRateExpiryTime(rateExpiryTime);
}
/**
* @dev Add a new employee to Payroll
* @param _accountAddress Employee's address to receive payroll
* @param _initialDenominationSalary Employee's salary, per second in denomination token
* @param _startDate Employee's starting timestamp in seconds
* @param _role Employee's role
*/
function _addEmployee(address _accountAddress, uint256 _initialDenominationSalary, uint64 _startDate, string _role) internal {
uint256 employeeId = nextEmployee++;
_setEmployeeAddress(employeeId, _accountAddress);
Employee storage employee = employees[employeeId];
employee.denominationTokenSalary = _initialDenominationSalary;
employee.lastPayroll = _startDate;
employee.endDate = MAX_UINT64;
emit AddEmployee(employeeId, _accountAddress, _initialDenominationSalary, _startDate, _role);
}
/**
* @dev Add amount to an employee's bonuses
* @param _employeeId Employee's identifier
* @param _amount Amount be added to the employee's bonuses in denomination token
*/
function _addBonus(uint256 _employeeId, uint256 _amount) internal {
Employee storage employee = employees[_employeeId];
employee.bonus = employee.bonus.add(_amount);
emit AddEmployeeBonus(_employeeId, _amount);
}
/**
* @dev Add amount to an employee's reimbursements
* @param _employeeId Employee's identifier
* @param _amount Amount be added to the employee's reimbursements in denomination token
*/
function _addReimbursement(uint256 _employeeId, uint256 _amount) internal {
Employee storage employee = employees[_employeeId];
employee.reimbursements = employee.reimbursements.add(_amount);
emit AddEmployeeReimbursement(_employeeId, _amount);
}
/**
* @dev Add amount to an employee's accrued salary
* @param _employeeId Employee's identifier
* @param _amount Amount be added to the employee's accrued salary in denomination token
*/
function _addAccruedSalary(uint256 _employeeId, uint256 _amount) internal {
Employee storage employee = employees[_employeeId];
employee.accruedSalary = employee.accruedSalary.add(_amount);
emit AddEmployeeAccruedSalary(_employeeId, _amount);
}
/**
* @dev Set an employee's account address
* @param _employeeId Employee's identifier
* @param _accountAddress Employee's address to receive payroll
*/
function _setEmployeeAddress(uint256 _employeeId, address _accountAddress) internal {
// Check address is non-null
require(_accountAddress != address(0), ERROR_EMPLOYEE_NULL_ADDRESS);
// Check address isn't already being used
require(employeeIds[_accountAddress] == uint256(0), ERROR_EMPLOYEE_ALREADY_EXIST);
employees[_employeeId].accountAddress = _accountAddress;
// Create IDs mapping
employeeIds[_accountAddress] = _employeeId;
}
/**
* @dev Terminate employee on end date
* @param _employeeId Employee's identifier
* @param _endDate Termination timestamp in seconds
*/
function _terminateEmployee(uint256 _employeeId, uint64 _endDate) internal {
// Prevent past termination dates
require(_endDate >= getTimestamp64(), ERROR_PAST_TERMINATION_DATE);
employees[_employeeId].endDate = _endDate;
emit TerminateEmployee(_employeeId, _endDate);
}
/**
* @dev Loop over allowed tokens to send requested amount to the employee in their desired allocation
* @param _employeeId Employee's identifier
* @param _totalAmount Total amount to be transferred to the employee distributed in accordance to the employee's token allocation.
* @param _type Payment type being transferred (Payroll, Reimbursement or Bonus)
* @param _minRates Array of employee's minimum acceptable rates for their allowed payment tokens
* @return True if there was at least one token transfer
*/
function _transferTokensAmount(uint256 _employeeId, PaymentType _type, uint256 _totalAmount, uint256[] _minRates) internal returns (bool somethingPaid) {
if (_totalAmount == 0) {
return false;
}
Employee storage employee = employees[_employeeId];
address employeeAddress = employee.accountAddress;
string memory paymentReference = _paymentReferenceFor(_type);
address[] storage allocationTokenAddresses = employee.allocationTokenAddresses;
for (uint256 i = 0; i < allocationTokenAddresses.length; i++) {
address token = allocationTokenAddresses[i];
uint256 tokenAllocation = employee.allocationTokens[token];
if (tokenAllocation != uint256(0)) {
// Get the exchange rate for the payout token in denomination token,
// as we do accounting in denomination tokens
uint256 exchangeRate = _getExchangeRateInDenominationToken(token);
require(_minRates.length > 0 ? exchangeRate >= _minRates[i] : exchangeRate > 0, ERROR_EXCHANGE_RATE_TOO_LOW);
// Convert amount (in denomination tokens) to payout token and apply allocation
uint256 tokenAmount = _totalAmount.mul(exchangeRate).mul(tokenAllocation);
// Divide by 100 for the allocation percentage and by the exchange rate precision
tokenAmount = tokenAmount.div(100).div(feed.ratePrecision());
// Finance reverts if the payment wasn't possible
finance.newImmediatePayment(token, employeeAddress, tokenAmount, paymentReference);
emit SendPayment(_employeeId, employeeAddress, token, tokenAmount, exchangeRate, paymentReference);
somethingPaid = true;
}
}
}
/**
* @dev Remove employee if there are no owed funds and employee's end date has been reached
* @param _employeeId Employee's identifier
*/
function _removeEmployeeIfTerminatedAndPaidOut(uint256 _employeeId) internal {
Employee storage employee = employees[_employeeId];
if (
employee.lastPayroll == employee.endDate &&
(employee.accruedSalary == 0 && employee.bonus == 0 && employee.reimbursements == 0)
) {
delete employeeIds[employee.accountAddress];
delete employees[_employeeId];
}
}
/**
* @dev Updates the accrued salary and payroll date of an employee based on a payment amount and
* their currently owed salary since last payroll date
* @param _employee Employee struct in storage
* @param _paymentAmount Amount being paid to the employee
*/
function _updateEmployeeAccountingBasedOnPaidSalary(Employee storage _employee, uint256 _paymentAmount) internal {
uint256 accruedSalary = _employee.accruedSalary;
if (_paymentAmount <= accruedSalary) {
// Employee is only cashing out some previously owed salary so we don't need to update
// their last payroll date
// No need to use SafeMath as we already know _paymentAmount <= accruedSalary
_employee.accruedSalary = accruedSalary - _paymentAmount;
return;
}
// Employee is cashing out some of their currently owed salary so their last payroll date
// needs to be modified based on the amount of salary paid
uint256 currentSalaryPaid = _paymentAmount;
if (accruedSalary > 0) {
// Employee is cashing out a mixed amount between previous and current owed salaries;
// first use up their accrued salary
// No need to use SafeMath here as we already know _paymentAmount > accruedSalary
currentSalaryPaid = _paymentAmount - accruedSalary;
// We finally need to clear their accrued salary
_employee.accruedSalary = 0;
}
uint256 salary = _employee.denominationTokenSalary;
uint256 timeDiff = currentSalaryPaid.div(salary);
// If they're being paid an amount that doesn't match perfectly with the adjusted time
// (up to a seconds' worth of salary), add the second and put the extra remaining salary
// into their accrued salary
uint256 extraSalary = currentSalaryPaid % salary;
if (extraSalary > 0) {
timeDiff = timeDiff.add(1);
_employee.accruedSalary = salary - extraSalary;
}
uint256 lastPayrollDate = uint256(_employee.lastPayroll).add(timeDiff);
// Even though this function should never receive a currentSalaryPaid value that would
// result in the lastPayrollDate being higher than the current time,
// let's double check to be safe
require(lastPayrollDate <= uint256(getTimestamp64()), ERROR_LAST_PAYROLL_DATE_TOO_BIG);
// Already know lastPayrollDate must fit in uint64 from above
_employee.lastPayroll = uint64(lastPayrollDate);
}
/**
* @dev Tell whether an employee is registered in this Payroll or not
* @param _employeeId Employee's identifier
* @return True if the given employee ID belongs to an registered employee, false otherwise
*/
function _employeeExists(uint256 _employeeId) internal view returns (bool) {
return employees[_employeeId].accountAddress != address(0);
}
/**
* @dev Tell whether an employee has a valid token allocation or not.
* A valid allocation is one that sums to 100 and only includes allowed tokens.
* @param _employee Employee struct in storage
* @return Reverts if employee's allocation is invalid
*/
function _ensureEmployeeTokenAllocationsIsValid(Employee storage _employee) internal view {
uint256 sum = 0;
address[] memory allocationTokenAddresses = _employee.allocationTokenAddresses;
for (uint256 i = 0; i < allocationTokenAddresses.length; i++) {
address token = allocationTokenAddresses[i];
require(allowedTokens[token], ERROR_NOT_ALLOWED_TOKEN);
sum = sum.add(_employee.allocationTokens[token]);
}
require(sum == 100, ERROR_DISTRIBUTION_NOT_FULL);
}
/**
* @dev Tell whether an employee is still active or not
* @param _employee Employee struct in storage
* @return True if the employee exists and has an end date that has not been reached yet, false otherwise
*/
function _isEmployeeActive(Employee storage _employee) internal view returns (bool) {
return _employee.endDate >= getTimestamp64();
}
/**
* @dev Tell whether an employee id is still active or not
* @param _employeeId Employee's identifier
* @return True if the employee exists and has an end date that has not been reached yet, false otherwise
*/
function _isEmployeeIdActive(uint256 _employeeId) internal view returns (bool) {
return _isEmployeeActive(employees[_employeeId]);
}
/**
* @dev Get exchange rate for a token based on the denomination token.
* As an example, if the denomination token was USD and ETH's price was 100USD,
* this would return 0.01 * precision rate for ETH.
* @param _token Token to get price of in denomination tokens
* @return Exchange rate (multiplied by the PPF rate precision)
*/
function _getExchangeRateInDenominationToken(address _token) internal view returns (uint256) {
// xrt is the number of `_token` that can be exchanged for one `denominationToken`
(uint128 xrt, uint64 when) = feed.get(
denominationToken, // Base (e.g. USD)
_token // Quote (e.g. ETH)
);
// Check the price feed is recent enough
if (getTimestamp64().sub(when) >= rateExpiryTime) {
return 0;
}
return uint256(xrt);
}
/**
* @dev Get owed salary since last payroll for an employee
* @param _employee Employee struct in storage
* @param _capped Safely cap the owed salary at max uint
* @return Owed salary in denomination tokens since last payroll for the employee.
* If _capped is false, it reverts in case of an overflow.
*/
function _getOwedSalarySinceLastPayroll(Employee storage _employee, bool _capped) internal view returns (uint256) {
uint256 timeDiff = _getOwedPayrollPeriod(_employee);
if (timeDiff == 0) {
return 0;
}
uint256 salary = _employee.denominationTokenSalary;
if (_capped) {
// Return max uint if the result overflows
uint256 result = salary * timeDiff;
return (result / timeDiff != salary) ? MAX_UINT256 : result;
} else {
return salary.mul(timeDiff);
}
}
/**
* @dev Get owed payroll period for an employee
* @param _employee Employee struct in storage
* @return Owed time in seconds since the employee's last payroll date
*/
function _getOwedPayrollPeriod(Employee storage _employee) internal view returns (uint256) {
// Get the min of current date and termination date
uint64 date = _isEmployeeActive(_employee) ? getTimestamp64() : _employee.endDate;
// Make sure we don't revert if we try to get the owed salary for an employee whose last
// payroll date is now or in the future
// This can happen either by adding new employees with start dates in the future, to allow
// us to change their salary before their start date, or by terminating an employee and
// paying out their full owed salary
if (date <= _employee.lastPayroll) {
return 0;
}
// Return time diff in seconds, no need to use SafeMath as the underflow was covered by the previous check
return uint256(date - _employee.lastPayroll);
}
/**
* @dev Get owed salary since last payroll for an employee. It will take into account the accrued salary as well.
* The result will be capped to max uint256 to avoid having an overflow.
* @param _employee Employee struct in storage
* @return Employee's total owed salary: current owed payroll since the last payroll date, plus the accrued salary.
*/
function _getTotalOwedCappedSalary(Employee storage _employee) internal view returns (uint256) {
uint256 currentOwedSalary = _getOwedSalarySinceLastPayroll(_employee, true); // cap amount
uint256 totalOwedSalary = currentOwedSalary + _employee.accruedSalary;
if (totalOwedSalary < currentOwedSalary) {
totalOwedSalary = MAX_UINT256;
}
return totalOwedSalary;
}
/**
* @dev Get payment reference for a given payment type
* @param _type Payment type to query the reference of
* @return Payment reference for the given payment type
*/
function _paymentReferenceFor(PaymentType _type) internal pure returns (string memory) {
if (_type == PaymentType.Payroll) {
return "Employee salary";
} else if (_type == PaymentType.Reimbursement) {
return "Employee reimbursement";
} if (_type == PaymentType.Bonus) {
return "Employee bonus";
}
revert(ERROR_INVALID_PAYMENT_TYPE);
}
function _ensurePaymentAmount(uint256 _owedAmount, uint256 _requestedAmount) private pure returns (uint256) {
require(_owedAmount > 0, ERROR_NOTHING_PAID);
require(_owedAmount >= _requestedAmount, ERROR_INVALID_REQUESTED_AMOUNT);
return _requestedAmount > 0 ? _requestedAmount : _owedAmount;
}
}
// File: @aragon/apps-token-manager/contracts/TokenManager.sol
/*
* SPDX-License-Identitifer: GPL-3.0-or-later
*/
/* solium-disable function-order */
pragma solidity 0.4.24;
contract TokenManager is ITokenController, IForwarder, AragonApp {
using SafeMath for uint256;
bytes32 public constant MINT_ROLE = keccak256("MINT_ROLE");
bytes32 public constant ISSUE_ROLE = keccak256("ISSUE_ROLE");
bytes32 public constant ASSIGN_ROLE = keccak256("ASSIGN_ROLE");
bytes32 public constant REVOKE_VESTINGS_ROLE = keccak256("REVOKE_VESTINGS_ROLE");
bytes32 public constant BURN_ROLE = keccak256("BURN_ROLE");
uint256 public constant MAX_VESTINGS_PER_ADDRESS = 50;
string private constant ERROR_CALLER_NOT_TOKEN = "TM_CALLER_NOT_TOKEN";
string private constant ERROR_NO_VESTING = "TM_NO_VESTING";
string private constant ERROR_TOKEN_CONTROLLER = "TM_TOKEN_CONTROLLER";
string private constant ERROR_MINT_RECEIVER_IS_TM = "TM_MINT_RECEIVER_IS_TM";
string private constant ERROR_VESTING_TO_TM = "TM_VESTING_TO_TM";
string private constant ERROR_TOO_MANY_VESTINGS = "TM_TOO_MANY_VESTINGS";
string private constant ERROR_WRONG_CLIFF_DATE = "TM_WRONG_CLIFF_DATE";
string private constant ERROR_VESTING_NOT_REVOKABLE = "TM_VESTING_NOT_REVOKABLE";
string private constant ERROR_REVOKE_TRANSFER_FROM_REVERTED = "TM_REVOKE_TRANSFER_FROM_REVERTED";
string private constant ERROR_CAN_NOT_FORWARD = "TM_CAN_NOT_FORWARD";
string private constant ERROR_BALANCE_INCREASE_NOT_ALLOWED = "TM_BALANCE_INC_NOT_ALLOWED";
string private constant ERROR_ASSIGN_TRANSFER_FROM_REVERTED = "TM_ASSIGN_TRANSFER_FROM_REVERTED";
struct TokenVesting {
uint256 amount;
uint64 start;
uint64 cliff;
uint64 vesting;
bool revokable;
}
// Note that we COMPLETELY trust this MiniMeToken to not be malicious for proper operation of this contract
MiniMeToken public token;
uint256 public maxAccountTokens;
// We are mimicing an array in the inner mapping, we use a mapping instead to make app upgrade more graceful
mapping (address => mapping (uint256 => TokenVesting)) internal vestings;
mapping (address => uint256) public vestingsLengths;
// Other token specific events can be watched on the token address directly (avoids duplication)
event NewVesting(address indexed receiver, uint256 vestingId, uint256 amount);
event RevokeVesting(address indexed receiver, uint256 vestingId, uint256 nonVestedAmount);
modifier onlyToken() {
require(msg.sender == address(token), ERROR_CALLER_NOT_TOKEN);
_;
}
modifier vestingExists(address _holder, uint256 _vestingId) {
// TODO: it's not checking for gaps that may appear because of deletes in revokeVesting function
require(_vestingId < vestingsLengths[_holder], ERROR_NO_VESTING);
_;
}
/**
* @notice Initialize Token Manager for `_token.symbol(): string`, whose tokens are `transferable ? 'not' : ''` transferable`_maxAccountTokens > 0 ? ' and limited to a maximum of ' + @tokenAmount(_token, _maxAccountTokens, false) + ' per account' : ''`
* @param _token MiniMeToken address for the managed token (Token Manager instance must be already set as the token controller)
* @param _transferable whether the token can be transferred by holders
* @param _maxAccountTokens Maximum amount of tokens an account can have (0 for infinite tokens)
*/
function initialize(
MiniMeToken _token,
bool _transferable,
uint256 _maxAccountTokens
)
external
onlyInit
{
initialized();
require(_token.controller() == address(this), ERROR_TOKEN_CONTROLLER);
token = _token;
maxAccountTokens = _maxAccountTokens == 0 ? uint256(-1) : _maxAccountTokens;
if (token.transfersEnabled() != _transferable) {
token.enableTransfers(_transferable);
}
}
/**
* @notice Mint `@tokenAmount(self.token(): address, _amount, false)` tokens for `_receiver`
* @param _receiver The address receiving the tokens, cannot be the Token Manager itself (use `issue()` instead)
* @param _amount Number of tokens minted
*/
function mint(address _receiver, uint256 _amount) external authP(MINT_ROLE, arr(_receiver, _amount)) {
require(_receiver != address(this), ERROR_MINT_RECEIVER_IS_TM);
_mint(_receiver, _amount);
}
/**
* @notice Mint `@tokenAmount(self.token(): address, _amount, false)` tokens for the Token Manager
* @param _amount Number of tokens minted
*/
function issue(uint256 _amount) external authP(ISSUE_ROLE, arr(_amount)) {
_mint(address(this), _amount);
}
/**
* @notice Assign `@tokenAmount(self.token(): address, _amount, false)` tokens to `_receiver` from the Token Manager's holdings
* @param _receiver The address receiving the tokens
* @param _amount Number of tokens transferred
*/
function assign(address _receiver, uint256 _amount) external authP(ASSIGN_ROLE, arr(_receiver, _amount)) {
_assign(_receiver, _amount);
}
/**
* @notice Burn `@tokenAmount(self.token(): address, _amount, false)` tokens from `_holder`
* @param _holder Holder of tokens being burned
* @param _amount Number of tokens being burned
*/
function burn(address _holder, uint256 _amount) external authP(BURN_ROLE, arr(_holder, _amount)) {
// minime.destroyTokens() never returns false, only reverts on failure
token.destroyTokens(_holder, _amount);
}
/**
* @notice Assign `@tokenAmount(self.token(): address, _amount, false)` tokens to `_receiver` from the Token Manager's holdings with a `_revokable : 'revokable' : ''` vesting starting at `@formatDate(_start)`, cliff at `@formatDate(_cliff)` (first portion of tokens transferable), and completed vesting at `@formatDate(_vested)` (all tokens transferable)
* @param _receiver The address receiving the tokens, cannot be Token Manager itself
* @param _amount Number of tokens vested
* @param _start Date the vesting calculations start
* @param _cliff Date when the initial portion of tokens are transferable
* @param _vested Date when all tokens are transferable
* @param _revokable Whether the vesting can be revoked by the Token Manager
*/
function assignVested(
address _receiver,
uint256 _amount,
uint64 _start,
uint64 _cliff,
uint64 _vested,
bool _revokable
)
external
authP(ASSIGN_ROLE, arr(_receiver, _amount))
returns (uint256)
{
require(_receiver != address(this), ERROR_VESTING_TO_TM);
require(vestingsLengths[_receiver] < MAX_VESTINGS_PER_ADDRESS, ERROR_TOO_MANY_VESTINGS);
require(_start <= _cliff && _cliff <= _vested, ERROR_WRONG_CLIFF_DATE);
uint256 vestingId = vestingsLengths[_receiver]++;
vestings[_receiver][vestingId] = TokenVesting(
_amount,
_start,
_cliff,
_vested,
_revokable
);
_assign(_receiver, _amount);
emit NewVesting(_receiver, vestingId, _amount);
return vestingId;
}
/**
* @notice Revoke vesting #`_vestingId` from `_holder`, returning unvested tokens to the Token Manager
* @param _holder Address whose vesting to revoke
* @param _vestingId Numeric id of the vesting
*/
function revokeVesting(address _holder, uint256 _vestingId)
external
authP(REVOKE_VESTINGS_ROLE, arr(_holder))
vestingExists(_holder, _vestingId)
{
TokenVesting storage v = vestings[_holder][_vestingId];
require(v.revokable, ERROR_VESTING_NOT_REVOKABLE);
uint256 nonVested = _calculateNonVestedTokens(
v.amount,
getTimestamp(),
v.start,
v.cliff,
v.vesting
);
// To make vestingIds immutable over time, we just zero out the revoked vesting
// Clearing this out also allows the token transfer back to the Token Manager to succeed
delete vestings[_holder][_vestingId];
// transferFrom always works as controller
// onTransfer hook always allows if transfering to token controller
require(token.transferFrom(_holder, address(this), nonVested), ERROR_REVOKE_TRANSFER_FROM_REVERTED);
emit RevokeVesting(_holder, _vestingId, nonVested);
}
// ITokenController fns
// `onTransfer()`, `onApprove()`, and `proxyPayment()` are callbacks from the MiniMe token
// contract and are only meant to be called through the managed MiniMe token that gets assigned
// during initialization.
/*
* @dev Notifies the controller about a token transfer allowing the controller to decide whether
* to allow it or react if desired (only callable from the token).
* Initialization check is implicitly provided by `onlyToken()`.
* @param _from The origin of the transfer
* @param _to The destination of the transfer
* @param _amount The amount of the transfer
* @return False if the controller does not authorize the transfer
*/
function onTransfer(address _from, address _to, uint256 _amount) external onlyToken returns (bool) {
return _isBalanceIncreaseAllowed(_to, _amount) && _transferableBalance(_from, getTimestamp()) >= _amount;
}
/**
* @dev Notifies the controller about an approval allowing the controller to react if desired
* Initialization check is implicitly provided by `onlyToken()`.
* @return False if the controller does not authorize the approval
*/
function onApprove(address, address, uint) external onlyToken returns (bool) {
return true;
}
/**
* @dev Called when ether is sent to the MiniMe Token contract
* Initialization check is implicitly provided by `onlyToken()`.
* @return True if the ether is accepted, false for it to throw
*/
function proxyPayment(address) external payable onlyToken returns (bool) {
return false;
}
// Forwarding fns
function isForwarder() external pure returns (bool) {
return true;
}
/**
* @notice Execute desired action as a token holder
* @dev IForwarder interface conformance. Forwards any token holder action.
* @param _evmScript Script being executed
*/
function forward(bytes _evmScript) public {
require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD);
bytes memory input = new bytes(0); // TODO: Consider input for this
// Add the managed token to the blacklist to disallow a token holder from executing actions
// on the token controller's (this contract) behalf
address[] memory blacklist = new address[](1);
blacklist[0] = address(token);
runScript(_evmScript, input, blacklist);
}
function canForward(address _sender, bytes) public view returns (bool) {
return hasInitialized() && token.balanceOf(_sender) > 0;
}
// Getter fns
function getVesting(
address _recipient,
uint256 _vestingId
)
public
view
vestingExists(_recipient, _vestingId)
returns (
uint256 amount,
uint64 start,
uint64 cliff,
uint64 vesting,
bool revokable
)
{
TokenVesting storage tokenVesting = vestings[_recipient][_vestingId];
amount = tokenVesting.amount;
start = tokenVesting.start;
cliff = tokenVesting.cliff;
vesting = tokenVesting.vesting;
revokable = tokenVesting.revokable;
}
function spendableBalanceOf(address _holder) public view isInitialized returns (uint256) {
return _transferableBalance(_holder, getTimestamp());
}
function transferableBalance(address _holder, uint256 _time) public view isInitialized returns (uint256) {
return _transferableBalance(_holder, _time);
}
/**
* @dev Disable recovery escape hatch for own token,
* as the it has the concept of issuing tokens without assigning them
*/
function allowRecoverability(address _token) public view returns (bool) {
return _token != address(token);
}
// Internal fns
function _assign(address _receiver, uint256 _amount) internal {
require(_isBalanceIncreaseAllowed(_receiver, _amount), ERROR_BALANCE_INCREASE_NOT_ALLOWED);
// Must use transferFrom() as transfer() does not give the token controller full control
require(token.transferFrom(address(this), _receiver, _amount), ERROR_ASSIGN_TRANSFER_FROM_REVERTED);
}
function _mint(address _receiver, uint256 _amount) internal {
require(_isBalanceIncreaseAllowed(_receiver, _amount), ERROR_BALANCE_INCREASE_NOT_ALLOWED);
token.generateTokens(_receiver, _amount); // minime.generateTokens() never returns false
}
function _isBalanceIncreaseAllowed(address _receiver, uint256 _inc) internal view returns (bool) {
// Max balance doesn't apply to the token manager itself
if (_receiver == address(this)) {
return true;
}
return token.balanceOf(_receiver).add(_inc) <= maxAccountTokens;
}
/**
* @dev Calculate amount of non-vested tokens at a specifc time
* @param tokens The total amount of tokens vested
* @param time The time at which to check
* @param start The date vesting started
* @param cliff The cliff period
* @param vested The fully vested date
* @return The amount of non-vested tokens of a specific grant
* transferableTokens
* | _/-------- vestedTokens rect
* | _/
* | _/
* | _/
* | _/
* | /
* | .|
* | . |
* | . |
* | . |
* | . |
* | . |
* +===+===========+---------+----------> time
* Start Cliff Vested
*/
function _calculateNonVestedTokens(
uint256 tokens,
uint256 time,
uint256 start,
uint256 cliff,
uint256 vested
)
private
pure
returns (uint256)
{
// Shortcuts for before cliff and after vested cases.
if (time >= vested) {
return 0;
}
if (time < cliff) {
return tokens;
}
// Interpolate all vested tokens.
// As before cliff the shortcut returns 0, we can just calculate a value
// in the vesting rect (as shown in above's figure)
// vestedTokens = tokens * (time - start) / (vested - start)
// In assignVesting we enforce start <= cliff <= vested
// Here we shortcut time >= vested and time < cliff,
// so no division by 0 is possible
uint256 vestedTokens = tokens.mul(time.sub(start)) / vested.sub(start);
// tokens - vestedTokens
return tokens.sub(vestedTokens);
}
function _transferableBalance(address _holder, uint256 _time) internal view returns (uint256) {
uint256 transferable = token.balanceOf(_holder);
// This check is not strictly necessary for the current version of this contract, as
// Token Managers now cannot assign vestings to themselves.
// However, this was a possibility in the past, so in case there were vestings assigned to
// themselves, this will still return the correct value (entire balance, as the Token
// Manager does not have a spending limit on its own balance).
if (_holder != address(this)) {
uint256 vestingsCount = vestingsLengths[_holder];
for (uint256 i = 0; i < vestingsCount; i++) {
TokenVesting storage v = vestings[_holder][i];
uint256 nonTransferable = _calculateNonVestedTokens(
v.amount,
_time,
v.start,
v.cliff,
v.vesting
);
transferable = transferable.sub(nonTransferable);
}
}
return transferable;
}
}
// File: @aragon/apps-survey/contracts/Survey.sol
/*
* SPDX-License-Identitifer: GPL-3.0-or-later
*/
pragma solidity 0.4.24;
contract Survey is AragonApp {
using SafeMath for uint256;
using SafeMath64 for uint64;
bytes32 public constant CREATE_SURVEYS_ROLE = keccak256("CREATE_SURVEYS_ROLE");
bytes32 public constant MODIFY_PARTICIPATION_ROLE = keccak256("MODIFY_PARTICIPATION_ROLE");
uint64 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18
uint256 public constant ABSTAIN_VOTE = 0;
string private constant ERROR_MIN_PARTICIPATION = "SURVEY_MIN_PARTICIPATION";
string private constant ERROR_NO_SURVEY = "SURVEY_NO_SURVEY";
string private constant ERROR_NO_VOTING_POWER = "SURVEY_NO_VOTING_POWER";
string private constant ERROR_CAN_NOT_VOTE = "SURVEY_CAN_NOT_VOTE";
string private constant ERROR_VOTE_WRONG_INPUT = "SURVEY_VOTE_WRONG_INPUT";
string private constant ERROR_VOTE_WRONG_OPTION = "SURVEY_VOTE_WRONG_OPTION";
string private constant ERROR_NO_STAKE = "SURVEY_NO_STAKE";
string private constant ERROR_OPTIONS_NOT_ORDERED = "SURVEY_OPTIONS_NOT_ORDERED";
string private constant ERROR_NO_OPTION = "SURVEY_NO_OPTION";
struct OptionCast {
uint256 optionId;
uint256 stake;
}
/* Allows for multiple option votes.
* Index 0 is always used for the ABSTAIN_VOTE option, that's calculated automatically by the
* contract.
*/
struct MultiOptionVote {
uint256 optionsCastedLength;
// `castedVotes` simulates an array
// Each OptionCast in `castedVotes` must be ordered by ascending option IDs
mapping (uint256 => OptionCast) castedVotes;
}
struct SurveyStruct {
uint64 startDate;
uint64 snapshotBlock;
uint64 minParticipationPct;
uint256 options;
uint256 votingPower; // total tokens that can cast a vote
uint256 participation; // tokens that casted a vote
// Note that option IDs are from 1 to `options`, due to ABSTAIN_VOTE taking 0
mapping (uint256 => uint256) optionPower; // option ID -> voting power for option
mapping (address => MultiOptionVote) votes; // voter -> options voted, with its stakes
}
MiniMeToken public token;
uint64 public minParticipationPct;
uint64 public surveyTime;
// We are mimicing an array, we use a mapping instead to make app upgrade more graceful
mapping (uint256 => SurveyStruct) internal surveys;
uint256 public surveysLength;
event StartSurvey(uint256 indexed surveyId, address indexed creator, string metadata);
event CastVote(uint256 indexed surveyId, address indexed voter, uint256 option, uint256 stake, uint256 optionPower);
event ResetVote(uint256 indexed surveyId, address indexed voter, uint256 option, uint256 previousStake, uint256 optionPower);
event ChangeMinParticipation(uint64 minParticipationPct);
modifier acceptableMinParticipationPct(uint64 _minParticipationPct) {
require(_minParticipationPct > 0 && _minParticipationPct <= PCT_BASE, ERROR_MIN_PARTICIPATION);
_;
}
modifier surveyExists(uint256 _surveyId) {
require(_surveyId < surveysLength, ERROR_NO_SURVEY);
_;
}
/**
* @notice Initialize Survey app with `_token.symbol(): string` for governance, minimum acceptance participation of `@formatPct(_minParticipationPct)`%, and a voting duration of `@transformTime(_surveyTime)`
* @param _token MiniMeToken address that will be used as governance token
* @param _minParticipationPct Percentage of total voting power that must participate in a survey for it to be taken into account (expressed as a 10^18 percentage, (eg 10^16 = 1%, 10^18 = 100%)
* @param _surveyTime Seconds that a survey will be open for token holders to vote
*/
function initialize(
MiniMeToken _token,
uint64 _minParticipationPct,
uint64 _surveyTime
)
external
onlyInit
acceptableMinParticipationPct(_minParticipationPct)
{
initialized();
token = _token;
minParticipationPct = _minParticipationPct;
surveyTime = _surveyTime;
}
/**
* @notice Change minimum acceptance participation to `@formatPct(_minParticipationPct)`%
* @param _minParticipationPct New acceptance participation
*/
function changeMinAcceptParticipationPct(uint64 _minParticipationPct)
external
authP(MODIFY_PARTICIPATION_ROLE, arr(uint256(_minParticipationPct), uint256(minParticipationPct)))
acceptableMinParticipationPct(_minParticipationPct)
{
minParticipationPct = _minParticipationPct;
emit ChangeMinParticipation(_minParticipationPct);
}
/**
* @notice Create a new non-binding survey about "`_metadata`"
* @param _metadata Survey metadata
* @param _options Number of options voters can decide between
* @return surveyId id for newly created survey
*/
function newSurvey(string _metadata, uint256 _options) external auth(CREATE_SURVEYS_ROLE) returns (uint256 surveyId) {
uint64 snapshotBlock = getBlockNumber64() - 1; // avoid double voting in this very block
uint256 votingPower = token.totalSupplyAt(snapshotBlock);
require(votingPower > 0, ERROR_NO_VOTING_POWER);
surveyId = surveysLength++;
SurveyStruct storage survey = surveys[surveyId];
survey.startDate = getTimestamp64();
survey.snapshotBlock = snapshotBlock; // avoid double voting in this very block
survey.minParticipationPct = minParticipationPct;
survey.options = _options;
survey.votingPower = votingPower;
emit StartSurvey(surveyId, msg.sender, _metadata);
}
/**
* @notice Reset previously casted vote in survey #`_surveyId`, if any.
* @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only
* be created via `newSurvey(),` which requires initialization
* @param _surveyId Id for survey
*/
function resetVote(uint256 _surveyId) external surveyExists(_surveyId) {
require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE);
_resetVote(_surveyId);
}
/**
* @notice Vote for multiple options in survey #`_surveyId`.
* @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only
* be created via `newSurvey(),` which requires initialization
* @param _surveyId Id for survey
* @param _optionIds Array with indexes of supported options
* @param _stakes Number of tokens assigned to each option
*/
function voteOptions(uint256 _surveyId, uint256[] _optionIds, uint256[] _stakes)
external
surveyExists(_surveyId)
{
require(_optionIds.length == _stakes.length && _optionIds.length > 0, ERROR_VOTE_WRONG_INPUT);
require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE);
_voteOptions(_surveyId, _optionIds, _stakes);
}
/**
* @notice Vote option #`_optionId` in survey #`_surveyId`.
* @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only
* be created via `newSurvey(),` which requires initialization
* @dev It will use the whole balance.
* @param _surveyId Id for survey
* @param _optionId Index of supported option
*/
function voteOption(uint256 _surveyId, uint256 _optionId) external surveyExists(_surveyId) {
require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE);
SurveyStruct storage survey = surveys[_surveyId];
// This could re-enter, though we can asume the governance token is not maliciuous
uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock);
uint256[] memory options = new uint256[](1);
uint256[] memory stakes = new uint256[](1);
options[0] = _optionId;
stakes[0] = voterStake;
_voteOptions(_surveyId, options, stakes);
}
// Getter fns
function canVote(uint256 _surveyId, address _voter) public view surveyExists(_surveyId) returns (bool) {
SurveyStruct storage survey = surveys[_surveyId];
return _isSurveyOpen(survey) && token.balanceOfAt(_voter, survey.snapshotBlock) > 0;
}
function getSurvey(uint256 _surveyId)
public
view
surveyExists(_surveyId)
returns (
bool open,
uint64 startDate,
uint64 snapshotBlock,
uint64 minParticipation,
uint256 votingPower,
uint256 participation,
uint256 options
)
{
SurveyStruct storage survey = surveys[_surveyId];
open = _isSurveyOpen(survey);
startDate = survey.startDate;
snapshotBlock = survey.snapshotBlock;
minParticipation = survey.minParticipationPct;
votingPower = survey.votingPower;
participation = survey.participation;
options = survey.options;
}
/**
* @dev This is not meant to be used on-chain
*/
/* solium-disable-next-line function-order */
function getVoterState(uint256 _surveyId, address _voter)
external
view
surveyExists(_surveyId)
returns (uint256[] options, uint256[] stakes)
{
MultiOptionVote storage vote = surveys[_surveyId].votes[_voter];
if (vote.optionsCastedLength == 0) {
return (new uint256[](0), new uint256[](0));
}
options = new uint256[](vote.optionsCastedLength + 1);
stakes = new uint256[](vote.optionsCastedLength + 1);
for (uint256 i = 0; i <= vote.optionsCastedLength; i++) {
options[i] = vote.castedVotes[i].optionId;
stakes[i] = vote.castedVotes[i].stake;
}
}
function getOptionPower(uint256 _surveyId, uint256 _optionId) public view surveyExists(_surveyId) returns (uint256) {
SurveyStruct storage survey = surveys[_surveyId];
require(_optionId <= survey.options, ERROR_NO_OPTION);
return survey.optionPower[_optionId];
}
function isParticipationAchieved(uint256 _surveyId) public view surveyExists(_surveyId) returns (bool) {
SurveyStruct storage survey = surveys[_surveyId];
// votingPower is always > 0
uint256 participationPct = survey.participation.mul(PCT_BASE) / survey.votingPower;
return participationPct >= survey.minParticipationPct;
}
// Internal fns
/*
* @dev Assumes the survey exists and that msg.sender can vote
*/
function _resetVote(uint256 _surveyId) internal {
SurveyStruct storage survey = surveys[_surveyId];
MultiOptionVote storage previousVote = survey.votes[msg.sender];
if (previousVote.optionsCastedLength > 0) {
// Voter removes their vote (index 0 is the abstain vote)
for (uint256 i = 1; i <= previousVote.optionsCastedLength; i++) {
OptionCast storage previousOptionCast = previousVote.castedVotes[i];
uint256 previousOptionPower = survey.optionPower[previousOptionCast.optionId];
uint256 currentOptionPower = previousOptionPower.sub(previousOptionCast.stake);
survey.optionPower[previousOptionCast.optionId] = currentOptionPower;
emit ResetVote(_surveyId, msg.sender, previousOptionCast.optionId, previousOptionCast.stake, currentOptionPower);
}
// Compute previously casted votes (i.e. substract non-used tokens from stake)
uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock);
uint256 previousParticipation = voterStake.sub(previousVote.castedVotes[0].stake);
// And remove it from total participation
survey.participation = survey.participation.sub(previousParticipation);
// Reset previously voted options
delete survey.votes[msg.sender];
}
}
/*
* @dev Assumes the survey exists and that msg.sender can vote
*/
function _voteOptions(uint256 _surveyId, uint256[] _optionIds, uint256[] _stakes) internal {
SurveyStruct storage survey = surveys[_surveyId];
MultiOptionVote storage senderVotes = survey.votes[msg.sender];
// Revert previous votes, if any
_resetVote(_surveyId);
uint256 totalVoted = 0;
// Reserve first index for ABSTAIN_VOTE
senderVotes.castedVotes[0] = OptionCast({ optionId: ABSTAIN_VOTE, stake: 0 });
for (uint256 optionIndex = 1; optionIndex <= _optionIds.length; optionIndex++) {
// Voters don't specify that they're abstaining,
// but we still keep track of this by reserving the first index of a survey's votes.
// We subtract 1 from the indexes of the arrays passed in by the voter to account for this.
uint256 optionId = _optionIds[optionIndex - 1];
uint256 stake = _stakes[optionIndex - 1];
require(optionId != ABSTAIN_VOTE && optionId <= survey.options, ERROR_VOTE_WRONG_OPTION);
require(stake > 0, ERROR_NO_STAKE);
// Let's avoid repeating an option by making sure that ascending order is preserved in
// the options array by checking that the current optionId is larger than the last one
// we added
require(senderVotes.castedVotes[optionIndex - 1].optionId < optionId, ERROR_OPTIONS_NOT_ORDERED);
// Register voter amount
senderVotes.castedVotes[optionIndex] = OptionCast({ optionId: optionId, stake: stake });
// Add to total option support
survey.optionPower[optionId] = survey.optionPower[optionId].add(stake);
// Keep track of stake used so far
totalVoted = totalVoted.add(stake);
emit CastVote(_surveyId, msg.sender, optionId, stake, survey.optionPower[optionId]);
}
// Compute and register non used tokens
// Implictly we are doing require(totalVoted <= voterStake) too
// (as stated before, index 0 is for ABSTAIN_VOTE option)
uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock);
senderVotes.castedVotes[0].stake = voterStake.sub(totalVoted);
// Register number of options voted
senderVotes.optionsCastedLength = _optionIds.length;
// Add voter tokens to participation
survey.participation = survey.participation.add(totalVoted);
assert(survey.participation <= survey.votingPower);
}
function _isSurveyOpen(SurveyStruct storage _survey) internal view returns (bool) {
return getTimestamp64() < _survey.startDate.add(surveyTime);
}
}
// File: @aragon/os/contracts/acl/IACLOracle.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
interface IACLOracle {
function canPerform(address who, address where, bytes32 what, uint256[] how) external view returns (bool);
}
// File: @aragon/os/contracts/acl/ACL.sol
pragma solidity 0.4.24;
/* solium-disable function-order */
// Allow public initialize() to be first
contract ACL is IACL, TimeHelpers, AragonApp, ACLHelpers {
/* Hardcoded constants to save gas
bytes32 public constant CREATE_PERMISSIONS_ROLE = keccak256("CREATE_PERMISSIONS_ROLE");
*/
bytes32 public constant CREATE_PERMISSIONS_ROLE = 0x0b719b33c83b8e5d300c521cb8b54ae9bd933996a14bef8c2f4e0285d2d2400a;
enum Op { NONE, EQ, NEQ, GT, LT, GTE, LTE, RET, NOT, AND, OR, XOR, IF_ELSE } // op types
struct Param {
uint8 id;
uint8 op;
uint240 value; // even though value is an uint240 it can store addresses
// in the case of 32 byte hashes losing 2 bytes precision isn't a huge deal
// op and id take less than 1 byte each so it can be kept in 1 sstore
}
uint8 internal constant BLOCK_NUMBER_PARAM_ID = 200;
uint8 internal constant TIMESTAMP_PARAM_ID = 201;
// 202 is unused
uint8 internal constant ORACLE_PARAM_ID = 203;
uint8 internal constant LOGIC_OP_PARAM_ID = 204;
uint8 internal constant PARAM_VALUE_PARAM_ID = 205;
// TODO: Add execution times param type?
/* Hardcoded constant to save gas
bytes32 public constant EMPTY_PARAM_HASH = keccak256(uint256(0));
*/
bytes32 public constant EMPTY_PARAM_HASH = 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563;
bytes32 public constant NO_PERMISSION = bytes32(0);
address public constant ANY_ENTITY = address(-1);
address public constant BURN_ENTITY = address(1); // address(0) is already used as "no permission manager"
uint256 internal constant ORACLE_CHECK_GAS = 30000;
string private constant ERROR_AUTH_INIT_KERNEL = "ACL_AUTH_INIT_KERNEL";
string private constant ERROR_AUTH_NO_MANAGER = "ACL_AUTH_NO_MANAGER";
string private constant ERROR_EXISTENT_MANAGER = "ACL_EXISTENT_MANAGER";
// Whether someone has a permission
mapping (bytes32 => bytes32) internal permissions; // permissions hash => params hash
mapping (bytes32 => Param[]) internal permissionParams; // params hash => params
// Who is the manager of a permission
mapping (bytes32 => address) internal permissionManager;
event SetPermission(address indexed entity, address indexed app, bytes32 indexed role, bool allowed);
event SetPermissionParams(address indexed entity, address indexed app, bytes32 indexed role, bytes32 paramsHash);
event ChangePermissionManager(address indexed app, bytes32 indexed role, address indexed manager);
modifier onlyPermissionManager(address _app, bytes32 _role) {
require(msg.sender == getPermissionManager(_app, _role), ERROR_AUTH_NO_MANAGER);
_;
}
modifier noPermissionManager(address _app, bytes32 _role) {
// only allow permission creation (or re-creation) when there is no manager
require(getPermissionManager(_app, _role) == address(0), ERROR_EXISTENT_MANAGER);
_;
}
/**
* @dev Initialize can only be called once. It saves the block number in which it was initialized.
* @notice Initialize an ACL instance and set `_permissionsCreator` as the entity that can create other permissions
* @param _permissionsCreator Entity that will be given permission over createPermission
*/
function initialize(address _permissionsCreator) public onlyInit {
initialized();
require(msg.sender == address(kernel()), ERROR_AUTH_INIT_KERNEL);
_createPermission(_permissionsCreator, this, CREATE_PERMISSIONS_ROLE, _permissionsCreator);
}
/**
* @dev Creates a permission that wasn't previously set and managed.
* If a created permission is removed it is possible to reset it with createPermission.
* This is the **ONLY** way to create permissions and set managers to permissions that don't
* have a manager.
* In terms of the ACL being initialized, this function implicitly protects all the other
* state-changing external functions, as they all require the sender to be a manager.
* @notice Create a new permission granting `_entity` the ability to perform actions requiring `_role` on `_app`, setting `_manager` as the permission's manager
* @param _entity Address of the whitelisted entity that will be able to perform the role
* @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL)
* @param _role Identifier for the group of actions in app given access to perform
* @param _manager Address of the entity that will be able to grant and revoke the permission further.
*/
function createPermission(address _entity, address _app, bytes32 _role, address _manager)
external
auth(CREATE_PERMISSIONS_ROLE)
noPermissionManager(_app, _role)
{
_createPermission(_entity, _app, _role, _manager);
}
/**
* @dev Grants permission if allowed. This requires `msg.sender` to be the permission manager
* @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app`
* @param _entity Address of the whitelisted entity that will be able to perform the role
* @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL)
* @param _role Identifier for the group of actions in app given access to perform
*/
function grantPermission(address _entity, address _app, bytes32 _role)
external
{
grantPermissionP(_entity, _app, _role, new uint256[](0));
}
/**
* @dev Grants a permission with parameters if allowed. This requires `msg.sender` to be the permission manager
* @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app`
* @param _entity Address of the whitelisted entity that will be able to perform the role
* @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL)
* @param _role Identifier for the group of actions in app given access to perform
* @param _params Permission parameters
*/
function grantPermissionP(address _entity, address _app, bytes32 _role, uint256[] _params)
public
onlyPermissionManager(_app, _role)
{
bytes32 paramsHash = _params.length > 0 ? _saveParams(_params) : EMPTY_PARAM_HASH;
_setPermission(_entity, _app, _role, paramsHash);
}
/**
* @dev Revokes permission if allowed. This requires `msg.sender` to be the the permission manager
* @notice Revoke from `_entity` the ability to perform actions requiring `_role` on `_app`
* @param _entity Address of the whitelisted entity to revoke access from
* @param _app Address of the app in which the role will be revoked
* @param _role Identifier for the group of actions in app being revoked
*/
function revokePermission(address _entity, address _app, bytes32 _role)
external
onlyPermissionManager(_app, _role)
{
_setPermission(_entity, _app, _role, NO_PERMISSION);
}
/**
* @notice Set `_newManager` as the manager of `_role` in `_app`
* @param _newManager Address for the new manager
* @param _app Address of the app in which the permission management is being transferred
* @param _role Identifier for the group of actions being transferred
*/
function setPermissionManager(address _newManager, address _app, bytes32 _role)
external
onlyPermissionManager(_app, _role)
{
_setPermissionManager(_newManager, _app, _role);
}
/**
* @notice Remove the manager of `_role` in `_app`
* @param _app Address of the app in which the permission is being unmanaged
* @param _role Identifier for the group of actions being unmanaged
*/
function removePermissionManager(address _app, bytes32 _role)
external
onlyPermissionManager(_app, _role)
{
_setPermissionManager(address(0), _app, _role);
}
/**
* @notice Burn non-existent `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager)
* @param _app Address of the app in which the permission is being burned
* @param _role Identifier for the group of actions being burned
*/
function createBurnedPermission(address _app, bytes32 _role)
external
auth(CREATE_PERMISSIONS_ROLE)
noPermissionManager(_app, _role)
{
_setPermissionManager(BURN_ENTITY, _app, _role);
}
/**
* @notice Burn `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager)
* @param _app Address of the app in which the permission is being burned
* @param _role Identifier for the group of actions being burned
*/
function burnPermissionManager(address _app, bytes32 _role)
external
onlyPermissionManager(_app, _role)
{
_setPermissionManager(BURN_ENTITY, _app, _role);
}
/**
* @notice Get parameters for permission array length
* @param _entity Address of the whitelisted entity that will be able to perform the role
* @param _app Address of the app
* @param _role Identifier for a group of actions in app
* @return Length of the array
*/
function getPermissionParamsLength(address _entity, address _app, bytes32 _role) external view returns (uint) {
return permissionParams[permissions[permissionHash(_entity, _app, _role)]].length;
}
/**
* @notice Get parameter for permission
* @param _entity Address of the whitelisted entity that will be able to perform the role
* @param _app Address of the app
* @param _role Identifier for a group of actions in app
* @param _index Index of parameter in the array
* @return Parameter (id, op, value)
*/
function getPermissionParam(address _entity, address _app, bytes32 _role, uint _index)
external
view
returns (uint8, uint8, uint240)
{
Param storage param = permissionParams[permissions[permissionHash(_entity, _app, _role)]][_index];
return (param.id, param.op, param.value);
}
/**
* @dev Get manager for permission
* @param _app Address of the app
* @param _role Identifier for a group of actions in app
* @return address of the manager for the permission
*/
function getPermissionManager(address _app, bytes32 _role) public view returns (address) {
return permissionManager[roleHash(_app, _role)];
}
/**
* @dev Function called by apps to check ACL on kernel or to check permission statu
* @param _who Sender of the original call
* @param _where Address of the app
* @param _where Identifier for a group of actions in app
* @param _how Permission parameters
* @return boolean indicating whether the ACL allows the role or not
*/
function hasPermission(address _who, address _where, bytes32 _what, bytes memory _how) public view returns (bool) {
return hasPermission(_who, _where, _what, ConversionHelpers.dangerouslyCastBytesToUintArray(_how));
}
function hasPermission(address _who, address _where, bytes32 _what, uint256[] memory _how) public view returns (bool) {
bytes32 whoParams = permissions[permissionHash(_who, _where, _what)];
if (whoParams != NO_PERMISSION && evalParams(whoParams, _who, _where, _what, _how)) {
return true;
}
bytes32 anyParams = permissions[permissionHash(ANY_ENTITY, _where, _what)];
if (anyParams != NO_PERMISSION && evalParams(anyParams, ANY_ENTITY, _where, _what, _how)) {
return true;
}
return false;
}
function hasPermission(address _who, address _where, bytes32 _what) public view returns (bool) {
uint256[] memory empty = new uint256[](0);
return hasPermission(_who, _where, _what, empty);
}
function evalParams(
bytes32 _paramsHash,
address _who,
address _where,
bytes32 _what,
uint256[] _how
) public view returns (bool)
{
if (_paramsHash == EMPTY_PARAM_HASH) {
return true;
}
return _evalParam(_paramsHash, 0, _who, _where, _what, _how);
}
/**
* @dev Internal createPermission for access inside the kernel (on instantiation)
*/
function _createPermission(address _entity, address _app, bytes32 _role, address _manager) internal {
_setPermission(_entity, _app, _role, EMPTY_PARAM_HASH);
_setPermissionManager(_manager, _app, _role);
}
/**
* @dev Internal function called to actually save the permission
*/
function _setPermission(address _entity, address _app, bytes32 _role, bytes32 _paramsHash) internal {
permissions[permissionHash(_entity, _app, _role)] = _paramsHash;
bool entityHasPermission = _paramsHash != NO_PERMISSION;
bool permissionHasParams = entityHasPermission && _paramsHash != EMPTY_PARAM_HASH;
emit SetPermission(_entity, _app, _role, entityHasPermission);
if (permissionHasParams) {
emit SetPermissionParams(_entity, _app, _role, _paramsHash);
}
}
function _saveParams(uint256[] _encodedParams) internal returns (bytes32) {
bytes32 paramHash = keccak256(abi.encodePacked(_encodedParams));
Param[] storage params = permissionParams[paramHash];
if (params.length == 0) { // params not saved before
for (uint256 i = 0; i < _encodedParams.length; i++) {
uint256 encodedParam = _encodedParams[i];
Param memory param = Param(decodeParamId(encodedParam), decodeParamOp(encodedParam), uint240(encodedParam));
params.push(param);
}
}
return paramHash;
}
function _evalParam(
bytes32 _paramsHash,
uint32 _paramId,
address _who,
address _where,
bytes32 _what,
uint256[] _how
) internal view returns (bool)
{
if (_paramId >= permissionParams[_paramsHash].length) {
return false; // out of bounds
}
Param memory param = permissionParams[_paramsHash][_paramId];
if (param.id == LOGIC_OP_PARAM_ID) {
return _evalLogic(param, _paramsHash, _who, _where, _what, _how);
}
uint256 value;
uint256 comparedTo = uint256(param.value);
// get value
if (param.id == ORACLE_PARAM_ID) {
value = checkOracle(IACLOracle(param.value), _who, _where, _what, _how) ? 1 : 0;
comparedTo = 1;
} else if (param.id == BLOCK_NUMBER_PARAM_ID) {
value = getBlockNumber();
} else if (param.id == TIMESTAMP_PARAM_ID) {
value = getTimestamp();
} else if (param.id == PARAM_VALUE_PARAM_ID) {
value = uint256(param.value);
} else {
if (param.id >= _how.length) {
return false;
}
value = uint256(uint240(_how[param.id])); // force lost precision
}
if (Op(param.op) == Op.RET) {
return uint256(value) > 0;
}
return compare(value, Op(param.op), comparedTo);
}
function _evalLogic(Param _param, bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how)
internal
view
returns (bool)
{
if (Op(_param.op) == Op.IF_ELSE) {
uint32 conditionParam;
uint32 successParam;
uint32 failureParam;
(conditionParam, successParam, failureParam) = decodeParamsList(uint256(_param.value));
bool result = _evalParam(_paramsHash, conditionParam, _who, _where, _what, _how);
return _evalParam(_paramsHash, result ? successParam : failureParam, _who, _where, _what, _how);
}
uint32 param1;
uint32 param2;
(param1, param2,) = decodeParamsList(uint256(_param.value));
bool r1 = _evalParam(_paramsHash, param1, _who, _where, _what, _how);
if (Op(_param.op) == Op.NOT) {
return !r1;
}
if (r1 && Op(_param.op) == Op.OR) {
return true;
}
if (!r1 && Op(_param.op) == Op.AND) {
return false;
}
bool r2 = _evalParam(_paramsHash, param2, _who, _where, _what, _how);
if (Op(_param.op) == Op.XOR) {
return r1 != r2;
}
return r2; // both or and and depend on result of r2 after checks
}
function compare(uint256 _a, Op _op, uint256 _b) internal pure returns (bool) {
if (_op == Op.EQ) return _a == _b; // solium-disable-line lbrace
if (_op == Op.NEQ) return _a != _b; // solium-disable-line lbrace
if (_op == Op.GT) return _a > _b; // solium-disable-line lbrace
if (_op == Op.LT) return _a < _b; // solium-disable-line lbrace
if (_op == Op.GTE) return _a >= _b; // solium-disable-line lbrace
if (_op == Op.LTE) return _a <= _b; // solium-disable-line lbrace
return false;
}
function checkOracle(IACLOracle _oracleAddr, address _who, address _where, bytes32 _what, uint256[] _how) internal view returns (bool) {
bytes4 sig = _oracleAddr.canPerform.selector;
// a raw call is required so we can return false if the call reverts, rather than reverting
bytes memory checkCalldata = abi.encodeWithSelector(sig, _who, _where, _what, _how);
uint256 oracleCheckGas = ORACLE_CHECK_GAS;
bool ok;
assembly {
ok := staticcall(oracleCheckGas, _oracleAddr, add(checkCalldata, 0x20), mload(checkCalldata), 0, 0)
}
if (!ok) {
return false;
}
uint256 size;
assembly { size := returndatasize }
if (size != 32) {
return false;
}
bool result;
assembly {
let ptr := mload(0x40) // get next free memory ptr
returndatacopy(ptr, 0, size) // copy return from above `staticcall`
result := mload(ptr) // read data at ptr and set it to result
mstore(ptr, 0) // set pointer memory to 0 so it still is the next free ptr
}
return result;
}
/**
* @dev Internal function that sets management
*/
function _setPermissionManager(address _newManager, address _app, bytes32 _role) internal {
permissionManager[roleHash(_app, _role)] = _newManager;
emit ChangePermissionManager(_app, _role, _newManager);
}
function roleHash(address _where, bytes32 _what) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("ROLE", _where, _what));
}
function permissionHash(address _who, address _where, bytes32 _what) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("PERMISSION", _who, _where, _what));
}
}
// File: @aragon/os/contracts/apm/Repo.sol
pragma solidity 0.4.24;
/* solium-disable function-order */
// Allow public initialize() to be first
contract Repo is AragonApp {
/* Hardcoded constants to save gas
bytes32 public constant CREATE_VERSION_ROLE = keccak256("CREATE_VERSION_ROLE");
*/
bytes32 public constant CREATE_VERSION_ROLE = 0x1f56cfecd3595a2e6cc1a7e6cb0b20df84cdbd92eff2fee554e70e4e45a9a7d8;
string private constant ERROR_INVALID_BUMP = "REPO_INVALID_BUMP";
string private constant ERROR_INVALID_VERSION = "REPO_INVALID_VERSION";
string private constant ERROR_INEXISTENT_VERSION = "REPO_INEXISTENT_VERSION";
struct Version {
uint16[3] semanticVersion;
address contractAddress;
bytes contentURI;
}
uint256 internal versionsNextIndex;
mapping (uint256 => Version) internal versions;
mapping (bytes32 => uint256) internal versionIdForSemantic;
mapping (address => uint256) internal latestVersionIdForContract;
event NewVersion(uint256 versionId, uint16[3] semanticVersion);
/**
* @dev Initialize can only be called once. It saves the block number in which it was initialized.
* @notice Initialize this Repo
*/
function initialize() public onlyInit {
initialized();
versionsNextIndex = 1;
}
/**
* @notice Create new version with contract `_contractAddress` and content `@fromHex(_contentURI)`
* @param _newSemanticVersion Semantic version for new repo version
* @param _contractAddress address for smart contract logic for version (if set to 0, it uses last versions' contractAddress)
* @param _contentURI External URI for fetching new version's content
*/
function newVersion(
uint16[3] _newSemanticVersion,
address _contractAddress,
bytes _contentURI
) public auth(CREATE_VERSION_ROLE)
{
address contractAddress = _contractAddress;
uint256 lastVersionIndex = versionsNextIndex - 1;
uint16[3] memory lastSematicVersion;
if (lastVersionIndex > 0) {
Version storage lastVersion = versions[lastVersionIndex];
lastSematicVersion = lastVersion.semanticVersion;
if (contractAddress == address(0)) {
contractAddress = lastVersion.contractAddress;
}
// Only allows smart contract change on major version bumps
require(
lastVersion.contractAddress == contractAddress || _newSemanticVersion[0] > lastVersion.semanticVersion[0],
ERROR_INVALID_VERSION
);
}
require(isValidBump(lastSematicVersion, _newSemanticVersion), ERROR_INVALID_BUMP);
uint256 versionId = versionsNextIndex++;
versions[versionId] = Version(_newSemanticVersion, contractAddress, _contentURI);
versionIdForSemantic[semanticVersionHash(_newSemanticVersion)] = versionId;
latestVersionIdForContract[contractAddress] = versionId;
emit NewVersion(versionId, _newSemanticVersion);
}
function getLatest() public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) {
return getByVersionId(versionsNextIndex - 1);
}
function getLatestForContractAddress(address _contractAddress)
public
view
returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI)
{
return getByVersionId(latestVersionIdForContract[_contractAddress]);
}
function getBySemanticVersion(uint16[3] _semanticVersion)
public
view
returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI)
{
return getByVersionId(versionIdForSemantic[semanticVersionHash(_semanticVersion)]);
}
function getByVersionId(uint _versionId) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) {
require(_versionId > 0 && _versionId < versionsNextIndex, ERROR_INEXISTENT_VERSION);
Version storage version = versions[_versionId];
return (version.semanticVersion, version.contractAddress, version.contentURI);
}
function getVersionsCount() public view returns (uint256) {
return versionsNextIndex - 1;
}
function isValidBump(uint16[3] _oldVersion, uint16[3] _newVersion) public pure returns (bool) {
bool hasBumped;
uint i = 0;
while (i < 3) {
if (hasBumped) {
if (_newVersion[i] != 0) {
return false;
}
} else if (_newVersion[i] != _oldVersion[i]) {
if (_oldVersion[i] > _newVersion[i] || _newVersion[i] - _oldVersion[i] != 1) {
return false;
}
hasBumped = true;
}
i++;
}
return hasBumped;
}
function semanticVersionHash(uint16[3] version) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(version[0], version[1], version[2]));
}
}
// File: @aragon/os/contracts/apm/APMNamehash.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract APMNamehash {
/* Hardcoded constants to save gas
bytes32 internal constant APM_NODE = keccak256(abi.encodePacked(ETH_TLD_NODE, keccak256(abi.encodePacked("aragonpm"))));
*/
bytes32 internal constant APM_NODE = 0x9065c3e7f7b7ef1ef4e53d2d0b8e0cef02874ab020c1ece79d5f0d3d0111c0ba;
function apmNamehash(string name) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(APM_NODE, keccak256(bytes(name))));
}
}
// File: @aragon/os/contracts/kernel/KernelStorage.sol
pragma solidity 0.4.24;
contract KernelStorage {
// namespace => app id => address
mapping (bytes32 => mapping (bytes32 => address)) public apps;
bytes32 public recoveryVaultAppId;
}
// File: @aragon/os/contracts/lib/misc/ERCProxy.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract ERCProxy {
uint256 internal constant FORWARDING = 1;
uint256 internal constant UPGRADEABLE = 2;
function proxyType() public pure returns (uint256 proxyTypeId);
function implementation() public view returns (address codeAddr);
}
// File: @aragon/os/contracts/common/DelegateProxy.sol
pragma solidity 0.4.24;
contract DelegateProxy is ERCProxy, IsContract {
uint256 internal constant FWD_GAS_LIMIT = 10000;
/**
* @dev Performs a delegatecall and returns whatever the delegatecall returned (entire context execution will return!)
* @param _dst Destination address to perform the delegatecall
* @param _calldata Calldata for the delegatecall
*/
function delegatedFwd(address _dst, bytes _calldata) internal {
require(isContract(_dst));
uint256 fwdGasLimit = FWD_GAS_LIMIT;
assembly {
let result := delegatecall(sub(gas, fwdGasLimit), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0)
let size := returndatasize
let ptr := mload(0x40)
returndatacopy(ptr, 0, size)
// revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas.
// if the call returned error data, forward it
switch result case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
}
// File: @aragon/os/contracts/common/DepositableDelegateProxy.sol
pragma solidity 0.4.24;
contract DepositableDelegateProxy is DepositableStorage, DelegateProxy {
event ProxyDeposit(address sender, uint256 value);
function () external payable {
// send / transfer
if (gasleft() < FWD_GAS_LIMIT) {
require(msg.value > 0 && msg.data.length == 0);
require(isDepositable());
emit ProxyDeposit(msg.sender, msg.value);
} else { // all calls except for send or transfer
address target = implementation();
delegatedFwd(target, msg.data);
}
}
}
// File: @aragon/os/contracts/apps/AppProxyBase.sol
pragma solidity 0.4.24;
contract AppProxyBase is AppStorage, DepositableDelegateProxy, KernelNamespaceConstants {
/**
* @dev Initialize AppProxy
* @param _kernel Reference to organization kernel for the app
* @param _appId Identifier for app
* @param _initializePayload Payload for call to be made after setup to initialize
*/
constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public {
setKernel(_kernel);
setAppId(_appId);
// Implicit check that kernel is actually a Kernel
// The EVM doesn't actually provide a way for us to make sure, but we can force a revert to
// occur if the kernel is set to 0x0 or a non-code address when we try to call a method on
// it.
address appCode = getAppBase(_appId);
// If initialize payload is provided, it will be executed
if (_initializePayload.length > 0) {
require(isContract(appCode));
// Cannot make delegatecall as a delegateproxy.delegatedFwd as it
// returns ending execution context and halts contract deployment
require(appCode.delegatecall(_initializePayload));
}
}
function getAppBase(bytes32 _appId) internal view returns (address) {
return kernel().getApp(KERNEL_APP_BASES_NAMESPACE, _appId);
}
}
// File: @aragon/os/contracts/apps/AppProxyUpgradeable.sol
pragma solidity 0.4.24;
contract AppProxyUpgradeable is AppProxyBase {
/**
* @dev Initialize AppProxyUpgradeable (makes it an upgradeable Aragon app)
* @param _kernel Reference to organization kernel for the app
* @param _appId Identifier for app
* @param _initializePayload Payload for call to be made after setup to initialize
*/
constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload)
AppProxyBase(_kernel, _appId, _initializePayload)
public // solium-disable-line visibility-first
{
// solium-disable-previous-line no-empty-blocks
}
/**
* @dev ERC897, the address the proxy would delegate calls to
*/
function implementation() public view returns (address) {
return getAppBase(appId());
}
/**
* @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy
*/
function proxyType() public pure returns (uint256 proxyTypeId) {
return UPGRADEABLE;
}
}
// File: @aragon/os/contracts/apps/AppProxyPinned.sol
pragma solidity 0.4.24;
contract AppProxyPinned is IsContract, AppProxyBase {
using UnstructuredStorage for bytes32;
// keccak256("aragonOS.appStorage.pinnedCode")
bytes32 internal constant PINNED_CODE_POSITION = 0xdee64df20d65e53d7f51cb6ab6d921a0a6a638a91e942e1d8d02df28e31c038e;
/**
* @dev Initialize AppProxyPinned (makes it an un-upgradeable Aragon app)
* @param _kernel Reference to organization kernel for the app
* @param _appId Identifier for app
* @param _initializePayload Payload for call to be made after setup to initialize
*/
constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload)
AppProxyBase(_kernel, _appId, _initializePayload)
public // solium-disable-line visibility-first
{
setPinnedCode(getAppBase(_appId));
require(isContract(pinnedCode()));
}
/**
* @dev ERC897, the address the proxy would delegate calls to
*/
function implementation() public view returns (address) {
return pinnedCode();
}
/**
* @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy
*/
function proxyType() public pure returns (uint256 proxyTypeId) {
return FORWARDING;
}
function setPinnedCode(address _pinnedCode) internal {
PINNED_CODE_POSITION.setStorageAddress(_pinnedCode);
}
function pinnedCode() internal view returns (address) {
return PINNED_CODE_POSITION.getStorageAddress();
}
}
// File: @aragon/os/contracts/factory/AppProxyFactory.sol
pragma solidity 0.4.24;
contract AppProxyFactory {
event NewAppProxy(address proxy, bool isUpgradeable, bytes32 appId);
/**
* @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId`
* @param _kernel App's Kernel reference
* @param _appId Identifier for app
* @return AppProxyUpgradeable
*/
function newAppProxy(IKernel _kernel, bytes32 _appId) public returns (AppProxyUpgradeable) {
return newAppProxy(_kernel, _appId, new bytes(0));
}
/**
* @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload`
* @param _kernel App's Kernel reference
* @param _appId Identifier for app
* @return AppProxyUpgradeable
*/
function newAppProxy(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyUpgradeable) {
AppProxyUpgradeable proxy = new AppProxyUpgradeable(_kernel, _appId, _initializePayload);
emit NewAppProxy(address(proxy), true, _appId);
return proxy;
}
/**
* @notice Create a new pinned app instance on `_kernel` with identifier `_appId`
* @param _kernel App's Kernel reference
* @param _appId Identifier for app
* @return AppProxyPinned
*/
function newAppProxyPinned(IKernel _kernel, bytes32 _appId) public returns (AppProxyPinned) {
return newAppProxyPinned(_kernel, _appId, new bytes(0));
}
/**
* @notice Create a new pinned app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload`
* @param _kernel App's Kernel reference
* @param _appId Identifier for app
* @param _initializePayload Proxy initialization payload
* @return AppProxyPinned
*/
function newAppProxyPinned(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyPinned) {
AppProxyPinned proxy = new AppProxyPinned(_kernel, _appId, _initializePayload);
emit NewAppProxy(address(proxy), false, _appId);
return proxy;
}
}
// File: @aragon/os/contracts/kernel/Kernel.sol
pragma solidity 0.4.24;
// solium-disable-next-line max-len
contract Kernel is IKernel, KernelStorage, KernelAppIds, KernelNamespaceConstants, Petrifiable, IsContract, VaultRecoverable, AppProxyFactory, ACLSyntaxSugar {
/* Hardcoded constants to save gas
bytes32 public constant APP_MANAGER_ROLE = keccak256("APP_MANAGER_ROLE");
*/
bytes32 public constant APP_MANAGER_ROLE = 0xb6d92708f3d4817afc106147d969e229ced5c46e65e0a5002a0d391287762bd0;
string private constant ERROR_APP_NOT_CONTRACT = "KERNEL_APP_NOT_CONTRACT";
string private constant ERROR_INVALID_APP_CHANGE = "KERNEL_INVALID_APP_CHANGE";
string private constant ERROR_AUTH_FAILED = "KERNEL_AUTH_FAILED";
/**
* @dev Constructor that allows the deployer to choose if the base instance should be petrified immediately.
* @param _shouldPetrify Immediately petrify this instance so that it can never be initialized
*/
constructor(bool _shouldPetrify) public {
if (_shouldPetrify) {
petrify();
}
}
/**
* @dev Initialize can only be called once. It saves the block number in which it was initialized.
* @notice Initialize this kernel instance along with its ACL and set `_permissionsCreator` as the entity that can create other permissions
* @param _baseAcl Address of base ACL app
* @param _permissionsCreator Entity that will be given permission over createPermission
*/
function initialize(IACL _baseAcl, address _permissionsCreator) public onlyInit {
initialized();
// Set ACL base
_setApp(KERNEL_APP_BASES_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, _baseAcl);
// Create ACL instance and attach it as the default ACL app
IACL acl = IACL(newAppProxy(this, KERNEL_DEFAULT_ACL_APP_ID));
acl.initialize(_permissionsCreator);
_setApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, acl);
recoveryVaultAppId = KERNEL_DEFAULT_VAULT_APP_ID;
}
/**
* @dev Create a new instance of an app linked to this kernel
* @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`
* @param _appId Identifier for app
* @param _appBase Address of the app's base implementation
* @return AppProxy instance
*/
function newAppInstance(bytes32 _appId, address _appBase)
public
auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
returns (ERCProxy appProxy)
{
return newAppInstance(_appId, _appBase, new bytes(0), false);
}
/**
* @dev Create a new instance of an app linked to this kernel and set its base
* implementation if it was not already set
* @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''`
* @param _appId Identifier for app
* @param _appBase Address of the app's base implementation
* @param _initializePayload Payload for call made by the proxy during its construction to initialize
* @param _setDefault Whether the app proxy app is the default one.
* Useful when the Kernel needs to know of an instance of a particular app,
* like Vault for escape hatch mechanism.
* @return AppProxy instance
*/
function newAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault)
public
auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
returns (ERCProxy appProxy)
{
_setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase);
appProxy = newAppProxy(this, _appId, _initializePayload);
// By calling setApp directly and not the internal functions, we make sure the params are checked
// and it will only succeed if sender has permissions to set something to the namespace.
if (_setDefault) {
setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy);
}
}
/**
* @dev Create a new pinned instance of an app linked to this kernel
* @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`.
* @param _appId Identifier for app
* @param _appBase Address of the app's base implementation
* @return AppProxy instance
*/
function newPinnedAppInstance(bytes32 _appId, address _appBase)
public
auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
returns (ERCProxy appProxy)
{
return newPinnedAppInstance(_appId, _appBase, new bytes(0), false);
}
/**
* @dev Create a new pinned instance of an app linked to this kernel and set
* its base implementation if it was not already set
* @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''`
* @param _appId Identifier for app
* @param _appBase Address of the app's base implementation
* @param _initializePayload Payload for call made by the proxy during its construction to initialize
* @param _setDefault Whether the app proxy app is the default one.
* Useful when the Kernel needs to know of an instance of a particular app,
* like Vault for escape hatch mechanism.
* @return AppProxy instance
*/
function newPinnedAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault)
public
auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
returns (ERCProxy appProxy)
{
_setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase);
appProxy = newAppProxyPinned(this, _appId, _initializePayload);
// By calling setApp directly and not the internal functions, we make sure the params are checked
// and it will only succeed if sender has permissions to set something to the namespace.
if (_setDefault) {
setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy);
}
}
/**
* @dev Set the resolving address of an app instance or base implementation
* @notice Set the resolving address of `_appId` in namespace `_namespace` to `_app`
* @param _namespace App namespace to use
* @param _appId Identifier for app
* @param _app Address of the app instance or base implementation
* @return ID of app
*/
function setApp(bytes32 _namespace, bytes32 _appId, address _app)
public
auth(APP_MANAGER_ROLE, arr(_namespace, _appId))
{
_setApp(_namespace, _appId, _app);
}
/**
* @dev Set the default vault id for the escape hatch mechanism
* @param _recoveryVaultAppId Identifier of the recovery vault app
*/
function setRecoveryVaultAppId(bytes32 _recoveryVaultAppId)
public
auth(APP_MANAGER_ROLE, arr(KERNEL_APP_ADDR_NAMESPACE, _recoveryVaultAppId))
{
recoveryVaultAppId = _recoveryVaultAppId;
}
// External access to default app id and namespace constants to mimic default getters for constants
/* solium-disable function-order, mixedcase */
function CORE_NAMESPACE() external pure returns (bytes32) { return KERNEL_CORE_NAMESPACE; }
function APP_BASES_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_BASES_NAMESPACE; }
function APP_ADDR_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_ADDR_NAMESPACE; }
function KERNEL_APP_ID() external pure returns (bytes32) { return KERNEL_CORE_APP_ID; }
function DEFAULT_ACL_APP_ID() external pure returns (bytes32) { return KERNEL_DEFAULT_ACL_APP_ID; }
/* solium-enable function-order, mixedcase */
/**
* @dev Get the address of an app instance or base implementation
* @param _namespace App namespace to use
* @param _appId Identifier for app
* @return Address of the app
*/
function getApp(bytes32 _namespace, bytes32 _appId) public view returns (address) {
return apps[_namespace][_appId];
}
/**
* @dev Get the address of the recovery Vault instance (to recover funds)
* @return Address of the Vault
*/
function getRecoveryVault() public view returns (address) {
return apps[KERNEL_APP_ADDR_NAMESPACE][recoveryVaultAppId];
}
/**
* @dev Get the installed ACL app
* @return ACL app
*/
function acl() public view returns (IACL) {
return IACL(getApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID));
}
/**
* @dev Function called by apps to check ACL on kernel or to check permission status
* @param _who Sender of the original call
* @param _where Address of the app
* @param _what Identifier for a group of actions in app
* @param _how Extra data for ACL auth
* @return Boolean indicating whether the ACL allows the role or not.
* Always returns false if the kernel hasn't been initialized yet.
*/
function hasPermission(address _who, address _where, bytes32 _what, bytes _how) public view returns (bool) {
IACL defaultAcl = acl();
return address(defaultAcl) != address(0) && // Poor man's initialization check (saves gas)
defaultAcl.hasPermission(_who, _where, _what, _how);
}
function _setApp(bytes32 _namespace, bytes32 _appId, address _app) internal {
require(isContract(_app), ERROR_APP_NOT_CONTRACT);
apps[_namespace][_appId] = _app;
emit SetApp(_namespace, _appId, _app);
}
function _setAppIfNew(bytes32 _namespace, bytes32 _appId, address _app) internal {
address app = getApp(_namespace, _appId);
if (app != address(0)) {
// The only way to set an app is if it passes the isContract check, so no need to check it again
require(app == _app, ERROR_INVALID_APP_CHANGE);
} else {
_setApp(_namespace, _appId, _app);
}
}
modifier auth(bytes32 _role, uint256[] memory _params) {
require(
hasPermission(msg.sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)),
ERROR_AUTH_FAILED
);
_;
}
}
// File: @aragon/os/contracts/lib/ens/AbstractENS.sol
// See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/AbstractENS.sol
pragma solidity ^0.4.15;
interface AbstractENS {
function owner(bytes32 _node) public constant returns (address);
function resolver(bytes32 _node) public constant returns (address);
function ttl(bytes32 _node) public constant returns (uint64);
function setOwner(bytes32 _node, address _owner) public;
function setSubnodeOwner(bytes32 _node, bytes32 label, address _owner) public;
function setResolver(bytes32 _node, address _resolver) public;
function setTTL(bytes32 _node, uint64 _ttl) public;
// Logged when the owner of a node assigns a new owner to a subnode.
event NewOwner(bytes32 indexed _node, bytes32 indexed _label, address _owner);
// Logged when the owner of a node transfers ownership to a new account.
event Transfer(bytes32 indexed _node, address _owner);
// Logged when the resolver for a node changes.
event NewResolver(bytes32 indexed _node, address _resolver);
// Logged when the TTL of a node changes
event NewTTL(bytes32 indexed _node, uint64 _ttl);
}
// File: @aragon/os/contracts/lib/ens/ENS.sol
// See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/ENS.sol
pragma solidity ^0.4.0;
/**
* The ENS registry contract.
*/
contract ENS is AbstractENS {
struct Record {
address owner;
address resolver;
uint64 ttl;
}
mapping(bytes32=>Record) records;
// Permits modifications only by the owner of the specified node.
modifier only_owner(bytes32 node) {
if (records[node].owner != msg.sender) throw;
_;
}
/**
* Constructs a new ENS registrar.
*/
function ENS() public {
records[0].owner = msg.sender;
}
/**
* Returns the address that owns the specified node.
*/
function owner(bytes32 node) public constant returns (address) {
return records[node].owner;
}
/**
* Returns the address of the resolver for the specified node.
*/
function resolver(bytes32 node) public constant returns (address) {
return records[node].resolver;
}
/**
* Returns the TTL of a node, and any records associated with it.
*/
function ttl(bytes32 node) public constant returns (uint64) {
return records[node].ttl;
}
/**
* Transfers ownership of a node to a new address. May only be called by the current
* owner of the node.
* @param node The node to transfer ownership of.
* @param owner The address of the new owner.
*/
function setOwner(bytes32 node, address owner) only_owner(node) public {
Transfer(node, owner);
records[node].owner = owner;
}
/**
* Transfers ownership of a subnode keccak256(node, label) to a new address. May only be
* called by the owner of the parent node.
* @param node The parent node.
* @param label The hash of the label specifying the subnode.
* @param owner The address of the new owner.
*/
function setSubnodeOwner(bytes32 node, bytes32 label, address owner) only_owner(node) public {
var subnode = keccak256(node, label);
NewOwner(node, label, owner);
records[subnode].owner = owner;
}
/**
* Sets the resolver address for the specified node.
* @param node The node to update.
* @param resolver The address of the resolver.
*/
function setResolver(bytes32 node, address resolver) only_owner(node) public {
NewResolver(node, resolver);
records[node].resolver = resolver;
}
/**
* Sets the TTL for the specified node.
* @param node The node to update.
* @param ttl The TTL in seconds.
*/
function setTTL(bytes32 node, uint64 ttl) only_owner(node) public {
NewTTL(node, ttl);
records[node].ttl = ttl;
}
}
// File: @aragon/os/contracts/lib/ens/PublicResolver.sol
// See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/PublicResolver.sol
pragma solidity ^0.4.0;
/**
* A simple resolver anyone can use; only allows the owner of a node to set its
* address.
*/
contract PublicResolver {
bytes4 constant INTERFACE_META_ID = 0x01ffc9a7;
bytes4 constant ADDR_INTERFACE_ID = 0x3b3b57de;
bytes4 constant CONTENT_INTERFACE_ID = 0xd8389dc5;
bytes4 constant NAME_INTERFACE_ID = 0x691f3431;
bytes4 constant ABI_INTERFACE_ID = 0x2203ab56;
bytes4 constant PUBKEY_INTERFACE_ID = 0xc8690233;
bytes4 constant TEXT_INTERFACE_ID = 0x59d1d43c;
event AddrChanged(bytes32 indexed node, address a);
event ContentChanged(bytes32 indexed node, bytes32 hash);
event NameChanged(bytes32 indexed node, string name);
event ABIChanged(bytes32 indexed node, uint256 indexed contentType);
event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y);
event TextChanged(bytes32 indexed node, string indexed indexedKey, string key);
struct PublicKey {
bytes32 x;
bytes32 y;
}
struct Record {
address addr;
bytes32 content;
string name;
PublicKey pubkey;
mapping(string=>string) text;
mapping(uint256=>bytes) abis;
}
AbstractENS ens;
mapping(bytes32=>Record) records;
modifier only_owner(bytes32 node) {
if (ens.owner(node) != msg.sender) throw;
_;
}
/**
* Constructor.
* @param ensAddr The ENS registrar contract.
*/
function PublicResolver(AbstractENS ensAddr) public {
ens = ensAddr;
}
/**
* Returns true if the resolver implements the interface specified by the provided hash.
* @param interfaceID The ID of the interface to check for.
* @return True if the contract implements the requested interface.
*/
function supportsInterface(bytes4 interfaceID) public pure returns (bool) {
return interfaceID == ADDR_INTERFACE_ID ||
interfaceID == CONTENT_INTERFACE_ID ||
interfaceID == NAME_INTERFACE_ID ||
interfaceID == ABI_INTERFACE_ID ||
interfaceID == PUBKEY_INTERFACE_ID ||
interfaceID == TEXT_INTERFACE_ID ||
interfaceID == INTERFACE_META_ID;
}
/**
* Returns the address associated with an ENS node.
* @param node The ENS node to query.
* @return The associated address.
*/
function addr(bytes32 node) public constant returns (address ret) {
ret = records[node].addr;
}
/**
* Sets the address associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param addr The address to set.
*/
function setAddr(bytes32 node, address addr) only_owner(node) public {
records[node].addr = addr;
AddrChanged(node, addr);
}
/**
* Returns the content hash associated with an ENS node.
* Note that this resource type is not standardized, and will likely change
* in future to a resource type based on multihash.
* @param node The ENS node to query.
* @return The associated content hash.
*/
function content(bytes32 node) public constant returns (bytes32 ret) {
ret = records[node].content;
}
/**
* Sets the content hash associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* Note that this resource type is not standardized, and will likely change
* in future to a resource type based on multihash.
* @param node The node to update.
* @param hash The content hash to set
*/
function setContent(bytes32 node, bytes32 hash) only_owner(node) public {
records[node].content = hash;
ContentChanged(node, hash);
}
/**
* Returns the name associated with an ENS node, for reverse records.
* Defined in EIP181.
* @param node The ENS node to query.
* @return The associated name.
*/
function name(bytes32 node) public constant returns (string ret) {
ret = records[node].name;
}
/**
* Sets the name associated with an ENS node, for reverse records.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param name The name to set.
*/
function setName(bytes32 node, string name) only_owner(node) public {
records[node].name = name;
NameChanged(node, name);
}
/**
* Returns the ABI associated with an ENS node.
* Defined in EIP205.
* @param node The ENS node to query
* @param contentTypes A bitwise OR of the ABI formats accepted by the caller.
* @return contentType The content type of the return value
* @return data The ABI data
*/
function ABI(bytes32 node, uint256 contentTypes) public constant returns (uint256 contentType, bytes data) {
var record = records[node];
for(contentType = 1; contentType <= contentTypes; contentType <<= 1) {
if ((contentType & contentTypes) != 0 && record.abis[contentType].length > 0) {
data = record.abis[contentType];
return;
}
}
contentType = 0;
}
/**
* Sets the ABI associated with an ENS node.
* Nodes may have one ABI of each content type. To remove an ABI, set it to
* the empty string.
* @param node The node to update.
* @param contentType The content type of the ABI
* @param data The ABI data.
*/
function setABI(bytes32 node, uint256 contentType, bytes data) only_owner(node) public {
// Content types must be powers of 2
if (((contentType - 1) & contentType) != 0) throw;
records[node].abis[contentType] = data;
ABIChanged(node, contentType);
}
/**
* Returns the SECP256k1 public key associated with an ENS node.
* Defined in EIP 619.
* @param node The ENS node to query
* @return x, y the X and Y coordinates of the curve point for the public key.
*/
function pubkey(bytes32 node) public constant returns (bytes32 x, bytes32 y) {
return (records[node].pubkey.x, records[node].pubkey.y);
}
/**
* Sets the SECP256k1 public key associated with an ENS node.
* @param node The ENS node to query
* @param x the X coordinate of the curve point for the public key.
* @param y the Y coordinate of the curve point for the public key.
*/
function setPubkey(bytes32 node, bytes32 x, bytes32 y) only_owner(node) public {
records[node].pubkey = PublicKey(x, y);
PubkeyChanged(node, x, y);
}
/**
* Returns the text data associated with an ENS node and key.
* @param node The ENS node to query.
* @param key The text data key to query.
* @return The associated text data.
*/
function text(bytes32 node, string key) public constant returns (string ret) {
ret = records[node].text[key];
}
/**
* Sets the text data associated with an ENS node and key.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param key The key to set.
* @param value The text data value to set.
*/
function setText(bytes32 node, string key, string value) only_owner(node) public {
records[node].text[key] = value;
TextChanged(node, key, key);
}
}
// File: @aragon/os/contracts/kernel/KernelProxy.sol
pragma solidity 0.4.24;
contract KernelProxy is IKernelEvents, KernelStorage, KernelAppIds, KernelNamespaceConstants, IsContract, DepositableDelegateProxy {
/**
* @dev KernelProxy is a proxy contract to a kernel implementation. The implementation
* can update the reference, which effectively upgrades the contract
* @param _kernelImpl Address of the contract used as implementation for kernel
*/
constructor(IKernel _kernelImpl) public {
require(isContract(address(_kernelImpl)));
apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID] = _kernelImpl;
// Note that emitting this event is important for verifying that a KernelProxy instance
// was never upgraded to a malicious Kernel logic contract over its lifespan.
// This starts the "chain of trust", that can be followed through later SetApp() events
// emitted during kernel upgrades.
emit SetApp(KERNEL_CORE_NAMESPACE, KERNEL_CORE_APP_ID, _kernelImpl);
}
/**
* @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy
*/
function proxyType() public pure returns (uint256 proxyTypeId) {
return UPGRADEABLE;
}
/**
* @dev ERC897, the address the proxy would delegate calls to
*/
function implementation() public view returns (address) {
return apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID];
}
}
// File: @aragon/os/contracts/evmscript/ScriptHelpers.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
library ScriptHelpers {
function getSpecId(bytes _script) internal pure returns (uint32) {
return uint32At(_script, 0);
}
function uint256At(bytes _data, uint256 _location) internal pure returns (uint256 result) {
assembly {
result := mload(add(_data, add(0x20, _location)))
}
}
function addressAt(bytes _data, uint256 _location) internal pure returns (address result) {
uint256 word = uint256At(_data, _location);
assembly {
result := div(and(word, 0xffffffffffffffffffffffffffffffffffffffff000000000000000000000000),
0x1000000000000000000000000)
}
}
function uint32At(bytes _data, uint256 _location) internal pure returns (uint32 result) {
uint256 word = uint256At(_data, _location);
assembly {
result := div(and(word, 0xffffffff00000000000000000000000000000000000000000000000000000000),
0x100000000000000000000000000000000000000000000000000000000)
}
}
function locationOf(bytes _data, uint256 _location) internal pure returns (uint256 result) {
assembly {
result := add(_data, add(0x20, _location))
}
}
function toBytes(bytes4 _sig) internal pure returns (bytes) {
bytes memory payload = new bytes(4);
assembly { mstore(add(payload, 0x20), _sig) }
return payload;
}
}
// File: @aragon/os/contracts/evmscript/EVMScriptRegistry.sol
pragma solidity 0.4.24;
/* solium-disable function-order */
// Allow public initialize() to be first
contract EVMScriptRegistry is IEVMScriptRegistry, EVMScriptRegistryConstants, AragonApp {
using ScriptHelpers for bytes;
/* Hardcoded constants to save gas
bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = keccak256("REGISTRY_ADD_EXECUTOR_ROLE");
bytes32 public constant REGISTRY_MANAGER_ROLE = keccak256("REGISTRY_MANAGER_ROLE");
*/
bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = 0xc4e90f38eea8c4212a009ca7b8947943ba4d4a58d19b683417f65291d1cd9ed2;
// WARN: Manager can censor all votes and the like happening in an org
bytes32 public constant REGISTRY_MANAGER_ROLE = 0xf7a450ef335e1892cb42c8ca72e7242359d7711924b75db5717410da3f614aa3;
uint256 internal constant SCRIPT_START_LOCATION = 4;
string private constant ERROR_INEXISTENT_EXECUTOR = "EVMREG_INEXISTENT_EXECUTOR";
string private constant ERROR_EXECUTOR_ENABLED = "EVMREG_EXECUTOR_ENABLED";
string private constant ERROR_EXECUTOR_DISABLED = "EVMREG_EXECUTOR_DISABLED";
string private constant ERROR_SCRIPT_LENGTH_TOO_SHORT = "EVMREG_SCRIPT_LENGTH_TOO_SHORT";
struct ExecutorEntry {
IEVMScriptExecutor executor;
bool enabled;
}
uint256 private executorsNextIndex;
mapping (uint256 => ExecutorEntry) public executors;
event EnableExecutor(uint256 indexed executorId, address indexed executorAddress);
event DisableExecutor(uint256 indexed executorId, address indexed executorAddress);
modifier executorExists(uint256 _executorId) {
require(_executorId > 0 && _executorId < executorsNextIndex, ERROR_INEXISTENT_EXECUTOR);
_;
}
/**
* @notice Initialize the registry
*/
function initialize() public onlyInit {
initialized();
// Create empty record to begin executor IDs at 1
executorsNextIndex = 1;
}
/**
* @notice Add a new script executor with address `_executor` to the registry
* @param _executor Address of the IEVMScriptExecutor that will be added to the registry
* @return id Identifier of the executor in the registry
*/
function addScriptExecutor(IEVMScriptExecutor _executor) external auth(REGISTRY_ADD_EXECUTOR_ROLE) returns (uint256 id) {
uint256 executorId = executorsNextIndex++;
executors[executorId] = ExecutorEntry(_executor, true);
emit EnableExecutor(executorId, _executor);
return executorId;
}
/**
* @notice Disable script executor with ID `_executorId`
* @param _executorId Identifier of the executor in the registry
*/
function disableScriptExecutor(uint256 _executorId)
external
authP(REGISTRY_MANAGER_ROLE, arr(_executorId))
{
// Note that we don't need to check for an executor's existence in this case, as only
// existing executors can be enabled
ExecutorEntry storage executorEntry = executors[_executorId];
require(executorEntry.enabled, ERROR_EXECUTOR_DISABLED);
executorEntry.enabled = false;
emit DisableExecutor(_executorId, executorEntry.executor);
}
/**
* @notice Enable script executor with ID `_executorId`
* @param _executorId Identifier of the executor in the registry
*/
function enableScriptExecutor(uint256 _executorId)
external
authP(REGISTRY_MANAGER_ROLE, arr(_executorId))
executorExists(_executorId)
{
ExecutorEntry storage executorEntry = executors[_executorId];
require(!executorEntry.enabled, ERROR_EXECUTOR_ENABLED);
executorEntry.enabled = true;
emit EnableExecutor(_executorId, executorEntry.executor);
}
/**
* @dev Get the script executor that can execute a particular script based on its first 4 bytes
* @param _script EVMScript being inspected
*/
function getScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) {
require(_script.length >= SCRIPT_START_LOCATION, ERROR_SCRIPT_LENGTH_TOO_SHORT);
uint256 id = _script.getSpecId();
// Note that we don't need to check for an executor's existence in this case, as only
// existing executors can be enabled
ExecutorEntry storage entry = executors[id];
return entry.enabled ? entry.executor : IEVMScriptExecutor(0);
}
}
// File: @aragon/os/contracts/evmscript/executors/BaseEVMScriptExecutor.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract BaseEVMScriptExecutor is IEVMScriptExecutor, Autopetrified {
uint256 internal constant SCRIPT_START_LOCATION = 4;
}
// File: @aragon/os/contracts/evmscript/executors/CallsScript.sol
pragma solidity 0.4.24;
// Inspired by https://github.com/reverendus/tx-manager
contract CallsScript is BaseEVMScriptExecutor {
using ScriptHelpers for bytes;
/* Hardcoded constants to save gas
bytes32 internal constant EXECUTOR_TYPE = keccak256("CALLS_SCRIPT");
*/
bytes32 internal constant EXECUTOR_TYPE = 0x2dc858a00f3e417be1394b87c07158e989ec681ce8cc68a9093680ac1a870302;
string private constant ERROR_BLACKLISTED_CALL = "EVMCALLS_BLACKLISTED_CALL";
string private constant ERROR_INVALID_LENGTH = "EVMCALLS_INVALID_LENGTH";
/* This is manually crafted in assembly
string private constant ERROR_CALL_REVERTED = "EVMCALLS_CALL_REVERTED";
*/
event LogScriptCall(address indexed sender, address indexed src, address indexed dst);
/**
* @notice Executes a number of call scripts
* @param _script [ specId (uint32) ] many calls with this structure ->
* [ to (address: 20 bytes) ] [ calldataLength (uint32: 4 bytes) ] [ calldata (calldataLength bytes) ]
* @param _blacklist Addresses the script cannot call to, or will revert.
* @return Always returns empty byte array
*/
function execScript(bytes _script, bytes, address[] _blacklist) external isInitialized returns (bytes) {
uint256 location = SCRIPT_START_LOCATION; // first 32 bits are spec id
while (location < _script.length) {
// Check there's at least address + calldataLength available
require(_script.length - location >= 0x18, ERROR_INVALID_LENGTH);
address contractAddress = _script.addressAt(location);
// Check address being called is not blacklist
for (uint256 i = 0; i < _blacklist.length; i++) {
require(contractAddress != _blacklist[i], ERROR_BLACKLISTED_CALL);
}
// logged before execution to ensure event ordering in receipt
// if failed entire execution is reverted regardless
emit LogScriptCall(msg.sender, address(this), contractAddress);
uint256 calldataLength = uint256(_script.uint32At(location + 0x14));
uint256 startOffset = location + 0x14 + 0x04;
uint256 calldataStart = _script.locationOf(startOffset);
// compute end of script / next location
location = startOffset + calldataLength;
require(location <= _script.length, ERROR_INVALID_LENGTH);
bool success;
assembly {
success := call(
sub(gas, 5000), // forward gas left - 5000
contractAddress, // address
0, // no value
calldataStart, // calldata start
calldataLength, // calldata length
0, // don't write output
0 // don't write output
)
switch success
case 0 {
let ptr := mload(0x40)
switch returndatasize
case 0 {
// No error data was returned, revert with "EVMCALLS_CALL_REVERTED"
// See remix: doing a `revert("EVMCALLS_CALL_REVERTED")` always results in
// this memory layout
mstore(ptr, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier
mstore(add(ptr, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset
mstore(add(ptr, 0x24), 0x0000000000000000000000000000000000000000000000000000000000000016) // reason length
mstore(add(ptr, 0x44), 0x45564d43414c4c535f43414c4c5f524556455254454400000000000000000000) // reason
revert(ptr, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error)
}
default {
// Forward the full error data
returndatacopy(ptr, 0, returndatasize)
revert(ptr, returndatasize)
}
}
default { }
}
}
// No need to allocate empty bytes for the return as this can only be called via an delegatecall
// (due to the isInitialized modifier)
}
function executorType() external pure returns (bytes32) {
return EXECUTOR_TYPE;
}
}
// File: @aragon/os/contracts/factory/EVMScriptRegistryFactory.sol
pragma solidity 0.4.24;
contract EVMScriptRegistryFactory is EVMScriptRegistryConstants {
EVMScriptRegistry public baseReg;
IEVMScriptExecutor public baseCallScript;
/**
* @notice Create a new EVMScriptRegistryFactory.
*/
constructor() public {
baseReg = new EVMScriptRegistry();
baseCallScript = IEVMScriptExecutor(new CallsScript());
}
/**
* @notice Install a new pinned instance of EVMScriptRegistry on `_dao`.
* @param _dao Kernel
* @return Installed EVMScriptRegistry
*/
function newEVMScriptRegistry(Kernel _dao) public returns (EVMScriptRegistry reg) {
bytes memory initPayload = abi.encodeWithSelector(reg.initialize.selector);
reg = EVMScriptRegistry(_dao.newPinnedAppInstance(EVMSCRIPT_REGISTRY_APP_ID, baseReg, initPayload, true));
ACL acl = ACL(_dao.acl());
acl.createPermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE(), this);
reg.addScriptExecutor(baseCallScript); // spec 1 = CallsScript
// Clean up the permissions
acl.revokePermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE());
acl.removePermissionManager(reg, reg.REGISTRY_ADD_EXECUTOR_ROLE());
return reg;
}
}
// File: @aragon/os/contracts/factory/DAOFactory.sol
pragma solidity 0.4.24;
contract DAOFactory {
IKernel public baseKernel;
IACL public baseACL;
EVMScriptRegistryFactory public regFactory;
event DeployDAO(address dao);
event DeployEVMScriptRegistry(address reg);
/**
* @notice Create a new DAOFactory, creating DAOs with Kernels proxied to `_baseKernel`, ACLs proxied to `_baseACL`, and new EVMScriptRegistries created from `_regFactory`.
* @param _baseKernel Base Kernel
* @param _baseACL Base ACL
* @param _regFactory EVMScriptRegistry factory
*/
constructor(IKernel _baseKernel, IACL _baseACL, EVMScriptRegistryFactory _regFactory) public {
// No need to init as it cannot be killed by devops199
if (address(_regFactory) != address(0)) {
regFactory = _regFactory;
}
baseKernel = _baseKernel;
baseACL = _baseACL;
}
/**
* @notice Create a new DAO with `_root` set as the initial admin
* @param _root Address that will be granted control to setup DAO permissions
* @return Newly created DAO
*/
function newDAO(address _root) public returns (Kernel) {
Kernel dao = Kernel(new KernelProxy(baseKernel));
if (address(regFactory) == address(0)) {
dao.initialize(baseACL, _root);
} else {
dao.initialize(baseACL, this);
ACL acl = ACL(dao.acl());
bytes32 permRole = acl.CREATE_PERMISSIONS_ROLE();
bytes32 appManagerRole = dao.APP_MANAGER_ROLE();
acl.grantPermission(regFactory, acl, permRole);
acl.createPermission(regFactory, dao, appManagerRole, this);
EVMScriptRegistry reg = regFactory.newEVMScriptRegistry(dao);
emit DeployEVMScriptRegistry(address(reg));
// Clean up permissions
// First, completely reset the APP_MANAGER_ROLE
acl.revokePermission(regFactory, dao, appManagerRole);
acl.removePermissionManager(dao, appManagerRole);
// Then, make root the only holder and manager of CREATE_PERMISSIONS_ROLE
acl.revokePermission(regFactory, acl, permRole);
acl.revokePermission(this, acl, permRole);
acl.grantPermission(_root, acl, permRole);
acl.setPermissionManager(_root, acl, permRole);
}
emit DeployDAO(address(dao));
return dao;
}
}
// File: @aragon/id/contracts/ens/IPublicResolver.sol
pragma solidity ^0.4.0;
interface IPublicResolver {
function supportsInterface(bytes4 interfaceID) constant returns (bool);
function addr(bytes32 node) constant returns (address ret);
function setAddr(bytes32 node, address addr);
function hash(bytes32 node) constant returns (bytes32 ret);
function setHash(bytes32 node, bytes32 hash);
}
// File: @aragon/id/contracts/IFIFSResolvingRegistrar.sol
pragma solidity 0.4.24;
interface IFIFSResolvingRegistrar {
function register(bytes32 _subnode, address _owner) external;
function registerWithResolver(bytes32 _subnode, address _owner, IPublicResolver _resolver) public;
}
// File: @aragon/templates-shared/contracts/BaseTemplate.sol
pragma solidity 0.4.24;
contract BaseTemplate is APMNamehash, IsContract {
using Uint256Helpers for uint256;
/* Hardcoded constant to save gas
* bytes32 constant internal AGENT_APP_ID = apmNamehash("agent"); // agent.aragonpm.eth
* bytes32 constant internal VAULT_APP_ID = apmNamehash("vault"); // vault.aragonpm.eth
* bytes32 constant internal VOTING_APP_ID = apmNamehash("voting"); // voting.aragonpm.eth
* bytes32 constant internal SURVEY_APP_ID = apmNamehash("survey"); // survey.aragonpm.eth
* bytes32 constant internal PAYROLL_APP_ID = apmNamehash("payroll"); // payroll.aragonpm.eth
* bytes32 constant internal FINANCE_APP_ID = apmNamehash("finance"); // finance.aragonpm.eth
* bytes32 constant internal TOKEN_MANAGER_APP_ID = apmNamehash("token-manager"); // token-manager.aragonpm.eth
*/
bytes32 constant internal AGENT_APP_ID = 0x9ac98dc5f995bf0211ed589ef022719d1487e5cb2bab505676f0d084c07cf89a;
bytes32 constant internal VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1;
bytes32 constant internal VOTING_APP_ID = 0x9fa3927f639745e587912d4b0fea7ef9013bf93fb907d29faeab57417ba6e1d4;
bytes32 constant internal PAYROLL_APP_ID = 0x463f596a96d808cb28b5d080181e4a398bc793df2c222f6445189eb801001991;
bytes32 constant internal FINANCE_APP_ID = 0xbf8491150dafc5dcaee5b861414dca922de09ccffa344964ae167212e8c673ae;
bytes32 constant internal TOKEN_MANAGER_APP_ID = 0x6b20a3010614eeebf2138ccec99f028a61c811b3b1a3343b6ff635985c75c91f;
bytes32 constant internal SURVEY_APP_ID = 0x030b2ab880b88e228f2da5a3d19a2a31bc10dbf91fb1143776a6de489389471e;
string constant private ERROR_ENS_NOT_CONTRACT = "TEMPLATE_ENS_NOT_CONTRACT";
string constant private ERROR_DAO_FACTORY_NOT_CONTRACT = "TEMPLATE_DAO_FAC_NOT_CONTRACT";
string constant private ERROR_ARAGON_ID_NOT_PROVIDED = "TEMPLATE_ARAGON_ID_NOT_PROVIDED";
string constant private ERROR_ARAGON_ID_NOT_CONTRACT = "TEMPLATE_ARAGON_ID_NOT_CONTRACT";
string constant private ERROR_MINIME_FACTORY_NOT_PROVIDED = "TEMPLATE_MINIME_FAC_NOT_PROVIDED";
string constant private ERROR_MINIME_FACTORY_NOT_CONTRACT = "TEMPLATE_MINIME_FAC_NOT_CONTRACT";
string constant private ERROR_CANNOT_CAST_VALUE_TO_ADDRESS = "TEMPLATE_CANNOT_CAST_VALUE_TO_ADDRESS";
string constant private ERROR_INVALID_ID = "TEMPLATE_INVALID_ID";
ENS internal ens;
DAOFactory internal daoFactory;
MiniMeTokenFactory internal miniMeFactory;
IFIFSResolvingRegistrar internal aragonID;
event DeployDao(address dao);
event SetupDao(address dao);
event DeployToken(address token);
event InstalledApp(address appProxy, bytes32 appId);
constructor(DAOFactory _daoFactory, ENS _ens, MiniMeTokenFactory _miniMeFactory, IFIFSResolvingRegistrar _aragonID) public {
require(isContract(address(_ens)), ERROR_ENS_NOT_CONTRACT);
require(isContract(address(_daoFactory)), ERROR_DAO_FACTORY_NOT_CONTRACT);
ens = _ens;
aragonID = _aragonID;
daoFactory = _daoFactory;
miniMeFactory = _miniMeFactory;
}
/**
* @dev Create a DAO using the DAO Factory and grant the template root permissions so it has full
* control during setup. Once the DAO setup has finished, it is recommended to call the
* `_transferRootPermissionsFromTemplateAndFinalizeDAO()` helper to transfer the root
* permissions to the end entity in control of the organization.
*/
function _createDAO() internal returns (Kernel dao, ACL acl) {
dao = daoFactory.newDAO(this);
emit DeployDao(address(dao));
acl = ACL(dao.acl());
_createPermissionForTemplate(acl, dao, dao.APP_MANAGER_ROLE());
}
/* ACL */
function _createPermissions(ACL _acl, address[] memory _grantees, address _app, bytes32 _permission, address _manager) internal {
_acl.createPermission(_grantees[0], _app, _permission, address(this));
for (uint256 i = 1; i < _grantees.length; i++) {
_acl.grantPermission(_grantees[i], _app, _permission);
}
_acl.revokePermission(address(this), _app, _permission);
_acl.setPermissionManager(_manager, _app, _permission);
}
function _createPermissionForTemplate(ACL _acl, address _app, bytes32 _permission) internal {
_acl.createPermission(address(this), _app, _permission, address(this));
}
function _removePermissionFromTemplate(ACL _acl, address _app, bytes32 _permission) internal {
_acl.revokePermission(address(this), _app, _permission);
_acl.removePermissionManager(_app, _permission);
}
function _transferRootPermissionsFromTemplateAndFinalizeDAO(Kernel _dao, address _to) internal {
_transferRootPermissionsFromTemplateAndFinalizeDAO(_dao, _to, _to);
}
function _transferRootPermissionsFromTemplateAndFinalizeDAO(Kernel _dao, address _to, address _manager) internal {
ACL _acl = ACL(_dao.acl());
_transferPermissionFromTemplate(_acl, _dao, _to, _dao.APP_MANAGER_ROLE(), _manager);
_transferPermissionFromTemplate(_acl, _acl, _to, _acl.CREATE_PERMISSIONS_ROLE(), _manager);
emit SetupDao(_dao);
}
function _transferPermissionFromTemplate(ACL _acl, address _app, address _to, bytes32 _permission, address _manager) internal {
_acl.grantPermission(_to, _app, _permission);
_acl.revokePermission(address(this), _app, _permission);
_acl.setPermissionManager(_manager, _app, _permission);
}
/* AGENT */
function _installDefaultAgentApp(Kernel _dao) internal returns (Agent) {
bytes memory initializeData = abi.encodeWithSelector(Agent(0).initialize.selector);
Agent agent = Agent(_installDefaultApp(_dao, AGENT_APP_ID, initializeData));
// We assume that installing the Agent app as a default app means the DAO should have its
// Vault replaced by the Agent. Thus, we also set the DAO's recovery app to the Agent.
_dao.setRecoveryVaultAppId(AGENT_APP_ID);
return agent;
}
function _installNonDefaultAgentApp(Kernel _dao) internal returns (Agent) {
bytes memory initializeData = abi.encodeWithSelector(Agent(0).initialize.selector);
return Agent(_installNonDefaultApp(_dao, AGENT_APP_ID, initializeData));
}
function _createAgentPermissions(ACL _acl, Agent _agent, address _grantee, address _manager) internal {
_acl.createPermission(_grantee, _agent, _agent.EXECUTE_ROLE(), _manager);
_acl.createPermission(_grantee, _agent, _agent.RUN_SCRIPT_ROLE(), _manager);
}
/* VAULT */
function _installVaultApp(Kernel _dao) internal returns (Vault) {
bytes memory initializeData = abi.encodeWithSelector(Vault(0).initialize.selector);
return Vault(_installDefaultApp(_dao, VAULT_APP_ID, initializeData));
}
function _createVaultPermissions(ACL _acl, Vault _vault, address _grantee, address _manager) internal {
_acl.createPermission(_grantee, _vault, _vault.TRANSFER_ROLE(), _manager);
}
/* VOTING */
function _installVotingApp(Kernel _dao, MiniMeToken _token, uint64[3] memory _votingSettings) internal returns (Voting) {
return _installVotingApp(_dao, _token, _votingSettings[0], _votingSettings[1], _votingSettings[2]);
}
function _installVotingApp(
Kernel _dao,
MiniMeToken _token,
uint64 _support,
uint64 _acceptance,
uint64 _duration
)
internal returns (Voting)
{
bytes memory initializeData = abi.encodeWithSelector(Voting(0).initialize.selector, _token, _support, _acceptance, _duration);
return Voting(_installNonDefaultApp(_dao, VOTING_APP_ID, initializeData));
}
function _createVotingPermissions(
ACL _acl,
Voting _voting,
address _settingsGrantee,
address _createVotesGrantee,
address _manager
)
internal
{
_acl.createPermission(_settingsGrantee, _voting, _voting.MODIFY_QUORUM_ROLE(), _manager);
_acl.createPermission(_settingsGrantee, _voting, _voting.MODIFY_SUPPORT_ROLE(), _manager);
_acl.createPermission(_createVotesGrantee, _voting, _voting.CREATE_VOTES_ROLE(), _manager);
}
/* SURVEY */
function _installSurveyApp(Kernel _dao, MiniMeToken _token, uint64 _minParticipationPct, uint64 _surveyTime) internal returns (Survey) {
bytes memory initializeData = abi.encodeWithSelector(Survey(0).initialize.selector, _token, _minParticipationPct, _surveyTime);
return Survey(_installNonDefaultApp(_dao, SURVEY_APP_ID, initializeData));
}
function _createSurveyPermissions(ACL _acl, Survey _survey, address _grantee, address _manager) internal {
_acl.createPermission(_grantee, _survey, _survey.CREATE_SURVEYS_ROLE(), _manager);
_acl.createPermission(_grantee, _survey, _survey.MODIFY_PARTICIPATION_ROLE(), _manager);
}
/* PAYROLL */
function _installPayrollApp(
Kernel _dao,
Finance _finance,
address _denominationToken,
IFeed _priceFeed,
uint64 _rateExpiryTime
)
internal returns (Payroll)
{
bytes memory initializeData = abi.encodeWithSelector(
Payroll(0).initialize.selector,
_finance,
_denominationToken,
_priceFeed,
_rateExpiryTime
);
return Payroll(_installNonDefaultApp(_dao, PAYROLL_APP_ID, initializeData));
}
/**
* @dev Internal function to configure payroll permissions. Note that we allow defining different managers for
* payroll since it may be useful to have one control the payroll settings (rate expiration, price feed,
* and allowed tokens), and another one to control the employee functionality (bonuses, salaries,
* reimbursements, employees, etc).
* @param _acl ACL instance being configured
* @param _acl Payroll app being configured
* @param _employeeManager Address that will receive permissions to handle employee payroll functionality
* @param _settingsManager Address that will receive permissions to manage payroll settings
* @param _permissionsManager Address that will be the ACL manager for the payroll permissions
*/
function _createPayrollPermissions(
ACL _acl,
Payroll _payroll,
address _employeeManager,
address _settingsManager,
address _permissionsManager
)
internal
{
_acl.createPermission(_employeeManager, _payroll, _payroll.ADD_BONUS_ROLE(), _permissionsManager);
_acl.createPermission(_employeeManager, _payroll, _payroll.ADD_EMPLOYEE_ROLE(), _permissionsManager);
_acl.createPermission(_employeeManager, _payroll, _payroll.ADD_REIMBURSEMENT_ROLE(), _permissionsManager);
_acl.createPermission(_employeeManager, _payroll, _payroll.TERMINATE_EMPLOYEE_ROLE(), _permissionsManager);
_acl.createPermission(_employeeManager, _payroll, _payroll.SET_EMPLOYEE_SALARY_ROLE(), _permissionsManager);
_acl.createPermission(_settingsManager, _payroll, _payroll.MODIFY_PRICE_FEED_ROLE(), _permissionsManager);
_acl.createPermission(_settingsManager, _payroll, _payroll.MODIFY_RATE_EXPIRY_ROLE(), _permissionsManager);
_acl.createPermission(_settingsManager, _payroll, _payroll.MANAGE_ALLOWED_TOKENS_ROLE(), _permissionsManager);
}
function _unwrapPayrollSettings(
uint256[4] memory _payrollSettings
)
internal pure returns (address denominationToken, IFeed priceFeed, uint64 rateExpiryTime, address employeeManager)
{
denominationToken = _toAddress(_payrollSettings[0]);
priceFeed = IFeed(_toAddress(_payrollSettings[1]));
rateExpiryTime = _payrollSettings[2].toUint64();
employeeManager = _toAddress(_payrollSettings[3]);
}
/* FINANCE */
function _installFinanceApp(Kernel _dao, Vault _vault, uint64 _periodDuration) internal returns (Finance) {
bytes memory initializeData = abi.encodeWithSelector(Finance(0).initialize.selector, _vault, _periodDuration);
return Finance(_installNonDefaultApp(_dao, FINANCE_APP_ID, initializeData));
}
function _createFinancePermissions(ACL _acl, Finance _finance, address _grantee, address _manager) internal {
_acl.createPermission(_grantee, _finance, _finance.EXECUTE_PAYMENTS_ROLE(), _manager);
_acl.createPermission(_grantee, _finance, _finance.MANAGE_PAYMENTS_ROLE(), _manager);
}
function _createFinanceCreatePaymentsPermission(ACL _acl, Finance _finance, address _grantee, address _manager) internal {
_acl.createPermission(_grantee, _finance, _finance.CREATE_PAYMENTS_ROLE(), _manager);
}
function _grantCreatePaymentPermission(ACL _acl, Finance _finance, address _to) internal {
_acl.grantPermission(_to, _finance, _finance.CREATE_PAYMENTS_ROLE());
}
function _transferCreatePaymentManagerFromTemplate(ACL _acl, Finance _finance, address _manager) internal {
_acl.setPermissionManager(_manager, _finance, _finance.CREATE_PAYMENTS_ROLE());
}
/* TOKEN MANAGER */
function _installTokenManagerApp(
Kernel _dao,
MiniMeToken _token,
bool _transferable,
uint256 _maxAccountTokens
)
internal returns (TokenManager)
{
TokenManager tokenManager = TokenManager(_installNonDefaultApp(_dao, TOKEN_MANAGER_APP_ID));
_token.changeController(tokenManager);
tokenManager.initialize(_token, _transferable, _maxAccountTokens);
return tokenManager;
}
function _createTokenManagerPermissions(ACL _acl, TokenManager _tokenManager, address _grantee, address _manager) internal {
_acl.createPermission(_grantee, _tokenManager, _tokenManager.MINT_ROLE(), _manager);
_acl.createPermission(_grantee, _tokenManager, _tokenManager.BURN_ROLE(), _manager);
}
function _mintTokens(ACL _acl, TokenManager _tokenManager, address[] memory _holders, uint256[] memory _stakes) internal {
_createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE());
for (uint256 i = 0; i < _holders.length; i++) {
_tokenManager.mint(_holders[i], _stakes[i]);
}
_removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE());
}
function _mintTokens(ACL _acl, TokenManager _tokenManager, address[] memory _holders, uint256 _stake) internal {
_createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE());
for (uint256 i = 0; i < _holders.length; i++) {
_tokenManager.mint(_holders[i], _stake);
}
_removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE());
}
function _mintTokens(ACL _acl, TokenManager _tokenManager, address _holder, uint256 _stake) internal {
_createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE());
_tokenManager.mint(_holder, _stake);
_removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE());
}
/* EVM SCRIPTS */
function _createEvmScriptsRegistryPermissions(ACL _acl, address _grantee, address _manager) internal {
EVMScriptRegistry registry = EVMScriptRegistry(_acl.getEVMScriptRegistry());
_acl.createPermission(_grantee, registry, registry.REGISTRY_MANAGER_ROLE(), _manager);
_acl.createPermission(_grantee, registry, registry.REGISTRY_ADD_EXECUTOR_ROLE(), _manager);
}
/* APPS */
function _installNonDefaultApp(Kernel _dao, bytes32 _appId) internal returns (address) {
return _installNonDefaultApp(_dao, _appId, new bytes(0));
}
function _installNonDefaultApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData) internal returns (address) {
return _installApp(_dao, _appId, _initializeData, false);
}
function _installDefaultApp(Kernel _dao, bytes32 _appId) internal returns (address) {
return _installDefaultApp(_dao, _appId, new bytes(0));
}
function _installDefaultApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData) internal returns (address) {
return _installApp(_dao, _appId, _initializeData, true);
}
function _installApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData, bool _setDefault) internal returns (address) {
address latestBaseAppAddress = _latestVersionAppBase(_appId);
address instance = address(_dao.newAppInstance(_appId, latestBaseAppAddress, _initializeData, _setDefault));
emit InstalledApp(instance, _appId);
return instance;
}
function _latestVersionAppBase(bytes32 _appId) internal view returns (address base) {
Repo repo = Repo(PublicResolver(ens.resolver(_appId)).addr(_appId));
(,base,) = repo.getLatest();
}
/* TOKEN */
function _createToken(string memory _name, string memory _symbol, uint8 _decimals) internal returns (MiniMeToken) {
require(address(miniMeFactory) != address(0), ERROR_MINIME_FACTORY_NOT_PROVIDED);
MiniMeToken token = miniMeFactory.createCloneToken(MiniMeToken(address(0)), 0, _name, _decimals, _symbol, true);
emit DeployToken(address(token));
return token;
}
function _ensureMiniMeFactoryIsValid(address _miniMeFactory) internal view {
require(isContract(address(_miniMeFactory)), ERROR_MINIME_FACTORY_NOT_CONTRACT);
}
/* IDS */
function _validateId(string memory _id) internal pure {
require(bytes(_id).length > 0, ERROR_INVALID_ID);
}
function _registerID(string memory _name, address _owner) internal {
require(address(aragonID) != address(0), ERROR_ARAGON_ID_NOT_PROVIDED);
aragonID.register(keccak256(abi.encodePacked(_name)), _owner);
}
function _ensureAragonIdIsValid(address _aragonID) internal view {
require(isContract(address(_aragonID)), ERROR_ARAGON_ID_NOT_CONTRACT);
}
/* HELPERS */
function _toAddress(uint256 _value) private pure returns (address) {
require(_value <= uint160(-1), ERROR_CANNOT_CAST_VALUE_TO_ADDRESS);
return address(_value);
}
}
// File: @ablack/fundraising-bancor-formula/contracts/interfaces/IBancorFormula.sol
pragma solidity 0.4.24;
/*
Bancor Formula interface
*/
contract IBancorFormula {
function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256);
function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256);
function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256);
}
// File: @ablack/fundraising-bancor-formula/contracts/utility/Utils.sol
pragma solidity 0.4.24;
/*
Utilities & Common Modifiers
*/
contract Utils {
/**
constructor
*/
constructor() public {
}
// verifies that an amount is greater than zero
modifier greaterThanZero(uint256 _amount) {
require(_amount > 0);
_;
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
require(_address != address(0));
_;
}
// verifies that the address is different than this contract address
modifier notThis(address _address) {
require(_address != address(this));
_;
}
}
// File: @ablack/fundraising-bancor-formula/contracts/BancorFormula.sol
pragma solidity 0.4.24;
contract BancorFormula is IBancorFormula, Utils {
using SafeMath for uint256;
string public version = '0.3';
uint256 private constant ONE = 1;
uint32 private constant MAX_WEIGHT = 1000000;
uint8 private constant MIN_PRECISION = 32;
uint8 private constant MAX_PRECISION = 127;
/**
Auto-generated via 'PrintIntScalingFactors.py'
*/
uint256 private constant FIXED_1 = 0x080000000000000000000000000000000;
uint256 private constant FIXED_2 = 0x100000000000000000000000000000000;
uint256 private constant MAX_NUM = 0x200000000000000000000000000000000;
/**
Auto-generated via 'PrintLn2ScalingFactors.py'
*/
uint256 private constant LN2_NUMERATOR = 0x3f80fe03f80fe03f80fe03f80fe03f8;
uint256 private constant LN2_DENOMINATOR = 0x5b9de1d10bf4103d647b0955897ba80;
/**
Auto-generated via 'PrintFunctionOptimalLog.py' and 'PrintFunctionOptimalExp.py'
*/
uint256 private constant OPT_LOG_MAX_VAL = 0x15bf0a8b1457695355fb8ac404e7a79e3;
uint256 private constant OPT_EXP_MAX_VAL = 0x800000000000000000000000000000000;
/**
Auto-generated via 'PrintFunctionConstructor.py'
*/
uint256[128] private maxExpArray;
constructor() public {
// maxExpArray[ 0] = 0x6bffffffffffffffffffffffffffffffff;
// maxExpArray[ 1] = 0x67ffffffffffffffffffffffffffffffff;
// maxExpArray[ 2] = 0x637fffffffffffffffffffffffffffffff;
// maxExpArray[ 3] = 0x5f6fffffffffffffffffffffffffffffff;
// maxExpArray[ 4] = 0x5b77ffffffffffffffffffffffffffffff;
// maxExpArray[ 5] = 0x57b3ffffffffffffffffffffffffffffff;
// maxExpArray[ 6] = 0x5419ffffffffffffffffffffffffffffff;
// maxExpArray[ 7] = 0x50a2ffffffffffffffffffffffffffffff;
// maxExpArray[ 8] = 0x4d517fffffffffffffffffffffffffffff;
// maxExpArray[ 9] = 0x4a233fffffffffffffffffffffffffffff;
// maxExpArray[ 10] = 0x47165fffffffffffffffffffffffffffff;
// maxExpArray[ 11] = 0x4429afffffffffffffffffffffffffffff;
// maxExpArray[ 12] = 0x415bc7ffffffffffffffffffffffffffff;
// maxExpArray[ 13] = 0x3eab73ffffffffffffffffffffffffffff;
// maxExpArray[ 14] = 0x3c1771ffffffffffffffffffffffffffff;
// maxExpArray[ 15] = 0x399e96ffffffffffffffffffffffffffff;
// maxExpArray[ 16] = 0x373fc47fffffffffffffffffffffffffff;
// maxExpArray[ 17] = 0x34f9e8ffffffffffffffffffffffffffff;
// maxExpArray[ 18] = 0x32cbfd5fffffffffffffffffffffffffff;
// maxExpArray[ 19] = 0x30b5057fffffffffffffffffffffffffff;
// maxExpArray[ 20] = 0x2eb40f9fffffffffffffffffffffffffff;
// maxExpArray[ 21] = 0x2cc8340fffffffffffffffffffffffffff;
// maxExpArray[ 22] = 0x2af09481ffffffffffffffffffffffffff;
// maxExpArray[ 23] = 0x292c5bddffffffffffffffffffffffffff;
// maxExpArray[ 24] = 0x277abdcdffffffffffffffffffffffffff;
// maxExpArray[ 25] = 0x25daf6657fffffffffffffffffffffffff;
// maxExpArray[ 26] = 0x244c49c65fffffffffffffffffffffffff;
// maxExpArray[ 27] = 0x22ce03cd5fffffffffffffffffffffffff;
// maxExpArray[ 28] = 0x215f77c047ffffffffffffffffffffffff;
// maxExpArray[ 29] = 0x1fffffffffffffffffffffffffffffffff;
// maxExpArray[ 30] = 0x1eaefdbdabffffffffffffffffffffffff;
// maxExpArray[ 31] = 0x1d6bd8b2ebffffffffffffffffffffffff;
maxExpArray[ 32] = 0x1c35fedd14ffffffffffffffffffffffff;
maxExpArray[ 33] = 0x1b0ce43b323fffffffffffffffffffffff;
maxExpArray[ 34] = 0x19f0028ec1ffffffffffffffffffffffff;
maxExpArray[ 35] = 0x18ded91f0e7fffffffffffffffffffffff;
maxExpArray[ 36] = 0x17d8ec7f0417ffffffffffffffffffffff;
maxExpArray[ 37] = 0x16ddc6556cdbffffffffffffffffffffff;
maxExpArray[ 38] = 0x15ecf52776a1ffffffffffffffffffffff;
maxExpArray[ 39] = 0x15060c256cb2ffffffffffffffffffffff;
maxExpArray[ 40] = 0x1428a2f98d72ffffffffffffffffffffff;
maxExpArray[ 41] = 0x13545598e5c23fffffffffffffffffffff;
maxExpArray[ 42] = 0x1288c4161ce1dfffffffffffffffffffff;
maxExpArray[ 43] = 0x11c592761c666fffffffffffffffffffff;
maxExpArray[ 44] = 0x110a688680a757ffffffffffffffffffff;
maxExpArray[ 45] = 0x1056f1b5bedf77ffffffffffffffffffff;
maxExpArray[ 46] = 0x0faadceceeff8bffffffffffffffffffff;
maxExpArray[ 47] = 0x0f05dc6b27edadffffffffffffffffffff;
maxExpArray[ 48] = 0x0e67a5a25da4107fffffffffffffffffff;
maxExpArray[ 49] = 0x0dcff115b14eedffffffffffffffffffff;
maxExpArray[ 50] = 0x0d3e7a392431239fffffffffffffffffff;
maxExpArray[ 51] = 0x0cb2ff529eb71e4fffffffffffffffffff;
maxExpArray[ 52] = 0x0c2d415c3db974afffffffffffffffffff;
maxExpArray[ 53] = 0x0bad03e7d883f69bffffffffffffffffff;
maxExpArray[ 54] = 0x0b320d03b2c343d5ffffffffffffffffff;
maxExpArray[ 55] = 0x0abc25204e02828dffffffffffffffffff;
maxExpArray[ 56] = 0x0a4b16f74ee4bb207fffffffffffffffff;
maxExpArray[ 57] = 0x09deaf736ac1f569ffffffffffffffffff;
maxExpArray[ 58] = 0x0976bd9952c7aa957fffffffffffffffff;
maxExpArray[ 59] = 0x09131271922eaa606fffffffffffffffff;
maxExpArray[ 60] = 0x08b380f3558668c46fffffffffffffffff;
maxExpArray[ 61] = 0x0857ddf0117efa215bffffffffffffffff;
maxExpArray[ 62] = 0x07ffffffffffffffffffffffffffffffff;
maxExpArray[ 63] = 0x07abbf6f6abb9d087fffffffffffffffff;
maxExpArray[ 64] = 0x075af62cbac95f7dfa7fffffffffffffff;
maxExpArray[ 65] = 0x070d7fb7452e187ac13fffffffffffffff;
maxExpArray[ 66] = 0x06c3390ecc8af379295fffffffffffffff;
maxExpArray[ 67] = 0x067c00a3b07ffc01fd6fffffffffffffff;
maxExpArray[ 68] = 0x0637b647c39cbb9d3d27ffffffffffffff;
maxExpArray[ 69] = 0x05f63b1fc104dbd39587ffffffffffffff;
maxExpArray[ 70] = 0x05b771955b36e12f7235ffffffffffffff;
maxExpArray[ 71] = 0x057b3d49dda84556d6f6ffffffffffffff;
maxExpArray[ 72] = 0x054183095b2c8ececf30ffffffffffffff;
maxExpArray[ 73] = 0x050a28be635ca2b888f77fffffffffffff;
maxExpArray[ 74] = 0x04d5156639708c9db33c3fffffffffffff;
maxExpArray[ 75] = 0x04a23105873875bd52dfdfffffffffffff;
maxExpArray[ 76] = 0x0471649d87199aa990756fffffffffffff;
maxExpArray[ 77] = 0x04429a21a029d4c1457cfbffffffffffff;
maxExpArray[ 78] = 0x0415bc6d6fb7dd71af2cb3ffffffffffff;
maxExpArray[ 79] = 0x03eab73b3bbfe282243ce1ffffffffffff;
maxExpArray[ 80] = 0x03c1771ac9fb6b4c18e229ffffffffffff;
maxExpArray[ 81] = 0x0399e96897690418f785257fffffffffff;
maxExpArray[ 82] = 0x0373fc456c53bb779bf0ea9fffffffffff;
maxExpArray[ 83] = 0x034f9e8e490c48e67e6ab8bfffffffffff;
maxExpArray[ 84] = 0x032cbfd4a7adc790560b3337ffffffffff;
maxExpArray[ 85] = 0x030b50570f6e5d2acca94613ffffffffff;
maxExpArray[ 86] = 0x02eb40f9f620fda6b56c2861ffffffffff;
maxExpArray[ 87] = 0x02cc8340ecb0d0f520a6af58ffffffffff;
maxExpArray[ 88] = 0x02af09481380a0a35cf1ba02ffffffffff;
maxExpArray[ 89] = 0x0292c5bdd3b92ec810287b1b3fffffffff;
maxExpArray[ 90] = 0x0277abdcdab07d5a77ac6d6b9fffffffff;
maxExpArray[ 91] = 0x025daf6654b1eaa55fd64df5efffffffff;
maxExpArray[ 92] = 0x0244c49c648baa98192dce88b7ffffffff;
maxExpArray[ 93] = 0x022ce03cd5619a311b2471268bffffffff;
maxExpArray[ 94] = 0x0215f77c045fbe885654a44a0fffffffff;
maxExpArray[ 95] = 0x01ffffffffffffffffffffffffffffffff;
maxExpArray[ 96] = 0x01eaefdbdaaee7421fc4d3ede5ffffffff;
maxExpArray[ 97] = 0x01d6bd8b2eb257df7e8ca57b09bfffffff;
maxExpArray[ 98] = 0x01c35fedd14b861eb0443f7f133fffffff;
maxExpArray[ 99] = 0x01b0ce43b322bcde4a56e8ada5afffffff;
maxExpArray[100] = 0x019f0028ec1fff007f5a195a39dfffffff;
maxExpArray[101] = 0x018ded91f0e72ee74f49b15ba527ffffff;
maxExpArray[102] = 0x017d8ec7f04136f4e5615fd41a63ffffff;
maxExpArray[103] = 0x016ddc6556cdb84bdc8d12d22e6fffffff;
maxExpArray[104] = 0x015ecf52776a1155b5bd8395814f7fffff;
maxExpArray[105] = 0x015060c256cb23b3b3cc3754cf40ffffff;
maxExpArray[106] = 0x01428a2f98d728ae223ddab715be3fffff;
maxExpArray[107] = 0x013545598e5c23276ccf0ede68034fffff;
maxExpArray[108] = 0x01288c4161ce1d6f54b7f61081194fffff;
maxExpArray[109] = 0x011c592761c666aa641d5a01a40f17ffff;
maxExpArray[110] = 0x0110a688680a7530515f3e6e6cfdcdffff;
maxExpArray[111] = 0x01056f1b5bedf75c6bcb2ce8aed428ffff;
maxExpArray[112] = 0x00faadceceeff8a0890f3875f008277fff;
maxExpArray[113] = 0x00f05dc6b27edad306388a600f6ba0bfff;
maxExpArray[114] = 0x00e67a5a25da41063de1495d5b18cdbfff;
maxExpArray[115] = 0x00dcff115b14eedde6fc3aa5353f2e4fff;
maxExpArray[116] = 0x00d3e7a3924312399f9aae2e0f868f8fff;
maxExpArray[117] = 0x00cb2ff529eb71e41582cccd5a1ee26fff;
maxExpArray[118] = 0x00c2d415c3db974ab32a51840c0b67edff;
maxExpArray[119] = 0x00bad03e7d883f69ad5b0a186184e06bff;
maxExpArray[120] = 0x00b320d03b2c343d4829abd6075f0cc5ff;
maxExpArray[121] = 0x00abc25204e02828d73c6e80bcdb1a95bf;
maxExpArray[122] = 0x00a4b16f74ee4bb2040a1ec6c15fbbf2df;
maxExpArray[123] = 0x009deaf736ac1f569deb1b5ae3f36c130f;
maxExpArray[124] = 0x00976bd9952c7aa957f5937d790ef65037;
maxExpArray[125] = 0x009131271922eaa6064b73a22d0bd4f2bf;
maxExpArray[126] = 0x008b380f3558668c46c91c49a2f8e967b9;
maxExpArray[127] = 0x00857ddf0117efa215952912839f6473e6;
}
/**
@dev given a token supply, connector balance, weight and a deposit amount (in the connector token),
calculates the return for a given conversion (in the main token)
Formula:
Return = _supply * ((1 + _depositAmount / _connectorBalance) ^ (_connectorWeight / 1000000) - 1)
@param _supply token total supply
@param _connectorBalance total connector balance
@param _connectorWeight connector weight, represented in ppm, 1-1000000
@param _depositAmount deposit amount, in connector token
@return purchase return amount
*/
function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256) {
// validate input
require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT);
// special case for 0 deposit amount
if (_depositAmount == 0)
return 0;
// special case if the weight = 100%
if (_connectorWeight == MAX_WEIGHT)
return _supply.mul(_depositAmount) / _connectorBalance;
uint256 result;
uint8 precision;
uint256 baseN = _depositAmount.add(_connectorBalance);
(result, precision) = power(baseN, _connectorBalance, _connectorWeight, MAX_WEIGHT);
uint256 temp = _supply.mul(result) >> precision;
return temp - _supply;
}
/**
@dev given a token supply, connector balance, weight and a sell amount (in the main token),
calculates the return for a given conversion (in the connector token)
Formula:
Return = _connectorBalance * (1 - (1 - _sellAmount / _supply) ^ (1 / (_connectorWeight / 1000000)))
@param _supply token total supply
@param _connectorBalance total connector
@param _connectorWeight constant connector Weight, represented in ppm, 1-1000000
@param _sellAmount sell amount, in the token itself
@return sale return amount
*/
function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256) {
// validate input
require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT && _sellAmount <= _supply);
// special case for 0 sell amount
if (_sellAmount == 0)
return 0;
// special case for selling the entire supply
if (_sellAmount == _supply)
return _connectorBalance;
// special case if the weight = 100%
if (_connectorWeight == MAX_WEIGHT)
return _connectorBalance.mul(_sellAmount) / _supply;
uint256 result;
uint8 precision;
uint256 baseD = _supply - _sellAmount;
(result, precision) = power(_supply, baseD, MAX_WEIGHT, _connectorWeight);
uint256 temp1 = _connectorBalance.mul(result);
uint256 temp2 = _connectorBalance << precision;
return (temp1 - temp2) / result;
}
/**
@dev given two connector balances/weights and a sell amount (in the first connector token),
calculates the return for a conversion from the first connector token to the second connector token (in the second connector token)
Formula:
Return = _toConnectorBalance * (1 - (_fromConnectorBalance / (_fromConnectorBalance + _amount)) ^ (_fromConnectorWeight / _toConnectorWeight))
@param _fromConnectorBalance input connector balance
@param _fromConnectorWeight input connector weight, represented in ppm, 1-1000000
@param _toConnectorBalance output connector balance
@param _toConnectorWeight output connector weight, represented in ppm, 1-1000000
@param _amount input connector amount
@return second connector amount
*/
function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256) {
// validate input
require(_fromConnectorBalance > 0 && _fromConnectorWeight > 0 && _fromConnectorWeight <= MAX_WEIGHT && _toConnectorBalance > 0 && _toConnectorWeight > 0 && _toConnectorWeight <= MAX_WEIGHT);
// special case for equal weights
if (_fromConnectorWeight == _toConnectorWeight)
return _toConnectorBalance.mul(_amount) / _fromConnectorBalance.add(_amount);
uint256 result;
uint8 precision;
uint256 baseN = _fromConnectorBalance.add(_amount);
(result, precision) = power(baseN, _fromConnectorBalance, _fromConnectorWeight, _toConnectorWeight);
uint256 temp1 = _toConnectorBalance.mul(result);
uint256 temp2 = _toConnectorBalance << precision;
return (temp1 - temp2) / result;
}
/**
General Description:
Determine a value of precision.
Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision.
Return the result along with the precision used.
Detailed Description:
Instead of calculating "base ^ exp", we calculate "e ^ (log(base) * exp)".
The value of "log(base)" is represented with an integer slightly smaller than "log(base) * 2 ^ precision".
The larger "precision" is, the more accurately this value represents the real value.
However, the larger "precision" is, the more bits are required in order to store this value.
And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x").
This maximum exponent depends on the "precision" used, and it is given by "maxExpArray[precision] >> (MAX_PRECISION - precision)".
Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function.
This allows us to compute "base ^ exp" with maximum accuracy and without exceeding 256 bits in any of the intermediate computations.
This functions assumes that "_expN < 2 ^ 256 / log(MAX_NUM - 1)", otherwise the multiplication should be replaced with a "safeMul".
*/
function power(uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD) internal view returns (uint256, uint8) {
require(_baseN < MAX_NUM);
uint256 baseLog;
uint256 base = _baseN * FIXED_1 / _baseD;
if (base < OPT_LOG_MAX_VAL) {
baseLog = optimalLog(base);
}
else {
baseLog = generalLog(base);
}
uint256 baseLogTimesExp = baseLog * _expN / _expD;
if (baseLogTimesExp < OPT_EXP_MAX_VAL) {
return (optimalExp(baseLogTimesExp), MAX_PRECISION);
}
else {
uint8 precision = findPositionInMaxExpArray(baseLogTimesExp);
return (generalExp(baseLogTimesExp >> (MAX_PRECISION - precision), precision), precision);
}
}
/**
Compute log(x / FIXED_1) * FIXED_1.
This functions assumes that "x >= FIXED_1", because the output would be negative otherwise.
*/
function generalLog(uint256 x) internal pure returns (uint256) {
uint256 res = 0;
// If x >= 2, then we compute the integer part of log2(x), which is larger than 0.
if (x >= FIXED_2) {
uint8 count = floorLog2(x / FIXED_1);
x >>= count; // now x < 2
res = count * FIXED_1;
}
// If x > 1, then we compute the fraction part of log2(x), which is larger than 0.
if (x > FIXED_1) {
for (uint8 i = MAX_PRECISION; i > 0; --i) {
x = (x * x) / FIXED_1; // now 1 < x < 4
if (x >= FIXED_2) {
x >>= 1; // now 1 < x < 2
res += ONE << (i - 1);
}
}
}
return res * LN2_NUMERATOR / LN2_DENOMINATOR;
}
/**
Compute the largest integer smaller than or equal to the binary logarithm of the input.
*/
function floorLog2(uint256 _n) internal pure returns (uint8) {
uint8 res = 0;
if (_n < 256) {
// At most 8 iterations
while (_n > 1) {
_n >>= 1;
res += 1;
}
}
else {
// Exactly 8 iterations
for (uint8 s = 128; s > 0; s >>= 1) {
if (_n >= (ONE << s)) {
_n >>= s;
res |= s;
}
}
}
return res;
}
/**
The global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent:
- This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"]
- This function finds the highest position of [a value in "maxExpArray" larger than or equal to "x"]
*/
function findPositionInMaxExpArray(uint256 _x) internal view returns (uint8) {
uint8 lo = MIN_PRECISION;
uint8 hi = MAX_PRECISION;
while (lo + 1 < hi) {
uint8 mid = (lo + hi) / 2;
if (maxExpArray[mid] >= _x)
lo = mid;
else
hi = mid;
}
if (maxExpArray[hi] >= _x)
return hi;
if (maxExpArray[lo] >= _x)
return lo;
require(false);
return 0;
}
/**
This function can be auto-generated by the script 'PrintFunctionGeneralExp.py'.
It approximates "e ^ x" via maclaurin summation: "(x^0)/0! + (x^1)/1! + ... + (x^n)/n!".
It returns "e ^ (x / 2 ^ precision) * 2 ^ precision", that is, the result is upshifted for accuracy.
The global "maxExpArray" maps each "precision" to "((maximumExponent + 1) << (MAX_PRECISION - precision)) - 1".
The maximum permitted value for "x" is therefore given by "maxExpArray[precision] >> (MAX_PRECISION - precision)".
*/
function generalExp(uint256 _x, uint8 _precision) internal pure returns (uint256) {
uint256 xi = _x;
uint256 res = 0;
xi = (xi * _x) >> _precision; res += xi * 0x3442c4e6074a82f1797f72ac0000000; // add x^02 * (33! / 02!)
xi = (xi * _x) >> _precision; res += xi * 0x116b96f757c380fb287fd0e40000000; // add x^03 * (33! / 03!)
xi = (xi * _x) >> _precision; res += xi * 0x045ae5bdd5f0e03eca1ff4390000000; // add x^04 * (33! / 04!)
xi = (xi * _x) >> _precision; res += xi * 0x00defabf91302cd95b9ffda50000000; // add x^05 * (33! / 05!)
xi = (xi * _x) >> _precision; res += xi * 0x002529ca9832b22439efff9b8000000; // add x^06 * (33! / 06!)
xi = (xi * _x) >> _precision; res += xi * 0x00054f1cf12bd04e516b6da88000000; // add x^07 * (33! / 07!)
xi = (xi * _x) >> _precision; res += xi * 0x0000a9e39e257a09ca2d6db51000000; // add x^08 * (33! / 08!)
xi = (xi * _x) >> _precision; res += xi * 0x000012e066e7b839fa050c309000000; // add x^09 * (33! / 09!)
xi = (xi * _x) >> _precision; res += xi * 0x000001e33d7d926c329a1ad1a800000; // add x^10 * (33! / 10!)
xi = (xi * _x) >> _precision; res += xi * 0x0000002bee513bdb4a6b19b5f800000; // add x^11 * (33! / 11!)
xi = (xi * _x) >> _precision; res += xi * 0x00000003a9316fa79b88eccf2a00000; // add x^12 * (33! / 12!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000048177ebe1fa812375200000; // add x^13 * (33! / 13!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000005263fe90242dcbacf00000; // add x^14 * (33! / 14!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000057e22099c030d94100000; // add x^15 * (33! / 15!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000057e22099c030d9410000; // add x^16 * (33! / 16!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000052b6b54569976310000; // add x^17 * (33! / 17!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000004985f67696bf748000; // add x^18 * (33! / 18!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000000003dea12ea99e498000; // add x^19 * (33! / 19!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000031880f2214b6e000; // add x^20 * (33! / 20!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000000000025bcff56eb36000; // add x^21 * (33! / 21!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000000000001b722e10ab1000; // add x^22 * (33! / 22!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000001317c70077000; // add x^23 * (33! / 23!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000cba84aafa00; // add x^24 * (33! / 24!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000082573a0a00; // add x^25 * (33! / 25!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000005035ad900; // add x^26 * (33! / 26!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000000000000000002f881b00; // add x^27 * (33! / 27!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000001b29340; // add x^28 * (33! / 28!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000000000efc40; // add x^29 * (33! / 29!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000007fe0; // add x^30 * (33! / 30!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000420; // add x^31 * (33! / 31!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000021; // add x^32 * (33! / 32!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000001; // add x^33 * (33! / 33!)
return res / 0x688589cc0e9505e2f2fee5580000000 + _x + (ONE << _precision); // divide by 33! and then add x^1 / 1! + x^0 / 0!
}
/**
Return log(x / FIXED_1) * FIXED_1
Input range: FIXED_1 <= x <= LOG_EXP_MAX_VAL - 1
Auto-generated via 'PrintFunctionOptimalLog.py'
Detailed description:
- Rewrite the input as a product of natural exponents and a single residual r, such that 1 < r < 2
- The natural logarithm of each (pre-calculated) exponent is the degree of the exponent
- The natural logarithm of r is calculated via Taylor series for log(1 + x), where x = r - 1
- The natural logarithm of the input is calculated by summing up the intermediate results above
- For example: log(250) = log(e^4 * e^1 * e^0.5 * 1.021692859) = 4 + 1 + 0.5 + log(1 + 0.021692859)
*/
function optimalLog(uint256 x) internal pure returns (uint256) {
uint256 res = 0;
uint256 y;
uint256 z;
uint256 w;
if (x >= 0xd3094c70f034de4b96ff7d5b6f99fcd8) {res += 0x40000000000000000000000000000000; x = x * FIXED_1 / 0xd3094c70f034de4b96ff7d5b6f99fcd8;} // add 1 / 2^1
if (x >= 0xa45af1e1f40c333b3de1db4dd55f29a7) {res += 0x20000000000000000000000000000000; x = x * FIXED_1 / 0xa45af1e1f40c333b3de1db4dd55f29a7;} // add 1 / 2^2
if (x >= 0x910b022db7ae67ce76b441c27035c6a1) {res += 0x10000000000000000000000000000000; x = x * FIXED_1 / 0x910b022db7ae67ce76b441c27035c6a1;} // add 1 / 2^3
if (x >= 0x88415abbe9a76bead8d00cf112e4d4a8) {res += 0x08000000000000000000000000000000; x = x * FIXED_1 / 0x88415abbe9a76bead8d00cf112e4d4a8;} // add 1 / 2^4
if (x >= 0x84102b00893f64c705e841d5d4064bd3) {res += 0x04000000000000000000000000000000; x = x * FIXED_1 / 0x84102b00893f64c705e841d5d4064bd3;} // add 1 / 2^5
if (x >= 0x8204055aaef1c8bd5c3259f4822735a2) {res += 0x02000000000000000000000000000000; x = x * FIXED_1 / 0x8204055aaef1c8bd5c3259f4822735a2;} // add 1 / 2^6
if (x >= 0x810100ab00222d861931c15e39b44e99) {res += 0x01000000000000000000000000000000; x = x * FIXED_1 / 0x810100ab00222d861931c15e39b44e99;} // add 1 / 2^7
if (x >= 0x808040155aabbbe9451521693554f733) {res += 0x00800000000000000000000000000000; x = x * FIXED_1 / 0x808040155aabbbe9451521693554f733;} // add 1 / 2^8
z = y = x - FIXED_1;
w = y * y / FIXED_1;
res += z * (0x100000000000000000000000000000000 - y) / 0x100000000000000000000000000000000; z = z * w / FIXED_1; // add y^01 / 01 - y^02 / 02
res += z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y) / 0x200000000000000000000000000000000; z = z * w / FIXED_1; // add y^03 / 03 - y^04 / 04
res += z * (0x099999999999999999999999999999999 - y) / 0x300000000000000000000000000000000; z = z * w / FIXED_1; // add y^05 / 05 - y^06 / 06
res += z * (0x092492492492492492492492492492492 - y) / 0x400000000000000000000000000000000; z = z * w / FIXED_1; // add y^07 / 07 - y^08 / 08
res += z * (0x08e38e38e38e38e38e38e38e38e38e38e - y) / 0x500000000000000000000000000000000; z = z * w / FIXED_1; // add y^09 / 09 - y^10 / 10
res += z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y) / 0x600000000000000000000000000000000; z = z * w / FIXED_1; // add y^11 / 11 - y^12 / 12
res += z * (0x089d89d89d89d89d89d89d89d89d89d89 - y) / 0x700000000000000000000000000000000; z = z * w / FIXED_1; // add y^13 / 13 - y^14 / 14
res += z * (0x088888888888888888888888888888888 - y) / 0x800000000000000000000000000000000; // add y^15 / 15 - y^16 / 16
return res;
}
/**
Return e ^ (x / FIXED_1) * FIXED_1
Input range: 0 <= x <= OPT_EXP_MAX_VAL - 1
Auto-generated via 'PrintFunctionOptimalExp.py'
Detailed description:
- Rewrite the input as a sum of binary exponents and a single residual r, as small as possible
- The exponentiation of each binary exponent is given (pre-calculated)
- The exponentiation of r is calculated via Taylor series for e^x, where x = r
- The exponentiation of the input is calculated by multiplying the intermediate results above
- For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859
*/
function optimalExp(uint256 x) internal pure returns (uint256) {
uint256 res = 0;
uint256 y;
uint256 z;
z = y = x % 0x10000000000000000000000000000000; // get the input modulo 2^(-3)
z = z * y / FIXED_1; res += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!)
z = z * y / FIXED_1; res += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!)
z = z * y / FIXED_1; res += z * 0x0168244fdac78000; // add y^04 * (20! / 04!)
z = z * y / FIXED_1; res += z * 0x004807432bc18000; // add y^05 * (20! / 05!)
z = z * y / FIXED_1; res += z * 0x000c0135dca04000; // add y^06 * (20! / 06!)
z = z * y / FIXED_1; res += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!)
z = z * y / FIXED_1; res += z * 0x000036e0f639b800; // add y^08 * (20! / 08!)
z = z * y / FIXED_1; res += z * 0x00000618fee9f800; // add y^09 * (20! / 09!)
z = z * y / FIXED_1; res += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!)
z = z * y / FIXED_1; res += z * 0x0000000e30dce400; // add y^11 * (20! / 11!)
z = z * y / FIXED_1; res += z * 0x000000012ebd1300; // add y^12 * (20! / 12!)
z = z * y / FIXED_1; res += z * 0x0000000017499f00; // add y^13 * (20! / 13!)
z = z * y / FIXED_1; res += z * 0x0000000001a9d480; // add y^14 * (20! / 14!)
z = z * y / FIXED_1; res += z * 0x00000000001c6380; // add y^15 * (20! / 15!)
z = z * y / FIXED_1; res += z * 0x000000000001c638; // add y^16 * (20! / 16!)
z = z * y / FIXED_1; res += z * 0x0000000000001ab8; // add y^17 * (20! / 17!)
z = z * y / FIXED_1; res += z * 0x000000000000017c; // add y^18 * (20! / 18!)
z = z * y / FIXED_1; res += z * 0x0000000000000014; // add y^19 * (20! / 19!)
z = z * y / FIXED_1; res += z * 0x0000000000000001; // add y^20 * (20! / 20!)
res = res / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0!
if ((x & 0x010000000000000000000000000000000) != 0) res = res * 0x1c3d6a24ed82218787d624d3e5eba95f9 / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3)
if ((x & 0x020000000000000000000000000000000) != 0) res = res * 0x18ebef9eac820ae8682b9793ac6d1e778 / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2)
if ((x & 0x040000000000000000000000000000000) != 0) res = res * 0x1368b2fc6f9609fe7aceb46aa619baed5 / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1)
if ((x & 0x080000000000000000000000000000000) != 0) res = res * 0x0bc5ab1b16779be3575bd8f0520a9f21e / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0)
if ((x & 0x100000000000000000000000000000000) != 0) res = res * 0x0454aaa8efe072e7f6ddbab84b40a55c5 / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1)
if ((x & 0x200000000000000000000000000000000) != 0) res = res * 0x00960aadc109e7a3bf4578099615711d7 / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2)
if ((x & 0x400000000000000000000000000000000) != 0) res = res * 0x0002bf84208204f5977f9a8cf01fdc307 / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3)
return res;
}
}
// File: @ablack/fundraising-shared-interfaces/contracts/IAragonFundraisingController.sol
pragma solidity 0.4.24;
contract IAragonFundraisingController {
function openTrading() external;
function updateTappedAmount(address _token) external;
function collateralsToBeClaimed(address _collateral) public view returns (uint256);
function balanceOf(address _who, address _token) public view returns (uint256);
}
// File: @ablack/fundraising-batched-bancor-market-maker/contracts/BatchedBancorMarketMaker.sol
pragma solidity 0.4.24;
contract BatchedBancorMarketMaker is EtherTokenConstant, IsContract, AragonApp {
using SafeERC20 for ERC20;
using SafeMath for uint256;
/**
Hardcoded constants to save gas
bytes32 public constant OPEN_ROLE = keccak256("OPEN_ROLE");
bytes32 public constant UPDATE_FORMULA_ROLE = keccak256("UPDATE_FORMULA_ROLE");
bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE");
bytes32 public constant UPDATE_FEES_ROLE = keccak256("UPDATE_FEES_ROLE");
bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = keccak256("ADD_COLLATERAL_TOKEN_ROLE");
bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = keccak256("REMOVE_COLLATERAL_TOKEN_ROLE");
bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = keccak256("UPDATE_COLLATERAL_TOKEN_ROLE");
bytes32 public constant OPEN_BUY_ORDER_ROLE = keccak256("OPEN_BUY_ORDER_ROLE");
bytes32 public constant OPEN_SELL_ORDER_ROLE = keccak256("OPEN_SELL_ORDER_ROLE");
*/
bytes32 public constant OPEN_ROLE = 0xefa06053e2ca99a43c97c4a4f3d8a394ee3323a8ff237e625fba09fe30ceb0a4;
bytes32 public constant UPDATE_FORMULA_ROLE = 0xbfb76d8d43f55efe58544ea32af187792a7bdb983850d8fed33478266eec3cbb;
bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593;
bytes32 public constant UPDATE_FEES_ROLE = 0x5f9be2932ed3a723f295a763be1804c7ebfd1a41c1348fb8bdf5be1c5cdca822;
bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = 0x217b79cb2bc7760defc88529853ef81ab33ae5bb315408ce9f5af09c8776662d;
bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = 0x2044e56de223845e4be7d0a6f4e9a29b635547f16413a6d1327c58d9db438ee2;
bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = 0xe0565c2c43e0d841e206bb36a37f12f22584b4652ccee6f9e0c071b697a2e13d;
bytes32 public constant OPEN_BUY_ORDER_ROLE = 0xa589c8f284b76fc8d510d9d553485c47dbef1b0745ae00e0f3fd4e28fcd77ea7;
bytes32 public constant OPEN_SELL_ORDER_ROLE = 0xd68ba2b769fa37a2a7bd4bed9241b448bc99eca41f519ef037406386a8f291c0;
uint256 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10 ** 16; 100% = 10 ** 18
uint32 public constant PPM = 1000000;
string private constant ERROR_CONTRACT_IS_EOA = "MM_CONTRACT_IS_EOA";
string private constant ERROR_INVALID_BENEFICIARY = "MM_INVALID_BENEFICIARY";
string private constant ERROR_INVALID_BATCH_BLOCKS = "MM_INVALID_BATCH_BLOCKS";
string private constant ERROR_INVALID_PERCENTAGE = "MM_INVALID_PERCENTAGE";
string private constant ERROR_INVALID_RESERVE_RATIO = "MM_INVALID_RESERVE_RATIO";
string private constant ERROR_INVALID_TM_SETTING = "MM_INVALID_TM_SETTING";
string private constant ERROR_INVALID_COLLATERAL = "MM_INVALID_COLLATERAL";
string private constant ERROR_INVALID_COLLATERAL_VALUE = "MM_INVALID_COLLATERAL_VALUE";
string private constant ERROR_INVALID_BOND_AMOUNT = "MM_INVALID_BOND_AMOUNT";
string private constant ERROR_ALREADY_OPEN = "MM_ALREADY_OPEN";
string private constant ERROR_NOT_OPEN = "MM_NOT_OPEN";
string private constant ERROR_COLLATERAL_ALREADY_WHITELISTED = "MM_COLLATERAL_ALREADY_WHITELISTED";
string private constant ERROR_COLLATERAL_NOT_WHITELISTED = "MM_COLLATERAL_NOT_WHITELISTED";
string private constant ERROR_NOTHING_TO_CLAIM = "MM_NOTHING_TO_CLAIM";
string private constant ERROR_BATCH_NOT_OVER = "MM_BATCH_NOT_OVER";
string private constant ERROR_BATCH_CANCELLED = "MM_BATCH_CANCELLED";
string private constant ERROR_BATCH_NOT_CANCELLED = "MM_BATCH_NOT_CANCELLED";
string private constant ERROR_SLIPPAGE_EXCEEDS_LIMIT = "MM_SLIPPAGE_EXCEEDS_LIMIT";
string private constant ERROR_INSUFFICIENT_POOL_BALANCE = "MM_INSUFFICIENT_POOL_BALANCE";
string private constant ERROR_TRANSFER_FROM_FAILED = "MM_TRANSFER_FROM_FAILED";
struct Collateral {
bool whitelisted;
uint256 virtualSupply;
uint256 virtualBalance;
uint32 reserveRatio;
uint256 slippage;
}
struct MetaBatch {
bool initialized;
uint256 realSupply;
uint256 buyFeePct;
uint256 sellFeePct;
IBancorFormula formula;
mapping(address => Batch) batches;
}
struct Batch {
bool initialized;
bool cancelled;
uint256 supply;
uint256 balance;
uint32 reserveRatio;
uint256 slippage;
uint256 totalBuySpend;
uint256 totalBuyReturn;
uint256 totalSellSpend;
uint256 totalSellReturn;
mapping(address => uint256) buyers;
mapping(address => uint256) sellers;
}
IAragonFundraisingController public controller;
TokenManager public tokenManager;
ERC20 public token;
Vault public reserve;
address public beneficiary;
IBancorFormula public formula;
uint256 public batchBlocks;
uint256 public buyFeePct;
uint256 public sellFeePct;
bool public isOpen;
uint256 public tokensToBeMinted;
mapping(address => uint256) public collateralsToBeClaimed;
mapping(address => Collateral) public collaterals;
mapping(uint256 => MetaBatch) public metaBatches;
event UpdateBeneficiary (address indexed beneficiary);
event UpdateFormula (address indexed formula);
event UpdateFees (uint256 buyFeePct, uint256 sellFeePct);
event NewMetaBatch (uint256 indexed id, uint256 supply, uint256 buyFeePct, uint256 sellFeePct, address formula);
event NewBatch (
uint256 indexed id,
address indexed collateral,
uint256 supply,
uint256 balance,
uint32 reserveRatio,
uint256 slippage)
;
event CancelBatch (uint256 indexed id, address indexed collateral);
event AddCollateralToken (
address indexed collateral,
uint256 virtualSupply,
uint256 virtualBalance,
uint32 reserveRatio,
uint256 slippage
);
event RemoveCollateralToken (address indexed collateral);
event UpdateCollateralToken (
address indexed collateral,
uint256 virtualSupply,
uint256 virtualBalance,
uint32 reserveRatio,
uint256 slippage
);
event Open ();
event OpenBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 fee, uint256 value);
event OpenSellOrder (address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 amount);
event ClaimBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 amount);
event ClaimSellOrder (address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 fee, uint256 value);
event ClaimCancelledBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 value);
event ClaimCancelledSellOrder(address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 amount);
event UpdatePricing (
uint256 indexed batchId,
address indexed collateral,
uint256 totalBuySpend,
uint256 totalBuyReturn,
uint256 totalSellSpend,
uint256 totalSellReturn
);
/***** external function *****/
/**
* @notice Initialize market maker
* @param _controller The address of the controller contract
* @param _tokenManager The address of the [bonded token] token manager contract
* @param _reserve The address of the reserve [pool] contract
* @param _beneficiary The address of the beneficiary [to whom fees are to be sent]
* @param _formula The address of the BancorFormula [computation] contract
* @param _batchBlocks The number of blocks batches are to last
* @param _buyFeePct The fee to be deducted from buy orders [in PCT_BASE]
* @param _sellFeePct The fee to be deducted from sell orders [in PCT_BASE]
*/
function initialize(
IAragonFundraisingController _controller,
TokenManager _tokenManager,
IBancorFormula _formula,
Vault _reserve,
address _beneficiary,
uint256 _batchBlocks,
uint256 _buyFeePct,
uint256 _sellFeePct
)
external
onlyInit
{
initialized();
require(isContract(_controller), ERROR_CONTRACT_IS_EOA);
require(isContract(_tokenManager), ERROR_CONTRACT_IS_EOA);
require(isContract(_formula), ERROR_CONTRACT_IS_EOA);
require(isContract(_reserve), ERROR_CONTRACT_IS_EOA);
require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY);
require(_batchBlocks > 0, ERROR_INVALID_BATCH_BLOCKS);
require(_feeIsValid(_buyFeePct) && _feeIsValid(_sellFeePct), ERROR_INVALID_PERCENTAGE);
require(_tokenManagerSettingIsValid(_tokenManager), ERROR_INVALID_TM_SETTING);
controller = _controller;
tokenManager = _tokenManager;
token = ERC20(tokenManager.token());
formula = _formula;
reserve = _reserve;
beneficiary = _beneficiary;
batchBlocks = _batchBlocks;
buyFeePct = _buyFeePct;
sellFeePct = _sellFeePct;
}
/* generic settings related function */
/**
* @notice Open market making [enabling users to open buy and sell orders]
*/
function open() external auth(OPEN_ROLE) {
require(!isOpen, ERROR_ALREADY_OPEN);
_open();
}
/**
* @notice Update formula to `_formula`
* @param _formula The address of the new BancorFormula [computation] contract
*/
function updateFormula(IBancorFormula _formula) external auth(UPDATE_FORMULA_ROLE) {
require(isContract(_formula), ERROR_CONTRACT_IS_EOA);
_updateFormula(_formula);
}
/**
* @notice Update beneficiary to `_beneficiary`
* @param _beneficiary The address of the new beneficiary [to whom fees are to be sent]
*/
function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) {
require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY);
_updateBeneficiary(_beneficiary);
}
/**
* @notice Update fees deducted from buy and sell orders to respectively `@formatPct(_buyFeePct)`% and `@formatPct(_sellFeePct)`%
* @param _buyFeePct The new fee to be deducted from buy orders [in PCT_BASE]
* @param _sellFeePct The new fee to be deducted from sell orders [in PCT_BASE]
*/
function updateFees(uint256 _buyFeePct, uint256 _sellFeePct) external auth(UPDATE_FEES_ROLE) {
require(_feeIsValid(_buyFeePct) && _feeIsValid(_sellFeePct), ERROR_INVALID_PERCENTAGE);
_updateFees(_buyFeePct, _sellFeePct);
}
/* collateral tokens related functions */
/**
* @notice Add `_collateral.symbol(): string` as a whitelisted collateral token
* @param _collateral The address of the collateral token to be whitelisted
* @param _virtualSupply The virtual supply to be used for that collateral token [in wei]
* @param _virtualBalance The virtual balance to be used for that collateral token [in wei]
* @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM]
* @param _slippage The price slippage below which each batch is to be kept for that collateral token [in PCT_BASE]
*/
function addCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage)
external
auth(ADD_COLLATERAL_TOKEN_ROLE)
{
require(isContract(_collateral) || _collateral == ETH, ERROR_INVALID_COLLATERAL);
require(!_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_ALREADY_WHITELISTED);
require(_reserveRatioIsValid(_reserveRatio), ERROR_INVALID_RESERVE_RATIO);
_addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage);
}
/**
* @notice Remove `_collateral.symbol(): string` as a whitelisted collateral token
* @param _collateral The address of the collateral token to be un-whitelisted
*/
function removeCollateralToken(address _collateral) external auth(REMOVE_COLLATERAL_TOKEN_ROLE) {
require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED);
_removeCollateralToken(_collateral);
}
/**
* @notice Update `_collateral.symbol(): string` collateralization settings
* @param _collateral The address of the collateral token whose collateralization settings are to be updated
* @param _virtualSupply The new virtual supply to be used for that collateral token [in wei]
* @param _virtualBalance The new virtual balance to be used for that collateral token [in wei]
* @param _reserveRatio The new reserve ratio to be used for that collateral token [in PPM]
* @param _slippage The new price slippage below which each batch is to be kept for that collateral token [in PCT_BASE]
*/
function updateCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage)
external
auth(UPDATE_COLLATERAL_TOKEN_ROLE)
{
require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED);
require(_reserveRatioIsValid(_reserveRatio), ERROR_INVALID_RESERVE_RATIO);
_updateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage);
}
/* market making related functions */
/**
* @notice Open a buy order worth `@tokenAmount(_collateral, _value)`
* @param _buyer The address of the buyer
* @param _collateral The address of the collateral token to be spent
* @param _value The amount of collateral token to be spent
*/
function openBuyOrder(address _buyer, address _collateral, uint256 _value) external payable auth(OPEN_BUY_ORDER_ROLE) {
require(isOpen, ERROR_NOT_OPEN);
require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED);
require(!_batchIsCancelled(_currentBatchId(), _collateral), ERROR_BATCH_CANCELLED);
require(_collateralValueIsValid(_buyer, _collateral, _value, msg.value), ERROR_INVALID_COLLATERAL_VALUE);
_openBuyOrder(_buyer, _collateral, _value);
}
/**
* @notice Open a sell order worth `@tokenAmount(self.token(): address, _amount)` against `_collateral.symbol(): string`
* @param _seller The address of the seller
* @param _collateral The address of the collateral token to be returned
* @param _amount The amount of bonded token to be spent
*/
function openSellOrder(address _seller, address _collateral, uint256 _amount) external auth(OPEN_SELL_ORDER_ROLE) {
require(isOpen, ERROR_NOT_OPEN);
require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED);
require(!_batchIsCancelled(_currentBatchId(), _collateral), ERROR_BATCH_CANCELLED);
require(_bondAmountIsValid(_seller, _amount), ERROR_INVALID_BOND_AMOUNT);
_openSellOrder(_seller, _collateral, _amount);
}
/**
* @notice Claim the results of `_buyer`'s `_collateral.symbol(): string` buy orders from batch #`_batchId`
* @param _buyer The address of the user whose buy orders are to be claimed
* @param _batchId The id of the batch in which buy orders are to be claimed
* @param _collateral The address of the collateral token against which buy orders are to be claimed
*/
function claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) external nonReentrant isInitialized {
require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED);
require(_batchIsOver(_batchId), ERROR_BATCH_NOT_OVER);
require(!_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_CANCELLED);
require(_userIsBuyer(_batchId, _collateral, _buyer), ERROR_NOTHING_TO_CLAIM);
_claimBuyOrder(_buyer, _batchId, _collateral);
}
/**
* @notice Claim the results of `_seller`'s `_collateral.symbol(): string` sell orders from batch #`_batchId`
* @param _seller The address of the user whose sell orders are to be claimed
* @param _batchId The id of the batch in which sell orders are to be claimed
* @param _collateral The address of the collateral token against which sell orders are to be claimed
*/
function claimSellOrder(address _seller, uint256 _batchId, address _collateral) external nonReentrant isInitialized {
require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED);
require(_batchIsOver(_batchId), ERROR_BATCH_NOT_OVER);
require(!_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_CANCELLED);
require(_userIsSeller(_batchId, _collateral, _seller), ERROR_NOTHING_TO_CLAIM);
_claimSellOrder(_seller, _batchId, _collateral);
}
/**
* @notice Claim the investments of `_buyer`'s `_collateral.symbol(): string` buy orders from cancelled batch #`_batchId`
* @param _buyer The address of the user whose cancelled buy orders are to be claimed
* @param _batchId The id of the batch in which cancelled buy orders are to be claimed
* @param _collateral The address of the collateral token against which cancelled buy orders are to be claimed
*/
function claimCancelledBuyOrder(address _buyer, uint256 _batchId, address _collateral) external nonReentrant isInitialized {
require(_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_NOT_CANCELLED);
require(_userIsBuyer(_batchId, _collateral, _buyer), ERROR_NOTHING_TO_CLAIM);
_claimCancelledBuyOrder(_buyer, _batchId, _collateral);
}
/**
* @notice Claim the investments of `_seller`'s `_collateral.symbol(): string` sell orders from cancelled batch #`_batchId`
* @param _seller The address of the user whose cancelled sell orders are to be claimed
* @param _batchId The id of the batch in which cancelled sell orders are to be claimed
* @param _collateral The address of the collateral token against which cancelled sell orders are to be claimed
*/
function claimCancelledSellOrder(address _seller, uint256 _batchId, address _collateral) external nonReentrant isInitialized {
require(_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_NOT_CANCELLED);
require(_userIsSeller(_batchId, _collateral, _seller), ERROR_NOTHING_TO_CLAIM);
_claimCancelledSellOrder(_seller, _batchId, _collateral);
}
/***** public view functions *****/
function getCurrentBatchId() public view isInitialized returns (uint256) {
return _currentBatchId();
}
function getCollateralToken(address _collateral) public view isInitialized returns (bool, uint256, uint256, uint32, uint256) {
Collateral storage collateral = collaterals[_collateral];
return (collateral.whitelisted, collateral.virtualSupply, collateral.virtualBalance, collateral.reserveRatio, collateral.slippage);
}
function getBatch(uint256 _batchId, address _collateral)
public view isInitialized
returns (bool, bool, uint256, uint256, uint32, uint256, uint256, uint256, uint256, uint256)
{
Batch storage batch = metaBatches[_batchId].batches[_collateral];
return (
batch.initialized,
batch.cancelled,
batch.supply,
batch.balance,
batch.reserveRatio,
batch.slippage,
batch.totalBuySpend,
batch.totalBuyReturn,
batch.totalSellSpend,
batch.totalSellReturn
);
}
function getStaticPricePPM(uint256 _supply, uint256 _balance, uint32 _reserveRatio) public view isInitialized returns (uint256) {
return _staticPricePPM(_supply, _balance, _reserveRatio);
}
/***** internal functions *****/
/* computation functions */
function _staticPricePPM(uint256 _supply, uint256 _balance, uint32 _reserveRatio) internal pure returns (uint256) {
return uint256(PPM).mul(uint256(PPM)).mul(_balance).div(_supply.mul(uint256(_reserveRatio)));
}
function _currentBatchId() internal view returns (uint256) {
return (block.number.div(batchBlocks)).mul(batchBlocks);
}
/* check functions */
function _beneficiaryIsValid(address _beneficiary) internal pure returns (bool) {
return _beneficiary != address(0);
}
function _feeIsValid(uint256 _fee) internal pure returns (bool) {
return _fee < PCT_BASE;
}
function _reserveRatioIsValid(uint32 _reserveRatio) internal pure returns (bool) {
return _reserveRatio <= PPM;
}
function _tokenManagerSettingIsValid(TokenManager _tokenManager) internal view returns (bool) {
return _tokenManager.maxAccountTokens() == uint256(-1);
}
function _collateralValueIsValid(address _buyer, address _collateral, uint256 _value, uint256 _msgValue) internal view returns (bool) {
if (_value == 0) {
return false;
}
if (_collateral == ETH) {
return _msgValue == _value;
}
return (
_msgValue == 0 &&
controller.balanceOf(_buyer, _collateral) >= _value &&
ERC20(_collateral).allowance(_buyer, address(this)) >= _value
);
}
function _bondAmountIsValid(address _seller, uint256 _amount) internal view returns (bool) {
return _amount != 0 && tokenManager.spendableBalanceOf(_seller) >= _amount;
}
function _collateralIsWhitelisted(address _collateral) internal view returns (bool) {
return collaterals[_collateral].whitelisted;
}
function _batchIsOver(uint256 _batchId) internal view returns (bool) {
return _batchId < _currentBatchId();
}
function _batchIsCancelled(uint256 _batchId, address _collateral) internal view returns (bool) {
return metaBatches[_batchId].batches[_collateral].cancelled;
}
function _userIsBuyer(uint256 _batchId, address _collateral, address _user) internal view returns (bool) {
Batch storage batch = metaBatches[_batchId].batches[_collateral];
return batch.buyers[_user] > 0;
}
function _userIsSeller(uint256 _batchId, address _collateral, address _user) internal view returns (bool) {
Batch storage batch = metaBatches[_batchId].batches[_collateral];
return batch.sellers[_user] > 0;
}
function _poolBalanceIsSufficient(address _collateral) internal view returns (bool) {
return controller.balanceOf(address(reserve), _collateral) >= collateralsToBeClaimed[_collateral];
}
function _slippageIsValid(Batch storage _batch, address _collateral) internal view returns (bool) {
uint256 staticPricePPM = _staticPricePPM(_batch.supply, _batch.balance, _batch.reserveRatio);
uint256 maximumSlippage = _batch.slippage;
// if static price is zero let's consider that every slippage is valid
if (staticPricePPM == 0) {
return true;
}
return _buySlippageIsValid(_batch, staticPricePPM, maximumSlippage) && _sellSlippageIsValid(_batch, staticPricePPM, maximumSlippage);
}
function _buySlippageIsValid(Batch storage _batch, uint256 _startingPricePPM, uint256 _maximumSlippage) internal view returns (bool) {
/**
* NOTE
* the case where starting price is zero is handled
* in the meta function _slippageIsValid()
*/
/**
* NOTE
* slippage is valid if:
* totalBuyReturn >= totalBuySpend / (startingPrice * (1 + maxSlippage))
* totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (1 + maximumSlippage / PCT_BASE))
* totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (1 + maximumSlippage / PCT_BASE))
* totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (PCT + maximumSlippage) / PCT_BASE)
* totalBuyReturn * startingPrice * ( PCT + maximumSlippage) >= totalBuySpend * PCT_BASE * PPM
*/
if (
_batch.totalBuyReturn.mul(_startingPricePPM).mul(PCT_BASE.add(_maximumSlippage)) >=
_batch.totalBuySpend.mul(PCT_BASE).mul(uint256(PPM))
) {
return true;
}
return false;
}
function _sellSlippageIsValid(Batch storage _batch, uint256 _startingPricePPM, uint256 _maximumSlippage) internal view returns (bool) {
/**
* NOTE
* the case where starting price is zero is handled
* in the meta function _slippageIsValid()
*/
// if allowed sell slippage >= 100%
// then any sell slippage is valid
if (_maximumSlippage >= PCT_BASE) {
return true;
}
/**
* NOTE
* slippage is valid if
* totalSellReturn >= startingPrice * (1 - maxSlippage) * totalBuySpend
* totalSellReturn >= (startingPricePPM / PPM) * (1 - maximumSlippage / PCT_BASE) * totalBuySpend
* totalSellReturn >= (startingPricePPM / PPM) * (PCT_BASE - maximumSlippage) * totalBuySpend / PCT_BASE
* totalSellReturn * PCT_BASE * PPM = startingPricePPM * (PCT_BASE - maximumSlippage) * totalBuySpend
*/
if (
_batch.totalSellReturn.mul(PCT_BASE).mul(uint256(PPM)) >=
_startingPricePPM.mul(PCT_BASE.sub(_maximumSlippage)).mul(_batch.totalSellSpend)
) {
return true;
}
return false;
}
/* initialization functions */
function _currentBatch(address _collateral) internal returns (uint256, Batch storage) {
uint256 batchId = _currentBatchId();
MetaBatch storage metaBatch = metaBatches[batchId];
Batch storage batch = metaBatch.batches[_collateral];
if (!metaBatch.initialized) {
/**
* NOTE
* all collateral batches should be initialized with the same supply to
* avoid price manipulation between different collaterals in the same meta-batch
* we don't need to do the same with collateral balances as orders against one collateral
* can't affect the pool's balance against another collateral and tap is a step-function
* of the meta-batch duration
*/
/**
* NOTE
* realSupply(metaBatch) = totalSupply(metaBatchInitialization) + tokensToBeMinted(metaBatchInitialization)
* 1. buy and sell orders incoming during the current meta-batch and affecting totalSupply or tokensToBeMinted
* should not be taken into account in the price computation [they are already a part of the batched pricing computation]
* 2. the only way for totalSupply to be modified during a meta-batch [outside of incoming buy and sell orders]
* is for buy orders from previous meta-batches to be claimed [and tokens to be minted]:
* as such totalSupply(metaBatch) + tokenToBeMinted(metaBatch) will always equal totalSupply(metaBatchInitialization) + tokenToBeMinted(metaBatchInitialization)
*/
metaBatch.realSupply = token.totalSupply().add(tokensToBeMinted);
metaBatch.buyFeePct = buyFeePct;
metaBatch.sellFeePct = sellFeePct;
metaBatch.formula = formula;
metaBatch.initialized = true;
emit NewMetaBatch(batchId, metaBatch.realSupply, metaBatch.buyFeePct, metaBatch.sellFeePct, metaBatch.formula);
}
if (!batch.initialized) {
/**
* NOTE
* supply(batch) = realSupply(metaBatch) + virtualSupply(batchInitialization)
* virtualSupply can technically be updated during a batch: the on-going batch will still use
* its value at the time of initialization [it's up to the updater to act wisely]
*/
/**
* NOTE
* balance(batch) = poolBalance(batchInitialization) - collateralsToBeClaimed(batchInitialization) + virtualBalance(metaBatchInitialization)
* 1. buy and sell orders incoming during the current batch and affecting poolBalance or collateralsToBeClaimed
* should not be taken into account in the price computation [they are already a part of the batched price computation]
* 2. the only way for poolBalance to be modified during a batch [outside of incoming buy and sell orders]
* is for sell orders from previous meta-batches to be claimed [and collateral to be transfered] as the tap is a step-function of the meta-batch duration:
* as such poolBalance(batch) - collateralsToBeClaimed(batch) will always equal poolBalance(batchInitialization) - collateralsToBeClaimed(batchInitialization)
* 3. virtualBalance can technically be updated during a batch: the on-going batch will still use
* its value at the time of initialization [it's up to the updater to act wisely]
*/
controller.updateTappedAmount(_collateral);
batch.supply = metaBatch.realSupply.add(collaterals[_collateral].virtualSupply);
batch.balance = controller.balanceOf(address(reserve), _collateral).add(collaterals[_collateral].virtualBalance).sub(collateralsToBeClaimed[_collateral]);
batch.reserveRatio = collaterals[_collateral].reserveRatio;
batch.slippage = collaterals[_collateral].slippage;
batch.initialized = true;
emit NewBatch(batchId, _collateral, batch.supply, batch.balance, batch.reserveRatio, batch.slippage);
}
return (batchId, batch);
}
/* state modifiying functions */
function _open() internal {
isOpen = true;
emit Open();
}
function _updateBeneficiary(address _beneficiary) internal {
beneficiary = _beneficiary;
emit UpdateBeneficiary(_beneficiary);
}
function _updateFormula(IBancorFormula _formula) internal {
formula = _formula;
emit UpdateFormula(address(_formula));
}
function _updateFees(uint256 _buyFeePct, uint256 _sellFeePct) internal {
buyFeePct = _buyFeePct;
sellFeePct = _sellFeePct;
emit UpdateFees(_buyFeePct, _sellFeePct);
}
function _cancelCurrentBatch(address _collateral) internal {
(uint256 batchId, Batch storage batch) = _currentBatch(_collateral);
if (!batch.cancelled) {
batch.cancelled = true;
// bought bonds are cancelled but sold bonds are due back
// bought collaterals are cancelled but sold collaterals are due back
tokensToBeMinted = tokensToBeMinted.sub(batch.totalBuyReturn).add(batch.totalSellSpend);
collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].add(batch.totalBuySpend).sub(batch.totalSellReturn);
emit CancelBatch(batchId, _collateral);
}
}
function _addCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage)
internal
{
collaterals[_collateral].whitelisted = true;
collaterals[_collateral].virtualSupply = _virtualSupply;
collaterals[_collateral].virtualBalance = _virtualBalance;
collaterals[_collateral].reserveRatio = _reserveRatio;
collaterals[_collateral].slippage = _slippage;
emit AddCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage);
}
function _removeCollateralToken(address _collateral) internal {
_cancelCurrentBatch(_collateral);
Collateral storage collateral = collaterals[_collateral];
delete collateral.whitelisted;
delete collateral.virtualSupply;
delete collateral.virtualBalance;
delete collateral.reserveRatio;
delete collateral.slippage;
emit RemoveCollateralToken(_collateral);
}
function _updateCollateralToken(
address _collateral,
uint256 _virtualSupply,
uint256 _virtualBalance,
uint32 _reserveRatio,
uint256 _slippage
)
internal
{
collaterals[_collateral].virtualSupply = _virtualSupply;
collaterals[_collateral].virtualBalance = _virtualBalance;
collaterals[_collateral].reserveRatio = _reserveRatio;
collaterals[_collateral].slippage = _slippage;
emit UpdateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage);
}
function _openBuyOrder(address _buyer, address _collateral, uint256 _value) internal {
(uint256 batchId, Batch storage batch) = _currentBatch(_collateral);
// deduct fee
uint256 fee = _value.mul(metaBatches[batchId].buyFeePct).div(PCT_BASE);
uint256 value = _value.sub(fee);
// collect fee and collateral
if (fee > 0) {
_transfer(_buyer, beneficiary, _collateral, fee);
}
_transfer(_buyer, address(reserve), _collateral, value);
// save batch
uint256 deprecatedBuyReturn = batch.totalBuyReturn;
uint256 deprecatedSellReturn = batch.totalSellReturn;
// update batch
batch.totalBuySpend = batch.totalBuySpend.add(value);
batch.buyers[_buyer] = batch.buyers[_buyer].add(value);
// update pricing
_updatePricing(batch, batchId, _collateral);
// update the amount of tokens to be minted and collaterals to be claimed
tokensToBeMinted = tokensToBeMinted.sub(deprecatedBuyReturn).add(batch.totalBuyReturn);
collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(deprecatedSellReturn).add(batch.totalSellReturn);
// sanity checks
require(_slippageIsValid(batch, _collateral), ERROR_SLIPPAGE_EXCEEDS_LIMIT);
emit OpenBuyOrder(_buyer, batchId, _collateral, fee, value);
}
function _openSellOrder(address _seller, address _collateral, uint256 _amount) internal {
(uint256 batchId, Batch storage batch) = _currentBatch(_collateral);
// burn bonds
tokenManager.burn(_seller, _amount);
// save batch
uint256 deprecatedBuyReturn = batch.totalBuyReturn;
uint256 deprecatedSellReturn = batch.totalSellReturn;
// update batch
batch.totalSellSpend = batch.totalSellSpend.add(_amount);
batch.sellers[_seller] = batch.sellers[_seller].add(_amount);
// update pricing
_updatePricing(batch, batchId, _collateral);
// update the amount of tokens to be minted and collaterals to be claimed
tokensToBeMinted = tokensToBeMinted.sub(deprecatedBuyReturn).add(batch.totalBuyReturn);
collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(deprecatedSellReturn).add(batch.totalSellReturn);
// sanity checks
require(_slippageIsValid(batch, _collateral), ERROR_SLIPPAGE_EXCEEDS_LIMIT);
require(_poolBalanceIsSufficient(_collateral), ERROR_INSUFFICIENT_POOL_BALANCE);
emit OpenSellOrder(_seller, batchId, _collateral, _amount);
}
function _claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) internal {
Batch storage batch = metaBatches[_batchId].batches[_collateral];
uint256 buyReturn = (batch.buyers[_buyer].mul(batch.totalBuyReturn)).div(batch.totalBuySpend);
batch.buyers[_buyer] = 0;
if (buyReturn > 0) {
tokensToBeMinted = tokensToBeMinted.sub(buyReturn);
tokenManager.mint(_buyer, buyReturn);
}
emit ClaimBuyOrder(_buyer, _batchId, _collateral, buyReturn);
}
function _claimSellOrder(address _seller, uint256 _batchId, address _collateral) internal {
Batch storage batch = metaBatches[_batchId].batches[_collateral];
uint256 saleReturn = (batch.sellers[_seller].mul(batch.totalSellReturn)).div(batch.totalSellSpend);
uint256 fee = saleReturn.mul(metaBatches[_batchId].sellFeePct).div(PCT_BASE);
uint256 value = saleReturn.sub(fee);
batch.sellers[_seller] = 0;
if (value > 0) {
collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(saleReturn);
reserve.transfer(_collateral, _seller, value);
}
if (fee > 0) {
reserve.transfer(_collateral, beneficiary, fee);
}
emit ClaimSellOrder(_seller, _batchId, _collateral, fee, value);
}
function _claimCancelledBuyOrder(address _buyer, uint256 _batchId, address _collateral) internal {
Batch storage batch = metaBatches[_batchId].batches[_collateral];
uint256 value = batch.buyers[_buyer];
batch.buyers[_buyer] = 0;
if (value > 0) {
collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(value);
reserve.transfer(_collateral, _buyer, value);
}
emit ClaimCancelledBuyOrder(_buyer, _batchId, _collateral, value);
}
function _claimCancelledSellOrder(address _seller, uint256 _batchId, address _collateral) internal {
Batch storage batch = metaBatches[_batchId].batches[_collateral];
uint256 amount = batch.sellers[_seller];
batch.sellers[_seller] = 0;
if (amount > 0) {
tokensToBeMinted = tokensToBeMinted.sub(amount);
tokenManager.mint(_seller, amount);
}
emit ClaimCancelledSellOrder(_seller, _batchId, _collateral, amount);
}
function _updatePricing(Batch storage batch, uint256 _batchId, address _collateral) internal {
// the situation where there are no buy nor sell orders can't happen [keep commented]
// if (batch.totalSellSpend == 0 && batch.totalBuySpend == 0)
// return;
// static price is the current exact price in collateral
// per token according to the initial state of the batch
// [expressed in PPM for precision sake]
uint256 staticPricePPM = _staticPricePPM(batch.supply, batch.balance, batch.reserveRatio);
// [NOTE]
// if staticPrice is zero then resultOfSell [= 0] <= batch.totalBuySpend
// so totalSellReturn will be zero and totalBuyReturn will be
// computed normally along the formula
// 1. we want to find out if buy orders are worth more sell orders [or vice-versa]
// 2. we thus check the return of sell orders at the current exact price
// 3. if the return of sell orders is larger than the pending buys,
// there are more sells than buys [and vice-versa]
uint256 resultOfSell = batch.totalSellSpend.mul(staticPricePPM).div(uint256(PPM));
if (resultOfSell > batch.totalBuySpend) {
// >> sell orders are worth more than buy orders
// 1. first we execute all pending buy orders at the current exact
// price because there is at least one sell order for each buy order
// 2. then the final sell return is the addition of this first
// matched return with the remaining bonding curve return
// the number of tokens bought as a result of all buy orders matched at the
// current exact price [which is less than the total amount of tokens to be sold]
batch.totalBuyReturn = batch.totalBuySpend.mul(uint256(PPM)).div(staticPricePPM);
// the number of tokens left over to be sold along the curve which is the difference
// between the original total sell order and the result of all the buy orders
uint256 remainingSell = batch.totalSellSpend.sub(batch.totalBuyReturn);
// the amount of collateral generated by selling tokens left over to be sold
// along the bonding curve in the batch initial state [as if the buy orders
// never existed and the sell order was just smaller than originally thought]
uint256 remainingSellReturn = metaBatches[_batchId].formula.calculateSaleReturn(batch.supply, batch.balance, batch.reserveRatio, remainingSell);
// the total result of all sells is the original amount of buys which were matched
// plus the remaining sells which were executed along the bonding curve
batch.totalSellReturn = batch.totalBuySpend.add(remainingSellReturn);
} else {
// >> buy orders are worth more than sell orders
// 1. first we execute all pending sell orders at the current exact
// price because there is at least one buy order for each sell order
// 2. then the final buy return is the addition of this first
// matched return with the remaining bonding curve return
// the number of collaterals bought as a result of all sell orders matched at the
// current exact price [which is less than the total amount of collateral to be spent]
batch.totalSellReturn = resultOfSell;
// the number of collaterals left over to be spent along the curve which is the difference
// between the original total buy order and the result of all the sell orders
uint256 remainingBuy = batch.totalBuySpend.sub(resultOfSell);
// the amount of tokens generated by selling collaterals left over to be spent
// along the bonding curve in the batch initial state [as if the sell orders
// never existed and the buy order was just smaller than originally thought]
uint256 remainingBuyReturn = metaBatches[_batchId].formula.calculatePurchaseReturn(batch.supply, batch.balance, batch.reserveRatio, remainingBuy);
// the total result of all buys is the original amount of buys which were matched
// plus the remaining buys which were executed along the bonding curve
batch.totalBuyReturn = batch.totalSellSpend.add(remainingBuyReturn);
}
emit UpdatePricing(_batchId, _collateral, batch.totalBuySpend, batch.totalBuyReturn, batch.totalSellSpend, batch.totalSellReturn);
}
function _transfer(address _from, address _to, address _collateralToken, uint256 _amount) internal {
if (_collateralToken == ETH) {
_to.transfer(_amount);
} else {
require(ERC20(_collateralToken).safeTransferFrom(_from, _to, _amount), ERROR_TRANSFER_FROM_FAILED);
}
}
}
// File: @ablack/fundraising-shared-interfaces/contracts/IPresale.sol
pragma solidity 0.4.24;
contract IPresale {
function open() external;
function close() external;
function contribute(address _contributor, uint256 _value) external payable;
function refund(address _contributor, uint256 _vestedPurchaseId) external;
function contributionToTokens(uint256 _value) public view returns (uint256);
function contributionToken() public view returns (address);
}
// File: @ablack/fundraising-shared-interfaces/contracts/ITap.sol
pragma solidity 0.4.24;
contract ITap {
function updateBeneficiary(address _beneficiary) external;
function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external;
function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external;
function addTappedToken(address _token, uint256 _rate, uint256 _floor) external;
function updateTappedToken(address _token, uint256 _rate, uint256 _floor) external;
function resetTappedToken(address _token) external;
function updateTappedAmount(address _token) external;
function withdraw(address _token) external;
function getMaximumWithdrawal(address _token) public view returns (uint256);
function rates(address _token) public view returns (uint256);
}
// File: @ablack/fundraising-aragon-fundraising/contracts/AragonFundraisingController.sol
pragma solidity 0.4.24;
contract AragonFundraisingController is EtherTokenConstant, IsContract, IAragonFundraisingController, AragonApp {
using SafeERC20 for ERC20;
using SafeMath for uint256;
/**
Hardcoded constants to save gas
bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE");
bytes32 public constant UPDATE_FEES_ROLE = keccak256("UPDATE_FEES_ROLE");
bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = keccak256("ADD_COLLATERAL_TOKEN_ROLE");
bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = keccak256("REMOVE_COLLATERAL_TOKEN_ROLE");
bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = keccak256("UPDATE_COLLATERAL_TOKEN_ROLE");
bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE");
bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE");
bytes32 public constant ADD_TOKEN_TAP_ROLE = keccak256("ADD_TOKEN_TAP_ROLE");
bytes32 public constant UPDATE_TOKEN_TAP_ROLE = keccak256("UPDATE_TOKEN_TAP_ROLE");
bytes32 public constant OPEN_PRESALE_ROLE = keccak256("OPEN_PRESALE_ROLE");
bytes32 public constant OPEN_TRADING_ROLE = keccak256("OPEN_TRADING_ROLE");
bytes32 public constant CONTRIBUTE_ROLE = keccak256("CONTRIBUTE_ROLE");
bytes32 public constant OPEN_BUY_ORDER_ROLE = keccak256("OPEN_BUY_ORDER_ROLE");
bytes32 public constant OPEN_SELL_ORDER_ROLE = keccak256("OPEN_SELL_ORDER_ROLE");
bytes32 public constant WITHDRAW_ROLE = keccak256("WITHDRAW_ROLE");
*/
bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593;
bytes32 public constant UPDATE_FEES_ROLE = 0x5f9be2932ed3a723f295a763be1804c7ebfd1a41c1348fb8bdf5be1c5cdca822;
bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = 0x217b79cb2bc7760defc88529853ef81ab33ae5bb315408ce9f5af09c8776662d;
bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = 0x2044e56de223845e4be7d0a6f4e9a29b635547f16413a6d1327c58d9db438ee2;
bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = 0xe0565c2c43e0d841e206bb36a37f12f22584b4652ccee6f9e0c071b697a2e13d;
bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = 0x5d94de7e429250eee4ff97e30ab9f383bea3cd564d6780e0a9e965b1add1d207;
bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = 0x57c9c67896cf0a4ffe92cbea66c2f7c34380af06bf14215dabb078cf8a6d99e1;
bytes32 public constant ADD_TOKEN_TAP_ROLE = 0xbc9cb5e3f7ce81c4fd021d86a4bcb193dee9df315b540808c3ed59a81e596207;
bytes32 public constant UPDATE_TOKEN_TAP_ROLE = 0xdb8c88bedbc61ea0f92e1ce46da0b7a915affbd46d1c76c4bbac9a209e4a8416;
bytes32 public constant OPEN_PRESALE_ROLE = 0xf323aa41eef4850a8ae7ebd047d4c89f01ce49c781f3308be67303db9cdd48c2;
bytes32 public constant OPEN_TRADING_ROLE = 0x26ce034204208c0bbca4c8a793d17b99e546009b1dd31d3c1ef761f66372caf6;
bytes32 public constant CONTRIBUTE_ROLE = 0x9ccaca4edf2127f20c425fdd86af1ba178b9e5bee280cd70d88ac5f6874c4f07;
bytes32 public constant OPEN_BUY_ORDER_ROLE = 0xa589c8f284b76fc8d510d9d553485c47dbef1b0745ae00e0f3fd4e28fcd77ea7;
bytes32 public constant OPEN_SELL_ORDER_ROLE = 0xd68ba2b769fa37a2a7bd4bed9241b448bc99eca41f519ef037406386a8f291c0;
bytes32 public constant WITHDRAW_ROLE = 0x5d8e12c39142ff96d79d04d15d1ba1269e4fe57bb9d26f43523628b34ba108ec;
uint256 public constant TO_RESET_CAP = 10;
string private constant ERROR_CONTRACT_IS_EOA = "FUNDRAISING_CONTRACT_IS_EOA";
string private constant ERROR_INVALID_TOKENS = "FUNDRAISING_INVALID_TOKENS";
IPresale public presale;
BatchedBancorMarketMaker public marketMaker;
Agent public reserve;
ITap public tap;
address[] public toReset;
/***** external functions *****/
/**
* @notice Initialize Aragon Fundraising controller
* @param _presale The address of the presale contract
* @param _marketMaker The address of the market maker contract
* @param _reserve The address of the reserve [pool] contract
* @param _tap The address of the tap contract
* @param _toReset The addresses of the tokens whose tap timestamps are to be reset [when presale is closed and trading is open]
*/
function initialize(
IPresale _presale,
BatchedBancorMarketMaker _marketMaker,
Agent _reserve,
ITap _tap,
address[] _toReset
)
external
onlyInit
{
require(isContract(_presale), ERROR_CONTRACT_IS_EOA);
require(isContract(_marketMaker), ERROR_CONTRACT_IS_EOA);
require(isContract(_reserve), ERROR_CONTRACT_IS_EOA);
require(isContract(_tap), ERROR_CONTRACT_IS_EOA);
require(_toReset.length < TO_RESET_CAP, ERROR_INVALID_TOKENS);
initialized();
presale = _presale;
marketMaker = _marketMaker;
reserve = _reserve;
tap = _tap;
for (uint256 i = 0; i < _toReset.length; i++) {
require(_tokenIsContractOrETH(_toReset[i]), ERROR_INVALID_TOKENS);
toReset.push(_toReset[i]);
}
}
/* generic settings related function */
/**
* @notice Update beneficiary to `_beneficiary`
* @param _beneficiary The address of the new beneficiary
*/
function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) {
marketMaker.updateBeneficiary(_beneficiary);
tap.updateBeneficiary(_beneficiary);
}
/**
* @notice Update fees deducted from buy and sell orders to respectively `@formatPct(_buyFeePct)`% and `@formatPct(_sellFeePct)`%
* @param _buyFeePct The new fee to be deducted from buy orders [in PCT_BASE]
* @param _sellFeePct The new fee to be deducted from sell orders [in PCT_BASE]
*/
function updateFees(uint256 _buyFeePct, uint256 _sellFeePct) external auth(UPDATE_FEES_ROLE) {
marketMaker.updateFees(_buyFeePct, _sellFeePct);
}
/* presale related functions */
/**
* @notice Open presale
*/
function openPresale() external auth(OPEN_PRESALE_ROLE) {
presale.open();
}
/**
* @notice Close presale and open trading
*/
function closePresale() external isInitialized {
presale.close();
}
/**
* @notice Contribute to the presale up to `@tokenAmount(self.contributionToken(): address, _value)`
* @param _value The amount of contribution token to be spent
*/
function contribute(uint256 _value) external payable auth(CONTRIBUTE_ROLE) {
presale.contribute.value(msg.value)(msg.sender, _value);
}
/**
* @notice Refund `_contributor`'s presale contribution #`_vestedPurchaseId`
* @param _contributor The address of the contributor whose presale contribution is to be refunded
* @param _vestedPurchaseId The id of the contribution to be refunded
*/
function refund(address _contributor, uint256 _vestedPurchaseId) external isInitialized {
presale.refund(_contributor, _vestedPurchaseId);
}
/* market making related functions */
/**
* @notice Open trading [enabling users to open buy and sell orders]
*/
function openTrading() external auth(OPEN_TRADING_ROLE) {
for (uint256 i = 0; i < toReset.length; i++) {
if (tap.rates(toReset[i]) != uint256(0)) {
tap.resetTappedToken(toReset[i]);
}
}
marketMaker.open();
}
/**
* @notice Open a buy order worth `@tokenAmount(_collateral, _value)`
* @param _collateral The address of the collateral token to be spent
* @param _value The amount of collateral token to be spent
*/
function openBuyOrder(address _collateral, uint256 _value) external payable auth(OPEN_BUY_ORDER_ROLE) {
marketMaker.openBuyOrder.value(msg.value)(msg.sender, _collateral, _value);
}
/**
* @notice Open a sell order worth `@tokenAmount(self.token(): address, _amount)` against `_collateral.symbol(): string`
* @param _collateral The address of the collateral token to be returned
* @param _amount The amount of bonded token to be spent
*/
function openSellOrder(address _collateral, uint256 _amount) external auth(OPEN_SELL_ORDER_ROLE) {
marketMaker.openSellOrder(msg.sender, _collateral, _amount);
}
/**
* @notice Claim the results of `_collateral.symbol(): string` buy orders from batch #`_batchId`
* @param _buyer The address of the user whose buy orders are to be claimed
* @param _batchId The id of the batch in which buy orders are to be claimed
* @param _collateral The address of the collateral token against which buy orders are to be claimed
*/
function claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) external isInitialized {
marketMaker.claimBuyOrder(_buyer, _batchId, _collateral);
}
/**
* @notice Claim the results of `_collateral.symbol(): string` sell orders from batch #`_batchId`
* @param _seller The address of the user whose sell orders are to be claimed
* @param _batchId The id of the batch in which sell orders are to be claimed
* @param _collateral The address of the collateral token against which sell orders are to be claimed
*/
function claimSellOrder(address _seller, uint256 _batchId, address _collateral) external isInitialized {
marketMaker.claimSellOrder(_seller, _batchId, _collateral);
}
/* collateral tokens related functions */
/**
* @notice Add `_collateral.symbol(): string` as a whitelisted collateral token
* @param _collateral The address of the collateral token to be whitelisted
* @param _virtualSupply The virtual supply to be used for that collateral token [in wei]
* @param _virtualBalance The virtual balance to be used for that collateral token [in wei]
* @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM]
* @param _slippage The price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE]
* @param _rate The rate at which that token is to be tapped [in wei / block]
* @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei]
*/
function addCollateralToken(
address _collateral,
uint256 _virtualSupply,
uint256 _virtualBalance,
uint32 _reserveRatio,
uint256 _slippage,
uint256 _rate,
uint256 _floor
)
external
auth(ADD_COLLATERAL_TOKEN_ROLE)
{
marketMaker.addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage);
if (_collateral != ETH) {
reserve.addProtectedToken(_collateral);
}
if (_rate > 0) {
tap.addTappedToken(_collateral, _rate, _floor);
}
}
/**
* @notice Re-add `_collateral.symbol(): string` as a whitelisted collateral token [if it has been un-whitelisted in the past]
* @param _collateral The address of the collateral token to be whitelisted
* @param _virtualSupply The virtual supply to be used for that collateral token [in wei]
* @param _virtualBalance The virtual balance to be used for that collateral token [in wei]
* @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM]
* @param _slippage The price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE]
*/
function reAddCollateralToken(
address _collateral,
uint256 _virtualSupply,
uint256 _virtualBalance,
uint32 _reserveRatio,
uint256 _slippage
)
external
auth(ADD_COLLATERAL_TOKEN_ROLE)
{
marketMaker.addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage);
}
/**
* @notice Remove `_collateral.symbol(): string` as a whitelisted collateral token
* @param _collateral The address of the collateral token to be un-whitelisted
*/
function removeCollateralToken(address _collateral) external auth(REMOVE_COLLATERAL_TOKEN_ROLE) {
marketMaker.removeCollateralToken(_collateral);
// the token should still be tapped to avoid being locked
// the token should still be protected to avoid being spent
}
/**
* @notice Update `_collateral.symbol(): string` collateralization settings
* @param _collateral The address of the collateral token whose collateralization settings are to be updated
* @param _virtualSupply The new virtual supply to be used for that collateral token [in wei]
* @param _virtualBalance The new virtual balance to be used for that collateral token [in wei]
* @param _reserveRatio The new reserve ratio to be used for that collateral token [in PPM]
* @param _slippage The new price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE]
*/
function updateCollateralToken(
address _collateral,
uint256 _virtualSupply,
uint256 _virtualBalance,
uint32 _reserveRatio,
uint256 _slippage
)
external
auth(UPDATE_COLLATERAL_TOKEN_ROLE)
{
marketMaker.updateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage);
}
/* tap related functions */
/**
* @notice Update maximum tap rate increase percentage to `@formatPct(_maximumTapRateIncreasePct)`%
* @param _maximumTapRateIncreasePct The new maximum tap rate increase percentage to be allowed [in PCT_BASE]
*/
function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external auth(UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE) {
tap.updateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct);
}
/**
* @notice Update maximum tap floor decrease percentage to `@formatPct(_maximumTapFloorDecreasePct)`%
* @param _maximumTapFloorDecreasePct The new maximum tap floor decrease percentage to be allowed [in PCT_BASE]
*/
function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external auth(UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE) {
tap.updateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct);
}
/**
* @notice Add tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)`
* @param _token The address of the token to be tapped
* @param _rate The rate at which that token is to be tapped [in wei / block]
* @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei]
*/
function addTokenTap(address _token, uint256 _rate, uint256 _floor) external auth(ADD_TOKEN_TAP_ROLE) {
tap.addTappedToken(_token, _rate, _floor);
}
/**
* @notice Update tap for `_token.symbol(): string` with a rate of about `@tokenAmount(_token, 4 * 60 * 24 * 30 * _rate)` per month and a floor of `@tokenAmount(_token, _floor)`
* @param _token The address of the token whose tap is to be updated
* @param _rate The new rate at which that token is to be tapped [in wei / block]
* @param _floor The new floor above which the reserve [pool] balance for that token is to be kept [in wei]
*/
function updateTokenTap(address _token, uint256 _rate, uint256 _floor) external auth(UPDATE_TOKEN_TAP_ROLE) {
tap.updateTappedToken(_token, _rate, _floor);
}
/**
* @notice Update tapped amount for `_token.symbol(): string`
* @param _token The address of the token whose tapped amount is to be updated
*/
function updateTappedAmount(address _token) external {
tap.updateTappedAmount(_token);
}
/**
* @notice Transfer about `@tokenAmount(_token, self.getMaximumWithdrawal(_token): uint256)` from the reserve to the beneficiary
* @param _token The address of the token to be transfered from the reserve to the beneficiary
*/
function withdraw(address _token) external auth(WITHDRAW_ROLE) {
tap.withdraw(_token);
}
/***** public view functions *****/
function token() public view isInitialized returns (address) {
return marketMaker.token();
}
function contributionToken() public view isInitialized returns (address) {
return presale.contributionToken();
}
function getMaximumWithdrawal(address _token) public view isInitialized returns (uint256) {
return tap.getMaximumWithdrawal(_token);
}
function collateralsToBeClaimed(address _collateral) public view isInitialized returns (uint256) {
return marketMaker.collateralsToBeClaimed(_collateral);
}
function balanceOf(address _who, address _token) public view isInitialized returns (uint256) {
uint256 balance = _token == ETH ? _who.balance : ERC20(_token).staticBalanceOf(_who);
if (_who == address(reserve)) {
return balance.sub(tap.getMaximumWithdrawal(_token));
} else {
return balance;
}
}
/***** internal functions *****/
function _tokenIsContractOrETH(address _token) internal view returns (bool) {
return isContract(_token) || _token == ETH;
}
}
// File: @ablack/fundraising-presale/contracts/Presale.sol
pragma solidity ^0.4.24;
contract Presale is IPresale, EtherTokenConstant, IsContract, AragonApp {
using SafeERC20 for ERC20;
using SafeMath for uint256;
using SafeMath64 for uint64;
/**
Hardcoded constants to save gas
bytes32 public constant OPEN_ROLE = keccak256("OPEN_ROLE");
bytes32 public constant CONTRIBUTE_ROLE = keccak256("CONTRIBUTE_ROLE");
*/
bytes32 public constant OPEN_ROLE = 0xefa06053e2ca99a43c97c4a4f3d8a394ee3323a8ff237e625fba09fe30ceb0a4;
bytes32 public constant CONTRIBUTE_ROLE = 0x9ccaca4edf2127f20c425fdd86af1ba178b9e5bee280cd70d88ac5f6874c4f07;
uint256 public constant PPM = 1000000; // 0% = 0 * 10 ** 4; 1% = 1 * 10 ** 4; 100% = 100 * 10 ** 4
string private constant ERROR_CONTRACT_IS_EOA = "PRESALE_CONTRACT_IS_EOA";
string private constant ERROR_INVALID_BENEFICIARY = "PRESALE_INVALID_BENEFICIARY";
string private constant ERROR_INVALID_CONTRIBUTE_TOKEN = "PRESALE_INVALID_CONTRIBUTE_TOKEN";
string private constant ERROR_INVALID_GOAL = "PRESALE_INVALID_GOAL";
string private constant ERROR_INVALID_EXCHANGE_RATE = "PRESALE_INVALID_EXCHANGE_RATE";
string private constant ERROR_INVALID_TIME_PERIOD = "PRESALE_INVALID_TIME_PERIOD";
string private constant ERROR_INVALID_PCT = "PRESALE_INVALID_PCT";
string private constant ERROR_INVALID_STATE = "PRESALE_INVALID_STATE";
string private constant ERROR_INVALID_CONTRIBUTE_VALUE = "PRESALE_INVALID_CONTRIBUTE_VALUE";
string private constant ERROR_INSUFFICIENT_BALANCE = "PRESALE_INSUFFICIENT_BALANCE";
string private constant ERROR_INSUFFICIENT_ALLOWANCE = "PRESALE_INSUFFICIENT_ALLOWANCE";
string private constant ERROR_NOTHING_TO_REFUND = "PRESALE_NOTHING_TO_REFUND";
string private constant ERROR_TOKEN_TRANSFER_REVERTED = "PRESALE_TOKEN_TRANSFER_REVERTED";
enum State {
Pending, // presale is idle and pending to be started
Funding, // presale has started and contributors can purchase tokens
Refunding, // presale has not reached goal within period and contributors can claim refunds
GoalReached, // presale has reached goal within period and trading is ready to be open
Closed // presale has reached goal within period, has been closed and trading has been open
}
IAragonFundraisingController public controller;
TokenManager public tokenManager;
ERC20 public token;
address public reserve;
address public beneficiary;
address public contributionToken;
uint256 public goal;
uint64 public period;
uint256 public exchangeRate;
uint64 public vestingCliffPeriod;
uint64 public vestingCompletePeriod;
uint256 public supplyOfferedPct;
uint256 public fundingForBeneficiaryPct;
uint64 public openDate;
bool public isClosed;
uint64 public vestingCliffDate;
uint64 public vestingCompleteDate;
uint256 public totalRaised;
mapping(address => mapping(uint256 => uint256)) public contributions; // contributor => (vestedPurchaseId => tokensSpent)
event SetOpenDate (uint64 date);
event Close ();
event Contribute (address indexed contributor, uint256 value, uint256 amount, uint256 vestedPurchaseId);
event Refund (address indexed contributor, uint256 value, uint256 amount, uint256 vestedPurchaseId);
/***** external function *****/
/**
* @notice Initialize presale
* @param _controller The address of the controller contract
* @param _tokenManager The address of the [bonded] token manager contract
* @param _reserve The address of the reserve [pool] contract
* @param _beneficiary The address of the beneficiary [to whom a percentage of the raised funds is be to be sent]
* @param _contributionToken The address of the token to be used to contribute
* @param _goal The goal to be reached by the end of that presale [in contribution token wei]
* @param _period The period within which to accept contribution for that presale
* @param _exchangeRate The exchangeRate [= 1/price] at which [bonded] tokens are to be purchased for that presale [in PPM]
* @param _vestingCliffPeriod The period during which purchased [bonded] tokens are to be cliffed
* @param _vestingCompletePeriod The complete period during which purchased [bonded] tokens are to be vested
* @param _supplyOfferedPct The percentage of the initial supply of [bonded] tokens to be offered during that presale [in PPM]
* @param _fundingForBeneficiaryPct The percentage of the raised contribution tokens to be sent to the beneficiary [instead of the fundraising reserve] when that presale is closed [in PPM]
* @param _openDate The date upon which that presale is to be open [ignored if 0]
*/
function initialize(
IAragonFundraisingController _controller,
TokenManager _tokenManager,
address _reserve,
address _beneficiary,
address _contributionToken,
uint256 _goal,
uint64 _period,
uint256 _exchangeRate,
uint64 _vestingCliffPeriod,
uint64 _vestingCompletePeriod,
uint256 _supplyOfferedPct,
uint256 _fundingForBeneficiaryPct,
uint64 _openDate
)
external
onlyInit
{
require(isContract(_controller), ERROR_CONTRACT_IS_EOA);
require(isContract(_tokenManager), ERROR_CONTRACT_IS_EOA);
require(isContract(_reserve), ERROR_CONTRACT_IS_EOA);
require(_beneficiary != address(0), ERROR_INVALID_BENEFICIARY);
require(isContract(_contributionToken) || _contributionToken == ETH, ERROR_INVALID_CONTRIBUTE_TOKEN);
require(_goal > 0, ERROR_INVALID_GOAL);
require(_period > 0, ERROR_INVALID_TIME_PERIOD);
require(_exchangeRate > 0, ERROR_INVALID_EXCHANGE_RATE);
require(_vestingCliffPeriod > _period, ERROR_INVALID_TIME_PERIOD);
require(_vestingCompletePeriod > _vestingCliffPeriod, ERROR_INVALID_TIME_PERIOD);
require(_supplyOfferedPct > 0 && _supplyOfferedPct <= PPM, ERROR_INVALID_PCT);
require(_fundingForBeneficiaryPct >= 0 && _fundingForBeneficiaryPct <= PPM, ERROR_INVALID_PCT);
initialized();
controller = _controller;
tokenManager = _tokenManager;
token = ERC20(_tokenManager.token());
reserve = _reserve;
beneficiary = _beneficiary;
contributionToken = _contributionToken;
goal = _goal;
period = _period;
exchangeRate = _exchangeRate;
vestingCliffPeriod = _vestingCliffPeriod;
vestingCompletePeriod = _vestingCompletePeriod;
supplyOfferedPct = _supplyOfferedPct;
fundingForBeneficiaryPct = _fundingForBeneficiaryPct;
if (_openDate != 0) {
_setOpenDate(_openDate);
}
}
/**
* @notice Open presale [enabling users to contribute]
*/
function open() external auth(OPEN_ROLE) {
require(state() == State.Pending, ERROR_INVALID_STATE);
require(openDate == 0, ERROR_INVALID_STATE);
_open();
}
/**
* @notice Contribute to the presale up to `@tokenAmount(self.contributionToken(): address, _value)`
* @param _contributor The address of the contributor
* @param _value The amount of contribution token to be spent
*/
function contribute(address _contributor, uint256 _value) external payable nonReentrant auth(CONTRIBUTE_ROLE) {
require(state() == State.Funding, ERROR_INVALID_STATE);
require(_value != 0, ERROR_INVALID_CONTRIBUTE_VALUE);
if (contributionToken == ETH) {
require(msg.value == _value, ERROR_INVALID_CONTRIBUTE_VALUE);
} else {
require(msg.value == 0, ERROR_INVALID_CONTRIBUTE_VALUE);
}
_contribute(_contributor, _value);
}
/**
* @notice Refund `_contributor`'s presale contribution #`_vestedPurchaseId`
* @param _contributor The address of the contributor whose presale contribution is to be refunded
* @param _vestedPurchaseId The id of the contribution to be refunded
*/
function refund(address _contributor, uint256 _vestedPurchaseId) external nonReentrant isInitialized {
require(state() == State.Refunding, ERROR_INVALID_STATE);
_refund(_contributor, _vestedPurchaseId);
}
/**
* @notice Close presale and open trading
*/
function close() external nonReentrant isInitialized {
require(state() == State.GoalReached, ERROR_INVALID_STATE);
_close();
}
/***** public view functions *****/
/**
* @notice Computes the amount of [bonded] tokens that would be purchased for `@tokenAmount(self.contributionToken(): address, _value)`
* @param _value The amount of contribution tokens to be used in that computation
*/
function contributionToTokens(uint256 _value) public view isInitialized returns (uint256) {
return _value.mul(exchangeRate).div(PPM);
}
function contributionToken() public view isInitialized returns (address) {
return contributionToken;
}
/**
* @notice Returns the current state of that presale
*/
function state() public view isInitialized returns (State) {
if (openDate == 0 || openDate > getTimestamp64()) {
return State.Pending;
}
if (totalRaised >= goal) {
if (isClosed) {
return State.Closed;
} else {
return State.GoalReached;
}
}
if (_timeSinceOpen() < period) {
return State.Funding;
} else {
return State.Refunding;
}
}
/***** internal functions *****/
function _timeSinceOpen() internal view returns (uint64) {
if (openDate == 0) {
return 0;
} else {
return getTimestamp64().sub(openDate);
}
}
function _setOpenDate(uint64 _date) internal {
require(_date >= getTimestamp64(), ERROR_INVALID_TIME_PERIOD);
openDate = _date;
_setVestingDatesWhenOpenDateIsKnown();
emit SetOpenDate(_date);
}
function _setVestingDatesWhenOpenDateIsKnown() internal {
vestingCliffDate = openDate.add(vestingCliffPeriod);
vestingCompleteDate = openDate.add(vestingCompletePeriod);
}
function _open() internal {
_setOpenDate(getTimestamp64());
}
function _contribute(address _contributor, uint256 _value) internal {
uint256 value = totalRaised.add(_value) > goal ? goal.sub(totalRaised) : _value;
if (contributionToken == ETH && _value > value) {
msg.sender.transfer(_value.sub(value));
}
// (contributor) ~~~> contribution tokens ~~~> (presale)
if (contributionToken != ETH) {
require(ERC20(contributionToken).balanceOf(_contributor) >= value, ERROR_INSUFFICIENT_BALANCE);
require(ERC20(contributionToken).allowance(_contributor, address(this)) >= value, ERROR_INSUFFICIENT_ALLOWANCE);
_transfer(contributionToken, _contributor, address(this), value);
}
// (mint ✨) ~~~> project tokens ~~~> (contributor)
uint256 tokensToSell = contributionToTokens(value);
tokenManager.issue(tokensToSell);
uint256 vestedPurchaseId = tokenManager.assignVested(
_contributor,
tokensToSell,
openDate,
vestingCliffDate,
vestingCompleteDate,
true /* revokable */
);
totalRaised = totalRaised.add(value);
// register contribution tokens spent in this purchase for a possible upcoming refund
contributions[_contributor][vestedPurchaseId] = value;
emit Contribute(_contributor, value, tokensToSell, vestedPurchaseId);
}
function _refund(address _contributor, uint256 _vestedPurchaseId) internal {
// recall how much contribution tokens are to be refund for this purchase
uint256 tokensToRefund = contributions[_contributor][_vestedPurchaseId];
require(tokensToRefund > 0, ERROR_NOTHING_TO_REFUND);
contributions[_contributor][_vestedPurchaseId] = 0;
// (presale) ~~~> contribution tokens ~~~> (contributor)
_transfer(contributionToken, address(this), _contributor, tokensToRefund);
/**
* NOTE
* the following lines assume that _contributor has not transfered any of its vested tokens
* for now TokenManager does not handle switching the transferrable status of its underlying token
* there is thus no way to enforce non-transferrability during the presale phase only
* this will be updated in a later version
*/
// (contributor) ~~~> project tokens ~~~> (token manager)
(uint256 tokensSold,,,,) = tokenManager.getVesting(_contributor, _vestedPurchaseId);
tokenManager.revokeVesting(_contributor, _vestedPurchaseId);
// (token manager) ~~~> project tokens ~~~> (burn 💥)
tokenManager.burn(address(tokenManager), tokensSold);
emit Refund(_contributor, tokensToRefund, tokensSold, _vestedPurchaseId);
}
function _close() internal {
isClosed = true;
// (presale) ~~~> contribution tokens ~~~> (beneficiary)
uint256 fundsForBeneficiary = totalRaised.mul(fundingForBeneficiaryPct).div(PPM);
if (fundsForBeneficiary > 0) {
_transfer(contributionToken, address(this), beneficiary, fundsForBeneficiary);
}
// (presale) ~~~> contribution tokens ~~~> (reserve)
uint256 tokensForReserve = contributionToken == ETH ? address(this).balance : ERC20(contributionToken).balanceOf(address(this));
_transfer(contributionToken, address(this), reserve, tokensForReserve);
// (mint ✨) ~~~> project tokens ~~~> (beneficiary)
uint256 tokensForBeneficiary = token.totalSupply().mul(PPM.sub(supplyOfferedPct)).div(supplyOfferedPct);
tokenManager.issue(tokensForBeneficiary);
tokenManager.assignVested(
beneficiary,
tokensForBeneficiary,
openDate,
vestingCliffDate,
vestingCompleteDate,
false /* revokable */
);
// open trading
controller.openTrading();
emit Close();
}
function _transfer(address _token, address _from, address _to, uint256 _amount) internal {
if (_token == ETH) {
require(_from == address(this), ERROR_TOKEN_TRANSFER_REVERTED);
require(_to != address(this), ERROR_TOKEN_TRANSFER_REVERTED);
_to.transfer(_amount);
} else {
if (_from == address(this)) {
require(ERC20(_token).safeTransfer(_to, _amount), ERROR_TOKEN_TRANSFER_REVERTED);
} else {
require(ERC20(_token).safeTransferFrom(_from, _to, _amount), ERROR_TOKEN_TRANSFER_REVERTED);
}
}
}
}
// File: @ablack/fundraising-tap/contracts/Tap.sol
pragma solidity 0.4.24;
contract Tap is ITap, TimeHelpers, EtherTokenConstant, IsContract, AragonApp {
using SafeERC20 for ERC20;
using SafeMath for uint256;
/**
Hardcoded constants to save gas
bytes32 public constant UPDATE_CONTROLLER_ROLE = keccak256("UPDATE_CONTROLLER_ROLE");
bytes32 public constant UPDATE_RESERVE_ROLE = keccak256("UPDATE_RESERVE_ROLE");
bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE");
bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE");
bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE");
bytes32 public constant ADD_TAPPED_TOKEN_ROLE = keccak256("ADD_TAPPED_TOKEN_ROLE");
bytes32 public constant REMOVE_TAPPED_TOKEN_ROLE = keccak256("REMOVE_TAPPED_TOKEN_ROLE");
bytes32 public constant UPDATE_TAPPED_TOKEN_ROLE = keccak256("UPDATE_TAPPED_TOKEN_ROLE");
bytes32 public constant RESET_TAPPED_TOKEN_ROLE = keccak256("RESET_TAPPED_TOKEN_ROLE");
bytes32 public constant WITHDRAW_ROLE = keccak256("WITHDRAW_ROLE");
*/
bytes32 public constant UPDATE_CONTROLLER_ROLE = 0x454b5d0dbb74f012faf1d3722ea441689f97dc957dd3ca5335b4969586e5dc30;
bytes32 public constant UPDATE_RESERVE_ROLE = 0x7984c050833e1db850f5aa7476710412fd2983fcec34da049502835ad7aed4f7;
bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593;
bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = 0x5d94de7e429250eee4ff97e30ab9f383bea3cd564d6780e0a9e965b1add1d207;
bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = 0x57c9c67896cf0a4ffe92cbea66c2f7c34380af06bf14215dabb078cf8a6d99e1;
bytes32 public constant ADD_TAPPED_TOKEN_ROLE = 0x5bc3b608e6be93b75a1c472a4a5bea3d31eabae46bf968e4bc4c7701562114dc;
bytes32 public constant REMOVE_TAPPED_TOKEN_ROLE = 0xd76960be78bfedc5b40ce4fa64a2f8308f39dd2cbb1f9676dbc4ce87b817befd;
bytes32 public constant UPDATE_TAPPED_TOKEN_ROLE = 0x83201394534c53ae0b4696fd49a933082d3e0525aa5a3d0a14a2f51e12213288;
bytes32 public constant RESET_TAPPED_TOKEN_ROLE = 0x294bf52c518669359157a9fe826e510dfc3dbd200d44bf77ec9536bff34bc29e;
bytes32 public constant WITHDRAW_ROLE = 0x5d8e12c39142ff96d79d04d15d1ba1269e4fe57bb9d26f43523628b34ba108ec;
uint256 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10 ** 16; 100% = 10 ** 18
string private constant ERROR_CONTRACT_IS_EOA = "TAP_CONTRACT_IS_EOA";
string private constant ERROR_INVALID_BENEFICIARY = "TAP_INVALID_BENEFICIARY";
string private constant ERROR_INVALID_BATCH_BLOCKS = "TAP_INVALID_BATCH_BLOCKS";
string private constant ERROR_INVALID_FLOOR_DECREASE_PCT = "TAP_INVALID_FLOOR_DECREASE_PCT";
string private constant ERROR_INVALID_TOKEN = "TAP_INVALID_TOKEN";
string private constant ERROR_INVALID_TAP_RATE = "TAP_INVALID_TAP_RATE";
string private constant ERROR_INVALID_TAP_UPDATE = "TAP_INVALID_TAP_UPDATE";
string private constant ERROR_TOKEN_ALREADY_TAPPED = "TAP_TOKEN_ALREADY_TAPPED";
string private constant ERROR_TOKEN_NOT_TAPPED = "TAP_TOKEN_NOT_TAPPED";
string private constant ERROR_WITHDRAWAL_AMOUNT_ZERO = "TAP_WITHDRAWAL_AMOUNT_ZERO";
IAragonFundraisingController public controller;
Vault public reserve;
address public beneficiary;
uint256 public batchBlocks;
uint256 public maximumTapRateIncreasePct;
uint256 public maximumTapFloorDecreasePct;
mapping (address => uint256) public tappedAmounts;
mapping (address => uint256) public rates;
mapping (address => uint256) public floors;
mapping (address => uint256) public lastTappedAmountUpdates; // batch ids [block numbers]
mapping (address => uint256) public lastTapUpdates; // timestamps
event UpdateBeneficiary (address indexed beneficiary);
event UpdateMaximumTapRateIncreasePct (uint256 maximumTapRateIncreasePct);
event UpdateMaximumTapFloorDecreasePct(uint256 maximumTapFloorDecreasePct);
event AddTappedToken (address indexed token, uint256 rate, uint256 floor);
event RemoveTappedToken (address indexed token);
event UpdateTappedToken (address indexed token, uint256 rate, uint256 floor);
event ResetTappedToken (address indexed token);
event UpdateTappedAmount (address indexed token, uint256 tappedAmount);
event Withdraw (address indexed token, uint256 amount);
/***** external functions *****/
/**
* @notice Initialize tap
* @param _controller The address of the controller contract
* @param _reserve The address of the reserve [pool] contract
* @param _beneficiary The address of the beneficiary [to whom funds are to be withdrawn]
* @param _batchBlocks The number of blocks batches are to last
* @param _maximumTapRateIncreasePct The maximum tap rate increase percentage allowed [in PCT_BASE]
* @param _maximumTapFloorDecreasePct The maximum tap floor decrease percentage allowed [in PCT_BASE]
*/
function initialize(
IAragonFundraisingController _controller,
Vault _reserve,
address _beneficiary,
uint256 _batchBlocks,
uint256 _maximumTapRateIncreasePct,
uint256 _maximumTapFloorDecreasePct
)
external
onlyInit
{
require(isContract(_controller), ERROR_CONTRACT_IS_EOA);
require(isContract(_reserve), ERROR_CONTRACT_IS_EOA);
require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY);
require(_batchBlocks != 0, ERROR_INVALID_BATCH_BLOCKS);
require(_maximumTapFloorDecreasePctIsValid(_maximumTapFloorDecreasePct), ERROR_INVALID_FLOOR_DECREASE_PCT);
initialized();
controller = _controller;
reserve = _reserve;
beneficiary = _beneficiary;
batchBlocks = _batchBlocks;
maximumTapRateIncreasePct = _maximumTapRateIncreasePct;
maximumTapFloorDecreasePct = _maximumTapFloorDecreasePct;
}
/**
* @notice Update beneficiary to `_beneficiary`
* @param _beneficiary The address of the new beneficiary [to whom funds are to be withdrawn]
*/
function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) {
require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY);
_updateBeneficiary(_beneficiary);
}
/**
* @notice Update maximum tap rate increase percentage to `@formatPct(_maximumTapRateIncreasePct)`%
* @param _maximumTapRateIncreasePct The new maximum tap rate increase percentage to be allowed [in PCT_BASE]
*/
function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external auth(UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE) {
_updateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct);
}
/**
* @notice Update maximum tap floor decrease percentage to `@formatPct(_maximumTapFloorDecreasePct)`%
* @param _maximumTapFloorDecreasePct The new maximum tap floor decrease percentage to be allowed [in PCT_BASE]
*/
function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external auth(UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE) {
require(_maximumTapFloorDecreasePctIsValid(_maximumTapFloorDecreasePct), ERROR_INVALID_FLOOR_DECREASE_PCT);
_updateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct);
}
/**
* @notice Add tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)`
* @param _token The address of the token to be tapped
* @param _rate The rate at which that token is to be tapped [in wei / block]
* @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei]
*/
function addTappedToken(address _token, uint256 _rate, uint256 _floor) external auth(ADD_TAPPED_TOKEN_ROLE) {
require(_tokenIsContractOrETH(_token), ERROR_INVALID_TOKEN);
require(!_tokenIsTapped(_token), ERROR_TOKEN_ALREADY_TAPPED);
require(_tapRateIsValid(_rate), ERROR_INVALID_TAP_RATE);
_addTappedToken(_token, _rate, _floor);
}
/**
* @notice Remove tap for `_token.symbol(): string`
* @param _token The address of the token to be un-tapped
*/
function removeTappedToken(address _token) external auth(REMOVE_TAPPED_TOKEN_ROLE) {
require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED);
_removeTappedToken(_token);
}
/**
* @notice Update tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)`
* @param _token The address of the token whose tap is to be updated
* @param _rate The new rate at which that token is to be tapped [in wei / block]
* @param _floor The new floor above which the reserve [pool] balance for that token is to be kept [in wei]
*/
function updateTappedToken(address _token, uint256 _rate, uint256 _floor) external auth(UPDATE_TAPPED_TOKEN_ROLE) {
require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED);
require(_tapRateIsValid(_rate), ERROR_INVALID_TAP_RATE);
require(_tapUpdateIsValid(_token, _rate, _floor), ERROR_INVALID_TAP_UPDATE);
_updateTappedToken(_token, _rate, _floor);
}
/**
* @notice Reset tap timestamps for `_token.symbol(): string`
* @param _token The address of the token whose tap timestamps are to be reset
*/
function resetTappedToken(address _token) external auth(RESET_TAPPED_TOKEN_ROLE) {
require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED);
_resetTappedToken(_token);
}
/**
* @notice Update tapped amount for `_token.symbol(): string`
* @param _token The address of the token whose tapped amount is to be updated
*/
function updateTappedAmount(address _token) external {
require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED);
_updateTappedAmount(_token);
}
/**
* @notice Transfer about `@tokenAmount(_token, self.getMaximalWithdrawal(_token): uint256)` from `self.reserve()` to `self.beneficiary()`
* @param _token The address of the token to be transfered
*/
function withdraw(address _token) external auth(WITHDRAW_ROLE) {
require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED);
uint256 amount = _updateTappedAmount(_token);
require(amount > 0, ERROR_WITHDRAWAL_AMOUNT_ZERO);
_withdraw(_token, amount);
}
/***** public view functions *****/
function getMaximumWithdrawal(address _token) public view isInitialized returns (uint256) {
return _tappedAmount(_token);
}
function rates(address _token) public view isInitialized returns (uint256) {
return rates[_token];
}
/***** internal functions *****/
/* computation functions */
function _currentBatchId() internal view returns (uint256) {
return (block.number.div(batchBlocks)).mul(batchBlocks);
}
function _tappedAmount(address _token) internal view returns (uint256) {
uint256 toBeKept = controller.collateralsToBeClaimed(_token).add(floors[_token]);
uint256 balance = _token == ETH ? address(reserve).balance : ERC20(_token).staticBalanceOf(reserve);
uint256 flow = (_currentBatchId().sub(lastTappedAmountUpdates[_token])).mul(rates[_token]);
uint256 tappedAmount = tappedAmounts[_token].add(flow);
/**
* whatever happens enough collateral should be
* kept in the reserve pool to guarantee that
* its balance is kept above the floor once
* all pending sell orders are claimed
*/
/**
* the reserve's balance is already below the balance to be kept
* the tapped amount should be reset to zero
*/
if (balance <= toBeKept) {
return 0;
}
/**
* the reserve's balance minus the upcoming tap flow would be below the balance to be kept
* the flow should be reduced to balance - toBeKept
*/
if (balance <= toBeKept.add(tappedAmount)) {
return balance.sub(toBeKept);
}
/**
* the reserve's balance minus the upcoming flow is above the balance to be kept
* the flow can be added to the tapped amount
*/
return tappedAmount;
}
/* check functions */
function _beneficiaryIsValid(address _beneficiary) internal pure returns (bool) {
return _beneficiary != address(0);
}
function _maximumTapFloorDecreasePctIsValid(uint256 _maximumTapFloorDecreasePct) internal pure returns (bool) {
return _maximumTapFloorDecreasePct <= PCT_BASE;
}
function _tokenIsContractOrETH(address _token) internal view returns (bool) {
return isContract(_token) || _token == ETH;
}
function _tokenIsTapped(address _token) internal view returns (bool) {
return rates[_token] != uint256(0);
}
function _tapRateIsValid(uint256 _rate) internal pure returns (bool) {
return _rate != 0;
}
function _tapUpdateIsValid(address _token, uint256 _rate, uint256 _floor) internal view returns (bool) {
return _tapRateUpdateIsValid(_token, _rate) && _tapFloorUpdateIsValid(_token, _floor);
}
function _tapRateUpdateIsValid(address _token, uint256 _rate) internal view returns (bool) {
uint256 rate = rates[_token];
if (_rate <= rate) {
return true;
}
if (getTimestamp() < lastTapUpdates[_token] + 30 days) {
return false;
}
if (_rate.mul(PCT_BASE) <= rate.mul(PCT_BASE.add(maximumTapRateIncreasePct))) {
return true;
}
return false;
}
function _tapFloorUpdateIsValid(address _token, uint256 _floor) internal view returns (bool) {
uint256 floor = floors[_token];
if (_floor >= floor) {
return true;
}
if (getTimestamp() < lastTapUpdates[_token] + 30 days) {
return false;
}
if (maximumTapFloorDecreasePct >= PCT_BASE) {
return true;
}
if (_floor.mul(PCT_BASE) >= floor.mul(PCT_BASE.sub(maximumTapFloorDecreasePct))) {
return true;
}
return false;
}
/* state modifying functions */
function _updateTappedAmount(address _token) internal returns (uint256) {
uint256 tappedAmount = _tappedAmount(_token);
lastTappedAmountUpdates[_token] = _currentBatchId();
tappedAmounts[_token] = tappedAmount;
emit UpdateTappedAmount(_token, tappedAmount);
return tappedAmount;
}
function _updateBeneficiary(address _beneficiary) internal {
beneficiary = _beneficiary;
emit UpdateBeneficiary(_beneficiary);
}
function _updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) internal {
maximumTapRateIncreasePct = _maximumTapRateIncreasePct;
emit UpdateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct);
}
function _updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) internal {
maximumTapFloorDecreasePct = _maximumTapFloorDecreasePct;
emit UpdateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct);
}
function _addTappedToken(address _token, uint256 _rate, uint256 _floor) internal {
/**
* NOTE
* 1. if _token is tapped in the middle of a batch it will
* reach the next batch faster than what it normally takes
* to go through a batch [e.g. one block later]
* 2. this will allow for a higher withdrawal than expected
* a few blocks after _token is tapped
* 3. this is not a problem because this extra amount is
* static [at most rates[_token] * batchBlocks] and does
* not increase in time
*/
rates[_token] = _rate;
floors[_token] = _floor;
lastTappedAmountUpdates[_token] = _currentBatchId();
lastTapUpdates[_token] = getTimestamp();
emit AddTappedToken(_token, _rate, _floor);
}
function _removeTappedToken(address _token) internal {
delete tappedAmounts[_token];
delete rates[_token];
delete floors[_token];
delete lastTappedAmountUpdates[_token];
delete lastTapUpdates[_token];
emit RemoveTappedToken(_token);
}
function _updateTappedToken(address _token, uint256 _rate, uint256 _floor) internal {
/**
* NOTE
* withdraw before updating to keep the reserve
* actual balance [balance - virtual withdrawal]
* continuous in time [though a floor update can
* still break this continuity]
*/
uint256 amount = _updateTappedAmount(_token);
if (amount > 0) {
_withdraw(_token, amount);
}
rates[_token] = _rate;
floors[_token] = _floor;
lastTapUpdates[_token] = getTimestamp();
emit UpdateTappedToken(_token, _rate, _floor);
}
function _resetTappedToken(address _token) internal {
tappedAmounts[_token] = 0;
lastTappedAmountUpdates[_token] = _currentBatchId();
lastTapUpdates[_token] = getTimestamp();
emit ResetTappedToken(_token);
}
function _withdraw(address _token, uint256 _amount) internal {
tappedAmounts[_token] = tappedAmounts[_token].sub(_amount);
reserve.transfer(_token, beneficiary, _amount); // vault contract's transfer method already reverts on error
emit Withdraw(_token, _amount);
}
}
// File: contracts/AavegotchiTBCTemplate.sol
pragma solidity 0.4.24;
contract AavegotchiTBCTemplate is EtherTokenConstant, BaseTemplate {
string private constant ERROR_BAD_SETTINGS = "FM_BAD_SETTINGS";
string private constant ERROR_MISSING_CACHE = "FM_MISSING_CACHE";
bool private constant BOARD_TRANSFERABLE = false;
uint8 private constant BOARD_TOKEN_DECIMALS = uint8(0);
uint256 private constant BOARD_MAX_PER_ACCOUNT = uint256(1);
bool private constant SHARE_TRANSFERABLE = true;
uint8 private constant SHARE_TOKEN_DECIMALS = uint8(18);
uint256 private constant SHARE_MAX_PER_ACCOUNT = uint256(0);
uint64 private constant DEFAULT_FINANCE_PERIOD = uint64(30 days);
uint256 private constant BUY_FEE_PCT = 0;
uint256 private constant SELL_FEE_PCT = 0;
uint32 private constant DAI_RESERVE_RATIO = 333333; // 33%
uint32 private constant ANT_RESERVE_RATIO = 10000; // 1%
bytes32 private constant BANCOR_FORMULA_ID = 0xd71dde5e4bea1928026c1779bde7ed27bd7ef3d0ce9802e4117631eb6fa4ed7d;
bytes32 private constant PRESALE_ID = 0x5de9bbdeaf6584c220c7b7f1922383bcd8bbcd4b48832080afd9d5ebf9a04df5;
bytes32 private constant MARKET_MAKER_ID = 0xc2bb88ab974c474221f15f691ed9da38be2f5d37364180cec05403c656981bf0;
bytes32 private constant ARAGON_FUNDRAISING_ID = 0x668ac370eed7e5861234d1c0a1e512686f53594fcb887e5bcecc35675a4becac;
bytes32 private constant TAP_ID = 0x82967efab7144b764bc9bca2f31a721269b6618c0ff4e50545737700a5e9c9dc;
struct Cache {
address dao;
address boardTokenManager;
address boardVoting;
address vault;
address finance;
address shareVoting;
address shareTokenManager;
address reserve;
address presale;
address marketMaker;
address tap;
address controller;
}
address[] public collaterals;
mapping (address => Cache) private cache;
constructor(
DAOFactory _daoFactory,
ENS _ens,
MiniMeTokenFactory _miniMeFactory,
IFIFSResolvingRegistrar _aragonID,
address _dai,
address _ant
)
BaseTemplate(_daoFactory, _ens, _miniMeFactory, _aragonID)
public
{
_ensureAragonIdIsValid(_aragonID);
_ensureMiniMeFactoryIsValid(_miniMeFactory);
require(isContract(_dai), ERROR_BAD_SETTINGS);
require(isContract(_ant), ERROR_BAD_SETTINGS);
require(_dai != _ant, ERROR_BAD_SETTINGS);
collaterals.push(_dai);
collaterals.push(_ant);
}
/***** external functions *****/
function prepareInstance(
string _boardTokenName,
string _boardTokenSymbol,
address[] _boardMembers,
uint64[3] _boardVotingSettings,
uint64 _financePeriod
)
external
{
require(_boardMembers.length > 0, ERROR_BAD_SETTINGS);
require(_boardVotingSettings.length == 3, ERROR_BAD_SETTINGS);
// deploy DAO
(Kernel dao, ACL acl) = _createDAO();
// deploy board token
MiniMeToken boardToken = _createToken(_boardTokenName, _boardTokenSymbol, BOARD_TOKEN_DECIMALS);
// install board apps
TokenManager tm = _installBoardApps(dao, boardToken, _boardVotingSettings, _financePeriod);
// mint board tokens
_mintTokens(acl, tm, _boardMembers, 1);
// cache DAO
_cacheDao(dao);
}
function installShareApps(
string _shareTokenName,
string _shareTokenSymbol,
uint64[3] _shareVotingSettings
)
external
{
require(_shareVotingSettings.length == 3, ERROR_BAD_SETTINGS);
_ensureBoardAppsCache();
Kernel dao = _daoCache();
// deploy share token
MiniMeToken shareToken = _createToken(_shareTokenName, _shareTokenSymbol, SHARE_TOKEN_DECIMALS);
// install share apps
_installShareApps(dao, shareToken, _shareVotingSettings);
// setup board apps permissions [now that share apps have been installed]
_setupBoardPermissions(dao);
}
function installFundraisingApps(
uint256 _goal,
uint64 _period,
uint256 _exchangeRate,
uint64 _vestingCliffPeriod,
uint64 _vestingCompletePeriod,
uint256 _supplyOfferedPct,
uint256 _fundingForBeneficiaryPct,
uint64 _openDate,
uint256 _batchBlocks,
uint256 _maxTapRateIncreasePct,
uint256 _maxTapFloorDecreasePct
)
external
{
_ensureShareAppsCache();
Kernel dao = _daoCache();
// install fundraising apps
_installFundraisingApps(
dao,
_goal,
_period,
_exchangeRate,
_vestingCliffPeriod,
_vestingCompletePeriod,
_supplyOfferedPct,
_fundingForBeneficiaryPct,
_openDate,
_batchBlocks,
_maxTapRateIncreasePct,
_maxTapFloorDecreasePct
);
// setup share apps permissions [now that fundraising apps have been installed]
_setupSharePermissions(dao);
// setup fundraising apps permissions
_setupFundraisingPermissions(dao);
}
function finalizeInstance(
string _id,
uint256[2] _virtualSupplies,
uint256[2] _virtualBalances,
uint256[2] _slippages,
uint256 _rateDAI,
uint256 _floorDAI
)
external
{
require(bytes(_id).length > 0, ERROR_BAD_SETTINGS);
require(_virtualSupplies.length == 2, ERROR_BAD_SETTINGS);
require(_virtualBalances.length == 2, ERROR_BAD_SETTINGS);
require(_slippages.length == 2, ERROR_BAD_SETTINGS);
_ensureFundraisingAppsCache();
Kernel dao = _daoCache();
ACL acl = ACL(dao.acl());
(, Voting shareVoting) = _shareAppsCache();
// setup collaterals
_setupCollaterals(dao, _virtualSupplies, _virtualBalances, _slippages, _rateDAI, _floorDAI);
// setup EVM script registry permissions
_createEvmScriptsRegistryPermissions(acl, shareVoting, shareVoting);
// clear DAO permissions
_transferRootPermissionsFromTemplateAndFinalizeDAO(dao, shareVoting, shareVoting);
// register id
_registerID(_id, address(dao));
// clear cache
_clearCache();
}
/***** internal apps installation functions *****/
function _installBoardApps(Kernel _dao, MiniMeToken _token, uint64[3] _votingSettings, uint64 _financePeriod)
internal
returns (TokenManager)
{
TokenManager tm = _installTokenManagerApp(_dao, _token, BOARD_TRANSFERABLE, BOARD_MAX_PER_ACCOUNT);
Voting voting = _installVotingApp(_dao, _token, _votingSettings);
Vault vault = _installVaultApp(_dao);
Finance finance = _installFinanceApp(_dao, vault, _financePeriod == 0 ? DEFAULT_FINANCE_PERIOD : _financePeriod);
_cacheBoardApps(tm, voting, vault, finance);
return tm;
}
function _installShareApps(Kernel _dao, MiniMeToken _shareToken, uint64[3] _shareVotingSettings)
internal
{
TokenManager tm = _installTokenManagerApp(_dao, _shareToken, SHARE_TRANSFERABLE, SHARE_MAX_PER_ACCOUNT);
Voting voting = _installVotingApp(_dao, _shareToken, _shareVotingSettings);
_cacheShareApps(tm, voting);
}
function _installFundraisingApps(
Kernel _dao,
uint256 _goal,
uint64 _period,
uint256 _exchangeRate,
uint64 _vestingCliffPeriod,
uint64 _vestingCompletePeriod,
uint256 _supplyOfferedPct,
uint256 _fundingForBeneficiaryPct,
uint64 _openDate,
uint256 _batchBlocks,
uint256 _maxTapRateIncreasePct,
uint256 _maxTapFloorDecreasePct
)
internal
{
_proxifyFundraisingApps(_dao);
_initializePresale(
_goal,
_period,
_exchangeRate,
_vestingCliffPeriod,
_vestingCompletePeriod,
_supplyOfferedPct,
_fundingForBeneficiaryPct,
_openDate
);
_initializeMarketMaker(_batchBlocks);
_initializeTap(_batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct);
_initializeController();
}
function _proxifyFundraisingApps(Kernel _dao) internal {
Agent reserve = _installNonDefaultAgentApp(_dao);
Presale presale = Presale(_registerApp(_dao, PRESALE_ID));
BatchedBancorMarketMaker marketMaker = BatchedBancorMarketMaker(_registerApp(_dao, MARKET_MAKER_ID));
Tap tap = Tap(_registerApp(_dao, TAP_ID));
AragonFundraisingController controller = AragonFundraisingController(_registerApp(_dao, ARAGON_FUNDRAISING_ID));
_cacheFundraisingApps(reserve, presale, marketMaker, tap, controller);
}
/***** internal apps initialization functions *****/
function _initializePresale(
uint256 _goal,
uint64 _period,
uint256 _exchangeRate,
uint64 _vestingCliffPeriod,
uint64 _vestingCompletePeriod,
uint256 _supplyOfferedPct,
uint256 _fundingForBeneficiaryPct,
uint64 _openDate
)
internal
{
_presaleCache().initialize(
_controllerCache(),
_shareTMCache(),
_reserveCache(),
_vaultCache(),
collaterals[0],
_goal,
_period,
_exchangeRate,
_vestingCliffPeriod,
_vestingCompletePeriod,
_supplyOfferedPct,
_fundingForBeneficiaryPct,
_openDate
);
}
function _initializeMarketMaker(uint256 _batchBlocks) internal {
IBancorFormula bancorFormula = IBancorFormula(_latestVersionAppBase(BANCOR_FORMULA_ID));
(,, Vault beneficiary,) = _boardAppsCache();
(TokenManager shareTM,) = _shareAppsCache();
(Agent reserve,, BatchedBancorMarketMaker marketMaker,, AragonFundraisingController controller) = _fundraisingAppsCache();
marketMaker.initialize(controller, shareTM, bancorFormula, reserve, beneficiary, _batchBlocks, BUY_FEE_PCT, SELL_FEE_PCT);
}
function _initializeTap(uint256 _batchBlocks, uint256 _maxTapRateIncreasePct, uint256 _maxTapFloorDecreasePct) internal {
(,, Vault beneficiary,) = _boardAppsCache();
(Agent reserve,,, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache();
tap.initialize(controller, reserve, beneficiary, _batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct);
}
function _initializeController() internal {
(Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache();
address[] memory toReset = new address[](1);
toReset[0] = collaterals[0];
controller.initialize(presale, marketMaker, reserve, tap, toReset);
}
/***** internal setup functions *****/
function _setupCollaterals(
Kernel _dao,
uint256[2] _virtualSupplies,
uint256[2] _virtualBalances,
uint256[2] _slippages,
uint256 _rateDAI,
uint256 _floorDAI
)
internal
{
ACL acl = ACL(_dao.acl());
(, Voting shareVoting) = _shareAppsCache();
(,,,, AragonFundraisingController controller) = _fundraisingAppsCache();
// create and grant ADD_COLLATERAL_TOKEN_ROLE to this template
_createPermissionForTemplate(acl, address(controller), controller.ADD_COLLATERAL_TOKEN_ROLE());
// add DAI both as a protected collateral and a tapped token
controller.addCollateralToken(
collaterals[0],
_virtualSupplies[0],
_virtualBalances[0],
DAI_RESERVE_RATIO,
_slippages[0],
_rateDAI,
_floorDAI
);
// add ANT as a protected collateral [but not as a tapped token]
controller.addCollateralToken(
collaterals[1],
_virtualSupplies[1],
_virtualBalances[1],
ANT_RESERVE_RATIO,
_slippages[1],
0,
0
);
// transfer ADD_COLLATERAL_TOKEN_ROLE
_transferPermissionFromTemplate(acl, controller, shareVoting, controller.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting);
}
/***** internal permissions functions *****/
function _setupBoardPermissions(Kernel _dao) internal {
ACL acl = ACL(_dao.acl());
(TokenManager boardTM, Voting boardVoting, Vault vault, Finance finance) = _boardAppsCache();
(, Voting shareVoting) = _shareAppsCache();
// token manager
_createTokenManagerPermissions(acl, boardTM, boardVoting, shareVoting);
// voting
_createVotingPermissions(acl, boardVoting, boardVoting, boardTM, shareVoting);
// vault
_createVaultPermissions(acl, vault, finance, shareVoting);
// finance
_createFinancePermissions(acl, finance, boardVoting, shareVoting);
_createFinanceCreatePaymentsPermission(acl, finance, boardVoting, shareVoting);
}
function _setupSharePermissions(Kernel _dao) internal {
ACL acl = ACL(_dao.acl());
(TokenManager boardTM,,,) = _boardAppsCache();
(TokenManager shareTM, Voting shareVoting) = _shareAppsCache();
(, Presale presale, BatchedBancorMarketMaker marketMaker,,) = _fundraisingAppsCache();
// token manager
address[] memory grantees = new address[](2);
grantees[0] = address(marketMaker);
grantees[1] = address(presale);
acl.createPermission(marketMaker, shareTM, shareTM.MINT_ROLE(),shareVoting);
acl.createPermission(presale, shareTM, shareTM.ISSUE_ROLE(),shareVoting);
acl.createPermission(presale, shareTM, shareTM.ASSIGN_ROLE(),shareVoting);
acl.createPermission(presale, shareTM, shareTM.REVOKE_VESTINGS_ROLE(), shareVoting);
_createPermissions(acl, grantees, shareTM, shareTM.BURN_ROLE(), shareVoting);
// voting
_createVotingPermissions(acl, shareVoting, shareVoting, boardTM, shareVoting);
}
function _setupFundraisingPermissions(Kernel _dao) internal {
ACL acl = ACL(_dao.acl());
(, Voting boardVoting,,) = _boardAppsCache();
(, Voting shareVoting) = _shareAppsCache();
(Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache();
// reserve
address[] memory grantees = new address[](2);
grantees[0] = address(tap);
grantees[1] = address(marketMaker);
acl.createPermission(shareVoting, reserve, reserve.SAFE_EXECUTE_ROLE(), shareVoting);
acl.createPermission(controller, reserve, reserve.ADD_PROTECTED_TOKEN_ROLE(), shareVoting);
_createPermissions(acl, grantees, reserve, reserve.TRANSFER_ROLE(), shareVoting);
// presale
acl.createPermission(controller, presale, presale.OPEN_ROLE(), shareVoting);
acl.createPermission(controller, presale, presale.CONTRIBUTE_ROLE(), shareVoting);
// market maker
acl.createPermission(controller, marketMaker, marketMaker.OPEN_ROLE(), shareVoting);
acl.createPermission(controller, marketMaker, marketMaker.UPDATE_BENEFICIARY_ROLE(), shareVoting);
acl.createPermission(controller, marketMaker, marketMaker.UPDATE_FEES_ROLE(), shareVoting);
acl.createPermission(controller, marketMaker, marketMaker.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting);
acl.createPermission(controller, marketMaker, marketMaker.REMOVE_COLLATERAL_TOKEN_ROLE(), shareVoting);
acl.createPermission(controller, marketMaker, marketMaker.UPDATE_COLLATERAL_TOKEN_ROLE(), shareVoting);
acl.createPermission(controller, marketMaker, marketMaker.OPEN_BUY_ORDER_ROLE(), shareVoting);
acl.createPermission(controller, marketMaker, marketMaker.OPEN_SELL_ORDER_ROLE(), shareVoting);
// tap
acl.createPermission(controller, tap, tap.UPDATE_BENEFICIARY_ROLE(), shareVoting);
acl.createPermission(controller, tap, tap.UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE(), shareVoting);
acl.createPermission(controller, tap, tap.UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE(), shareVoting);
acl.createPermission(controller, tap, tap.ADD_TAPPED_TOKEN_ROLE(), shareVoting);
acl.createPermission(controller, tap, tap.UPDATE_TAPPED_TOKEN_ROLE(), shareVoting);
acl.createPermission(controller, tap, tap.RESET_TAPPED_TOKEN_ROLE(), shareVoting);
acl.createPermission(controller, tap, tap.WITHDRAW_ROLE(), shareVoting);
// controller
// ADD_COLLATERAL_TOKEN_ROLE is handled later [after collaterals have been added]
acl.createPermission(shareVoting, controller, controller.UPDATE_BENEFICIARY_ROLE(), shareVoting);
acl.createPermission(shareVoting, controller, controller.UPDATE_FEES_ROLE(), shareVoting);
// acl.createPermission(shareVoting, controller, controller.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting);
acl.createPermission(shareVoting, controller, controller.REMOVE_COLLATERAL_TOKEN_ROLE(), shareVoting);
acl.createPermission(shareVoting, controller, controller.UPDATE_COLLATERAL_TOKEN_ROLE(), shareVoting);
acl.createPermission(shareVoting, controller, controller.UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE(), shareVoting);
acl.createPermission(shareVoting, controller, controller.UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE(), shareVoting);
acl.createPermission(shareVoting, controller, controller.ADD_TOKEN_TAP_ROLE(), shareVoting);
acl.createPermission(shareVoting, controller, controller.UPDATE_TOKEN_TAP_ROLE(), shareVoting);
acl.createPermission(boardVoting, controller, controller.OPEN_PRESALE_ROLE(), shareVoting);
acl.createPermission(presale, controller, controller.OPEN_TRADING_ROLE(), shareVoting);
acl.createPermission(address(-1), controller, controller.CONTRIBUTE_ROLE(), shareVoting);
acl.createPermission(address(-1), controller, controller.OPEN_BUY_ORDER_ROLE(), shareVoting);
acl.createPermission(address(-1), controller, controller.OPEN_SELL_ORDER_ROLE(), shareVoting);
acl.createPermission(address(-1), controller, controller.WITHDRAW_ROLE(), shareVoting);
}
/***** internal cache functions *****/
function _cacheDao(Kernel _dao) internal {
Cache storage c = cache[msg.sender];
c.dao = address(_dao);
}
function _cacheBoardApps(TokenManager _boardTM, Voting _boardVoting, Vault _vault, Finance _finance) internal {
Cache storage c = cache[msg.sender];
c.boardTokenManager = address(_boardTM);
c.boardVoting = address(_boardVoting);
c.vault = address(_vault);
c.finance = address(_finance);
}
function _cacheShareApps(TokenManager _shareTM, Voting _shareVoting) internal {
Cache storage c = cache[msg.sender];
c.shareTokenManager = address(_shareTM);
c.shareVoting = address(_shareVoting);
}
function _cacheFundraisingApps(Agent _reserve, Presale _presale, BatchedBancorMarketMaker _marketMaker, Tap _tap, AragonFundraisingController _controller) internal {
Cache storage c = cache[msg.sender];
c.reserve = address(_reserve);
c.presale = address(_presale);
c.marketMaker = address(_marketMaker);
c.tap = address(_tap);
c.controller = address(_controller);
}
function _daoCache() internal view returns (Kernel dao) {
Cache storage c = cache[msg.sender];
dao = Kernel(c.dao);
}
function _boardAppsCache() internal view returns (TokenManager boardTM, Voting boardVoting, Vault vault, Finance finance) {
Cache storage c = cache[msg.sender];
boardTM = TokenManager(c.boardTokenManager);
boardVoting = Voting(c.boardVoting);
vault = Vault(c.vault);
finance = Finance(c.finance);
}
function _shareAppsCache() internal view returns (TokenManager shareTM, Voting shareVoting) {
Cache storage c = cache[msg.sender];
shareTM = TokenManager(c.shareTokenManager);
shareVoting = Voting(c.shareVoting);
}
function _fundraisingAppsCache() internal view returns (
Agent reserve,
Presale presale,
BatchedBancorMarketMaker marketMaker,
Tap tap,
AragonFundraisingController controller
)
{
Cache storage c = cache[msg.sender];
reserve = Agent(c.reserve);
presale = Presale(c.presale);
marketMaker = BatchedBancorMarketMaker(c.marketMaker);
tap = Tap(c.tap);
controller = AragonFundraisingController(c.controller);
}
function _clearCache() internal {
Cache storage c = cache[msg.sender];
delete c.dao;
delete c.boardTokenManager;
delete c.boardVoting;
delete c.vault;
delete c.finance;
delete c.shareVoting;
delete c.shareTokenManager;
delete c.reserve;
delete c.presale;
delete c.marketMaker;
delete c.tap;
delete c.controller;
}
/**
* NOTE
* the following functions are only needed for the presale
* initialization function [which we can't compile otherwise
* because of a `stack too deep` error]
*/
function _vaultCache() internal view returns (Vault vault) {
Cache storage c = cache[msg.sender];
vault = Vault(c.vault);
}
function _shareTMCache() internal view returns (TokenManager shareTM) {
Cache storage c = cache[msg.sender];
shareTM = TokenManager(c.shareTokenManager);
}
function _reserveCache() internal view returns (Agent reserve) {
Cache storage c = cache[msg.sender];
reserve = Agent(c.reserve);
}
function _presaleCache() internal view returns (Presale presale) {
Cache storage c = cache[msg.sender];
presale = Presale(c.presale);
}
function _controllerCache() internal view returns (AragonFundraisingController controller) {
Cache storage c = cache[msg.sender];
controller = AragonFundraisingController(c.controller);
}
/***** internal check functions *****/
function _ensureBoardAppsCache() internal view {
Cache storage c = cache[msg.sender];
require(
c.boardTokenManager != address(0) &&
c.boardVoting != address(0) &&
c.vault != address(0) &&
c.finance != address(0),
ERROR_MISSING_CACHE
);
}
function _ensureShareAppsCache() internal view {
Cache storage c = cache[msg.sender];
require(
c.shareTokenManager != address(0) &&
c.shareVoting != address(0),
ERROR_MISSING_CACHE
);
}
function _ensureFundraisingAppsCache() internal view {
Cache storage c = cache[msg.sender];
require(
c.reserve != address(0) &&
c.presale != address(0) &&
c.marketMaker != address(0) &&
c.tap != address(0) &&
c.controller != address(0),
ERROR_MISSING_CACHE
);
}
/***** internal utils functions *****/
function _registerApp(Kernel _dao, bytes32 _appId) internal returns (address) {
address proxy = _dao.newAppInstance(_appId, _latestVersionAppBase(_appId));
emit InstalledApp(proxy, _appId);
return proxy;
}
} | add y^04 * (20! / 04!)
| z = z * y / FIXED_1; res += z * 0x0168244fdac78000; | 451,585 | [
1,
1289,
677,
66,
3028,
225,
261,
3462,
5,
342,
16486,
24949,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3639,
998,
273,
998,
380,
677,
342,
26585,
67,
21,
31,
400,
1011,
998,
380,
374,
92,
1611,
9470,
3247,
24,
8313,
1077,
8285,
3784,
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
] |
pragma solidity 0.6.6;
// SPDX-License-Identifier: MIT
abstract contract ReentrancyGuard {
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() public {
_status = _NOT_ENTERED;
}
modifier nonReentrant() {
require(_status != _ENTERED, "REENTRANCY_ERROR");
_status = _ENTERED;
_;
_status = _NOT_ENTERED;
}
}
// 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;
}
}
// SPDX-License-Identifier: MIT
/**
* @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: GPL-3.0-or-later
// Interface declarations
/* solhint-disable func-order */
interface IUniswapRouter {
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}
// SPDX-License-Identifier: MIT
interface IHarvestVault {
function deposit(uint256 amount) external;
function withdraw(uint256 numberOfShares) external;
}
// SPDX-License-Identifier: MIT
interface IMintNoRewardPool {
function stake(uint256 amount) external;
function withdraw(uint256 amount) external;
function earned(address account) external view returns (uint256);
function lastTimeRewardApplicable() external view returns (uint256);
function rewardPerToken() external view returns (uint256);
function rewards(address account) external view returns (uint256);
function userRewardPerTokenPaid(address account)
external
view
returns (uint256);
function lastUpdateTime() external view returns (uint256);
function rewardRate() external view returns (uint256);
function totalSupply() external view returns (uint256);
function rewardPerTokenStored() external view returns (uint256);
function periodFinish() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function getReward() external;
}
interface IHarvest {
function setHarvestRewardVault(address _harvestRewardVault) external;
function setHarvestRewardPool(address _harvestRewardPool) external;
function setHarvestPoolToken(address _harvestfToken) external;
function setFarmToken(address _farmToken) external;
function updateReward() external;
}
interface IStrategy {
function setTreasury(address payable _feeAddress) external;
function blacklistAddress(address account) external;
function removeFromBlacklist(address account) external;
function setCap(uint256 _cap) external;
function setLockTime(uint256 _lockTime) external;
function setFeeAddress(address payable _feeAddress) external;
function setFee(uint256 _fee) external;
function rescueDust() external;
function rescueAirdroppedTokens(address _token, address to) external;
function setSushiswapRouter(address _sushiswapRouter) external;
}
// SPDX-License-Identifier: MIT
/**
* @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
/**
* @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
/**
* @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
/**
* @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
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// This contract is used for printing receipt tokens
// Whenever someone joins a pool, a receipt token will be printed for that person
contract ReceiptToken is ERC20, Ownable {
ERC20 public underlyingToken;
address public underlyingStrategy;
constructor(address underlyingAddress, address strategy)
public
ERC20(
string(abi.encodePacked("pAT-", ERC20(underlyingAddress).name())),
string(abi.encodePacked("pAT-", ERC20(underlyingAddress).symbol()))
)
{
underlyingToken = ERC20(underlyingAddress);
underlyingStrategy = strategy;
}
/**
* @notice Mint new receipt tokens to some user
* @param to Address of the user that gets the receipt tokens
* @param amount Amount of receipt tokens that will get minted
*/
function mint(address to, uint256 amount) public onlyOwner {
_mint(to, amount);
}
/**
* @notice Burn receipt tokens from some user
* @param from Address of the user that gets the receipt tokens burne
* @param amount Amount of receipt tokens that will get burned
*/
function burn(address from, uint256 amount) public onlyOwner {
_burn(from, amount);
}
}
// SPDX-License-Identifier: MIT
contract StrategyBase {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IUniswapRouter public sushiswapRouter;
ReceiptToken public receiptToken;
uint256 internal _minSlippage = 10; //0.1%
uint256 public fee = uint256(100);
uint256 constant feeFactor = uint256(10000);
uint256 public cap;
/// @notice Event emitted when user makes a deposit and receipt token is minted
event ReceiptMinted(address indexed user, uint256 amount);
/// @notice Event emitted when user withdraws and receipt token is burned
event ReceiptBurned(address indexed user, uint256 amount);
function _validateCommon(
uint256 deadline,
uint256 amount,
uint256 _slippage
) internal view {
require(deadline >= block.timestamp, "DEADLINE_ERROR");
require(amount > 0, "AMOUNT_0");
require(_slippage >= _minSlippage, "SLIPPAGE_ERROR");
require(_slippage <= feeFactor, "MAX_SLIPPAGE_ERROR");
}
function _validateDeposit(
uint256 deadline,
uint256 amount,
uint256 total,
uint256 slippage
) internal view {
_validateCommon(deadline, amount, slippage);
require(total.add(amount) <= cap, "CAP_REACHED");
}
function _mintParachainAuctionTokens(uint256 _amount) internal {
receiptToken.mint(msg.sender, _amount);
emit ReceiptMinted(msg.sender, _amount);
}
function _burnParachainAuctionTokens(uint256 _amount) internal {
receiptToken.burn(msg.sender, _amount);
emit ReceiptBurned(msg.sender, _amount);
}
function _calculateFee(uint256 _amount) internal view returns (uint256) {
return _calculatePortion(_amount, fee);
}
function _getBalance(address _token) internal view returns (uint256) {
return IERC20(_token).balanceOf(address(this));
}
function _increaseAllowance(
address _token,
address _contract,
uint256 _amount
) internal {
IERC20(_token).safeIncreaseAllowance(address(_contract), _amount);
}
function _getRatio(
uint256 numerator,
uint256 denominator,
uint256 precision
) internal pure returns (uint256) {
if (numerator == 0 || denominator == 0) {
return 0;
}
uint256 _numerator = numerator * 10**(precision + 1);
uint256 _quotient = ((_numerator / denominator) + 5) / 10;
return (_quotient);
}
function _swapTokenToEth(
address[] memory swapPath,
uint256 exchangeAmount,
uint256 deadline,
uint256 slippage,
uint256 ethPerToken
) internal returns (uint256) {
uint256[] memory amounts =
sushiswapRouter.getAmountsOut(exchangeAmount, swapPath);
uint256 sushiAmount = amounts[amounts.length - 1]; //amount of ETH
uint256 portion = _calculatePortion(sushiAmount, slippage);
uint256 calculatedPrice = (exchangeAmount.mul(ethPerToken)).div(10**18);
uint256 decimals = ERC20(swapPath[0]).decimals();
if (decimals < 18) {
calculatedPrice = calculatedPrice.mul(10**(18 - decimals));
}
if (sushiAmount > calculatedPrice) {
require(
sushiAmount.sub(calculatedPrice) <= portion,
"PRICE_ERROR_1"
);
} else {
require(
calculatedPrice.sub(sushiAmount) <= portion,
"PRICE_ERROR_2"
);
}
_increaseAllowance(
swapPath[0],
address(sushiswapRouter),
exchangeAmount
);
uint256[] memory tokenSwapAmounts =
sushiswapRouter.swapExactTokensForETH(
exchangeAmount,
_getMinAmount(sushiAmount, slippage),
swapPath,
address(this),
deadline
);
return tokenSwapAmounts[tokenSwapAmounts.length - 1];
}
function _swapEthToToken(
address[] memory swapPath,
uint256 exchangeAmount,
uint256 deadline,
uint256 slippage,
uint256 tokensPerEth
) internal returns (uint256) {
uint256[] memory amounts =
sushiswapRouter.getAmountsOut(exchangeAmount, swapPath);
uint256 sushiAmount = amounts[amounts.length - 1];
uint256 portion = _calculatePortion(sushiAmount, slippage);
uint256 calculatedPrice =
(exchangeAmount.mul(tokensPerEth)).div(10**18);
uint256 decimals = ERC20(swapPath[0]).decimals();
if (decimals < 18) {
calculatedPrice = calculatedPrice.mul(10**(18 - decimals));
}
if (sushiAmount > calculatedPrice) {
require(
sushiAmount.sub(calculatedPrice) <= portion,
"PRICE_ERROR_1"
);
} else {
require(
calculatedPrice.sub(sushiAmount) <= portion,
"PRICE_ERROR_2"
);
}
uint256[] memory swapResult =
sushiswapRouter.swapExactETHForTokens{value: exchangeAmount}(
_getMinAmount(sushiAmount, slippage),
swapPath,
address(this),
deadline
);
return swapResult[swapResult.length - 1];
}
function _getMinAmount(uint256 amount, uint256 slippage)
private
pure
returns (uint256)
{
uint256 portion = _calculatePortion(amount, slippage);
return amount.sub(portion);
}
function _calculatePortion(uint256 _amount, uint256 _fee)
private
pure
returns (uint256)
{
return (_amount.mul(_fee)).div(feeFactor);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, "TransferHelper: ETH_TRANSFER_FAILED");
}
}
// SPDX-License-Identifier: MIT
contract HarvestBase is Ownable, StrategyBase, IHarvest, IStrategy {
address public token;
address public weth;
address public farmToken;
address public harvestfToken;
address payable public treasuryAddress;
address payable public feeAddress;
uint256 public ethDust;
uint256 public treasueryEthDust;
uint256 public totalDeposits;
uint256 public lockTime = 1;
mapping(address => bool) public blacklisted; //blacklisted users do not receive a receipt token
IMintNoRewardPool public harvestRewardPool;
IHarvestVault public harvestRewardVault;
/// @notice Info of each user.
struct UserInfo {
uint256 amountEth; //how much ETH the user entered with; should be 0 for HarvestSC
uint256 amountToken; //how much Token was obtained by swapping user's ETH
uint256 amountfToken; //how much fToken was obtained after deposit to vault
uint256 amountReceiptToken; //receipt tokens printed for user; should be equal to amountfToken
uint256 underlyingRatio; //ratio between obtained fToken and token
uint256 userTreasuryEth; //how much eth the user sent to treasury
uint256 userCollectedFees; //how much eth the user sent to fee address
bool wasUserBlacklisted; //if user was blacklist at deposit time, he is not receiving receipt tokens
uint256 timestamp; //first deposit timestamp; used for withdrawal lock time check
uint256 earnedTokens;
uint256 earnedRewards; //before fees
//----
uint256 rewards;
uint256 userRewardPerTokenPaid;
}
mapping(address => UserInfo) public userInfo;
struct UserDeposits {
uint256 timestamp;
uint256 amountfToken;
}
/// @notice Used internally for avoiding "stack-too-deep" error when depositing
struct DepositData {
address[] swapPath;
uint256[] swapAmounts;
uint256 obtainedToken;
uint256 obtainedfToken;
uint256 prevfTokenBalance;
}
/// @notice Used internally for avoiding "stack-too-deep" error when withdrawing
struct WithdrawData {
uint256 prevDustEthBalance;
uint256 prevfTokenBalance;
uint256 prevTokenBalance;
uint256 obtainedfToken;
uint256 obtainedToken;
uint256 feeableToken;
uint256 feeableEth;
uint256 totalEth;
uint256 totalToken;
uint256 auctionedEth;
uint256 auctionedToken;
uint256 rewards;
uint256 farmBalance;
uint256 burnAmount;
uint256 earnedTokens;
uint256 rewardsInEth;
uint256 auctionedRewardsInEth;
uint256 userRewardsInEth;
uint256 initialAmountfToken;
}
//-----------------------------------------------------------------------------------------------------------------//
//------------------------------------ Events -------------------------------------------------//
//-----------------------------------------------------------------------------------------------------------------//
event ExtraTokensExchanged(
address indexed user,
uint256 tokensAmount,
uint256 obtainedEth
);
event ObtainedInfo(
address indexed user,
uint256 underlying,
uint256 underlyingReceipt
);
event RewardsEarned(address indexed user, uint256 amount);
event ExtraTokens(address indexed user, uint256 amount);
/// @notice Event emitted when blacklist status for an address changes
event BlacklistChanged(
string actionType,
address indexed user,
bool oldVal,
bool newVal
);
/// @notice Event emitted when owner makes a rescue dust request
event RescuedDust(string indexed dustType, uint256 amount);
/// @notice Event emitted when owner changes any contract address
event ChangedAddress(
string indexed addressType,
address indexed oldAddress,
address indexed newAddress
);
/// @notice Event emitted when owner changes any contract address
event ChangedValue(
string indexed valueType,
uint256 indexed oldValue,
uint256 indexed newValue
);
//-----------------------------------------------------------------------------------------------------------------//
//------------------------------------ Setters -------------------------------------------------//
//-----------------------------------------------------------------------------------------------------------------//
/**
* @notice Update the address of VaultDAI
* @dev Can only be called by the owner
* @param _harvestRewardVault Address of VaultDAI
*/
function setHarvestRewardVault(address _harvestRewardVault)
external
override
onlyOwner
{
require(_harvestRewardVault != address(0), "VAULT_0x0");
emit ChangedAddress(
"VAULT",
address(harvestRewardVault),
_harvestRewardVault
);
harvestRewardVault = IHarvestVault(_harvestRewardVault);
}
/**
* @notice Update the address of NoMintRewardPool
* @dev Can only be called by the owner
* @param _harvestRewardPool Address of NoMintRewardPool
*/
function setHarvestRewardPool(address _harvestRewardPool)
external
override
onlyOwner
{
require(_harvestRewardPool != address(0), "POOL_0x0");
emit ChangedAddress(
"POOL",
address(harvestRewardPool),
_harvestRewardPool
);
harvestRewardPool = IMintNoRewardPool(_harvestRewardPool);
}
/**
* @notice Update the address of Sushiswap Router
* @dev Can only be called by the owner
* @param _sushiswapRouter Address of Sushiswap Router
*/
function setSushiswapRouter(address _sushiswapRouter)
external
override
onlyOwner
{
require(_sushiswapRouter != address(0), "0x0");
emit ChangedAddress(
"SUSHISWAP_ROUTER",
address(sushiswapRouter),
_sushiswapRouter
);
sushiswapRouter = IUniswapRouter(_sushiswapRouter);
}
/**
* @notice Update the address of Pool's underlying token
* @dev Can only be called by the owner
* @param _harvestfToken Address of Pool's underlying token
*/
function setHarvestPoolToken(address _harvestfToken)
external
override
onlyOwner
{
require(_harvestfToken != address(0), "TOKEN_0x0");
emit ChangedAddress("TOKEN", harvestfToken, _harvestfToken);
harvestfToken = _harvestfToken;
}
/**
* @notice Update the address of FARM
* @dev Can only be called by the owner
* @param _farmToken Address of FARM
*/
function setFarmToken(address _farmToken) external override onlyOwner {
require(_farmToken != address(0), "FARM_0x0");
emit ChangedAddress("FARM", farmToken, _farmToken);
farmToken = _farmToken;
}
/**
* @notice Update the address for fees
* @dev Can only be called by the owner
* @param _feeAddress Fee's address
*/
function setTreasury(address payable _feeAddress)
external
override
onlyOwner
{
require(_feeAddress != address(0), "0x0");
emit ChangedAddress(
"TREASURY",
address(treasuryAddress),
address(_feeAddress)
);
treasuryAddress = _feeAddress;
}
/**
* @notice Blacklist address; blacklisted addresses do not receive receipt tokens
* @dev Can only be called by the owner
* @param account User/contract address
*/
function blacklistAddress(address account) external override onlyOwner {
require(account != address(0), "0x0");
emit BlacklistChanged("BLACKLIST", account, blacklisted[account], true);
blacklisted[account] = true;
}
/**
* @notice Remove address from blacklisted addresses; blacklisted addresses do not receive receipt tokens
* @dev Can only be called by the owner
* @param account User/contract address
*/
function removeFromBlacklist(address account) external override onlyOwner {
require(account != address(0), "0x0");
emit BlacklistChanged("REMOVE", account, blacklisted[account], false);
blacklisted[account] = false;
}
/**
* @notice Set max ETH cap for this strategy
* @dev Can only be called by the owner
* @param _cap ETH amount
*/
function setCap(uint256 _cap) external override onlyOwner {
emit ChangedValue("CAP", cap, _cap);
cap = _cap;
}
/**
* @notice Set lock time
* @dev Can only be called by the owner
* @param _lockTime lock time in seconds
*/
function setLockTime(uint256 _lockTime) external override onlyOwner {
require(_lockTime > 0, "TIME_0");
emit ChangedValue("LOCKTIME", lockTime, _lockTime);
lockTime = _lockTime;
}
function setFeeAddress(address payable _feeAddress)
external
override
onlyOwner
{
emit ChangedAddress("FEE", address(feeAddress), address(_feeAddress));
feeAddress = _feeAddress;
}
function setFee(uint256 _fee) external override onlyOwner {
require(_fee <= uint256(9000), "FEE_TOO_HIGH");
emit ChangedValue("FEE", fee, _fee);
}
/**
* @notice Rescue dust resulted from swaps/liquidity
* @dev Can only be called by the owner
*/
function rescueDust() external override onlyOwner {
if (ethDust > 0) {
safeTransferETH(treasuryAddress, ethDust);
treasueryEthDust = treasueryEthDust.add(ethDust);
emit RescuedDust("ETH", ethDust);
ethDust = 0;
}
}
/**
* @notice Rescue any non-reward token that was airdropped to this contract
* @dev Can only be called by the owner
*/
function rescueAirdroppedTokens(address _token, address to)
external
override
onlyOwner
{
require(_token != address(0), "token_0x0");
require(to != address(0), "to_0x0");
require(_token != farmToken, "rescue_reward_error");
uint256 balanceOfToken = IERC20(_token).balanceOf(address(this));
require(balanceOfToken > 0, "balance_0");
require(IERC20(_token).transfer(to, balanceOfToken), "rescue_failed");
}
/// @notice Transfer rewards to this strategy
function updateReward() external override onlyOwner {
harvestRewardPool.getReward();
}
//-----------------------------------------------------------------------------------------------------------------//
//------------------------------------ View methods -------------------------------------------------//
//-----------------------------------------------------------------------------------------------------------------//
/**
* @notice Check if user can withdraw based on current lock time
* @param user Address of the user
* @return true or false
*/
function isWithdrawalAvailable(address user) public view returns (bool) {
if (lockTime > 0) {
return userInfo[user].timestamp.add(lockTime) <= block.timestamp;
}
return true;
}
/**
* @notice View function to see pending rewards for account.
* @param account user account to check
* @return pending rewards
*/
function getPendingRewards(address account) public view returns (uint256) {
if (account != address(0)) {
if (userInfo[account].amountfToken == 0) {
return 0;
}
return
_earned(
userInfo[account].amountfToken,
userInfo[account].userRewardPerTokenPaid,
userInfo[account].rewards
);
}
return 0;
}
//-----------------------------------------------------------------------------------------------------------------//
//------------------------------------ Internal methods -------------------------------------------------//
//-----------------------------------------------------------------------------------------------------------------//
function _calculateRewards(
address account,
uint256 amount,
uint256 amountfToken
) internal view returns (uint256) {
uint256 rewards = userInfo[account].rewards;
uint256 farmBalance = IERC20(farmToken).balanceOf(address(this));
if (amount == 0) {
if (rewards < farmBalance) {
return rewards;
}
return farmBalance;
}
return (amount.mul(rewards)).div(amountfToken);
}
function _updateRewards(address account) internal {
if (account != address(0)) {
UserInfo storage user = userInfo[account];
uint256 _stored = harvestRewardPool.rewardPerToken();
user.rewards = _earned(
user.amountfToken,
user.userRewardPerTokenPaid,
user.rewards
);
user.userRewardPerTokenPaid = _stored;
}
}
function _earned(
uint256 _amountfToken,
uint256 _userRewardPerTokenPaid,
uint256 _rewards
) internal view returns (uint256) {
return
_amountfToken
.mul(
harvestRewardPool.rewardPerToken().sub(_userRewardPerTokenPaid)
)
.div(1e18)
.add(_rewards);
}
function _validateWithdraw(
uint256 deadline,
uint256 amount,
uint256 amountfToken,
uint256 receiptBalance,
uint256 amountReceiptToken,
bool wasUserBlacklisted,
uint256 timestamp,
uint256 slippage
) internal view {
_validateCommon(deadline, amount, slippage);
require(amountfToken >= amount, "AMOUNT_GREATER_THAN_BALANCE");
if (!wasUserBlacklisted) {
require(receiptBalance >= amountReceiptToken, "RECEIPT_AMOUNT");
}
if (lockTime > 0) {
require(timestamp.add(lockTime) <= block.timestamp, "LOCK_TIME");
}
}
function _depositTokenToHarvestVault(uint256 amount)
internal
returns (uint256)
{
_increaseAllowance(token, address(harvestRewardVault), amount);
uint256 prevfTokenBalance = _getBalance(harvestfToken);
harvestRewardVault.deposit(amount);
uint256 currentfTokenBalance = _getBalance(harvestfToken);
require(
currentfTokenBalance > prevfTokenBalance,
"DEPOSIT_VAULT_ERROR"
);
return currentfTokenBalance.sub(prevfTokenBalance);
}
function _withdrawTokenFromHarvestVault(uint256 amount)
internal
returns (uint256)
{
_increaseAllowance(harvestfToken, address(harvestRewardVault), amount);
uint256 prevTokenBalance = _getBalance(token);
harvestRewardVault.withdraw(amount);
uint256 currentTokenBalance = _getBalance(token);
require(currentTokenBalance > prevTokenBalance, "WITHDRAW_VAULT_ERROR");
return currentTokenBalance.sub(prevTokenBalance);
}
function _stakefTokenToHarvestPool(uint256 amount) internal {
_increaseAllowance(harvestfToken, address(harvestRewardPool), amount);
harvestRewardPool.stake(amount);
}
function _unstakefTokenFromHarvestPool(uint256 amount)
internal
returns (uint256)
{
_increaseAllowance(harvestfToken, address(harvestRewardPool), amount);
uint256 prevfTokenBalance = _getBalance(harvestfToken);
harvestRewardPool.withdraw(amount);
uint256 currentfTokenBalance = _getBalance(harvestfToken);
require(
currentfTokenBalance > prevfTokenBalance,
"WITHDRAW_POOL_ERROR"
);
return currentfTokenBalance.sub(prevfTokenBalance);
}
function _calculatefTokenRemainings(
uint256 obtainedfToken,
uint256 amountfToken,
bool wasUserBlacklisted,
uint256 amountReceiptToken
)
internal
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 burnAmount = 0;
if (obtainedfToken < amountfToken) {
amountfToken = amountfToken.sub(obtainedfToken);
if (!wasUserBlacklisted) {
amountReceiptToken = amountReceiptToken.sub(obtainedfToken);
burnAmount = obtainedfToken;
}
} else {
amountfToken = 0;
if (!wasUserBlacklisted) {
burnAmount = amountReceiptToken;
amountReceiptToken = 0;
}
}
return (amountfToken, amountReceiptToken, burnAmount);
}
event log(string s);
event log(uint256 amount);
function _calculateFeeableTokens(
uint256 amount,
uint256 amountfToken,
uint256 obtainedToken,
uint256 amountToken,
uint256 obtainedfToken,
uint256 underlyingRatio
) internal returns (uint256 feeableToken, uint256 earnedTokens) {
emit log("_calculateFeeableTokens");
emit log(amount);
emit log(amountfToken);
emit log(obtainedToken);
emit log(amountToken);
if (amount == amountfToken) {
//there is no point to do the ratio math as we can just get the difference between current obtained tokens and initial obtained tokens
if (obtainedToken > amountToken) {
feeableToken = obtainedToken.sub(amountToken);
}
} else {
uint256 currentRatio = _getRatio(obtainedfToken, obtainedToken, 18);
if (currentRatio < underlyingRatio) {
uint256 noOfOriginalTokensForCurrentAmount =
(amount.mul(10**18)).div(underlyingRatio);
if (noOfOriginalTokensForCurrentAmount < obtainedToken) {
feeableToken = obtainedToken.sub(
noOfOriginalTokensForCurrentAmount
);
}
}
}
emit log("_calculateFeeableTokens end");
emit log(feeableToken);
if (feeableToken > 0) {
uint256 extraTokensFee = _calculateFee(feeableToken);
emit ExtraTokens(msg.sender, feeableToken.sub(extraTokensFee));
earnedTokens = feeableToken.sub(extraTokensFee);
}
}
receive() external payable {}
}
// SPDX-License-Identifier: MIT
contract HarvestSCBase is StrategyBase, HarvestBase {
uint256 public totalToken; //total invested eth
//-----------------------------------------------------------------------------------------------------------------//
//------------------------------------ Events -------------------------------------------------//
//-----------------------------------------------------------------------------------------------------------------//
/// @notice Event emitted when rewards are exchanged to ETH or to a specific Token
event RewardsExchanged(
address indexed user,
string exchangeType, //ETH or Token
uint256 rewardsAmount,
uint256 obtainedAmount
);
/// @notice Event emitted when user makes a deposit
event Deposit(
address indexed user,
address indexed origin,
uint256 amountToken,
uint256 amountfToken
);
/// @notice Event emitted when user withdraws
event Withdraw(
address indexed user,
address indexed origin,
uint256 amountToken,
uint256 amountfToken,
uint256 treasuryAmountEth
);
}
// SPDX-License-Identifier: MIT
/*
|Strategy Flow|
- User shows up with Token and we deposit it in Havest's Vault.
- After this we have fToken that we add in Harvest's Reward Pool which gives FARM as rewards
- Withdrawal flow does same thing, but backwards
- User can obtain extra Token when withdrawing. 50% of them goes to the user, 50% goes to the treasury in ETH
- User can obtain FARM tokens when withdrawing. 50% of them goes to the user in Token, 50% goes to the treasury in ETH
*/
contract HarvestSC is HarvestSCBase, ReentrancyGuard {
/**
* @notice Create a new HarvestDAI contract
* @param _harvestRewardVault VaultDAI address
* @param _harvestRewardPool NoMintRewardPool address
* @param _sushiswapRouter Sushiswap Router address
* @param _harvestfToken Pool's underlying token address
* @param _farmToken Farm address
* @param _token Token address
* @param _weth WETH address
* @param _treasuryAddress treasury address
* @param _feeAddress fee address
*/
constructor(
address _harvestRewardVault,
address _harvestRewardPool,
address _sushiswapRouter,
address _harvestfToken,
address _farmToken,
address _token,
address _weth,
address payable _treasuryAddress,
address payable _feeAddress
) public {
require(_harvestRewardVault != address(0), "VAULT_0x0");
require(_harvestRewardPool != address(0), "POOL_0x0");
require(_sushiswapRouter != address(0), "ROUTER_0x0");
require(_harvestfToken != address(0), "fTOKEN_0x0");
require(_farmToken != address(0), "FARM_0x0");
require(_token != address(0), "TOKEN_0x0");
require(_weth != address(0), "WETH_0x0");
require(_treasuryAddress != address(0), "TREASURY_0x0");
require(_feeAddress != address(0), "FEE_0x0");
harvestRewardVault = IHarvestVault(_harvestRewardVault);
harvestRewardPool = IMintNoRewardPool(_harvestRewardPool);
sushiswapRouter = IUniswapRouter(_sushiswapRouter);
harvestfToken = _harvestfToken;
farmToken = _farmToken;
token = _token;
weth = _weth;
treasuryAddress = _treasuryAddress;
receiptToken = new ReceiptToken(token, address(this));
feeAddress = _feeAddress;
cap = 5000000 * (10 ** 18);
}
/**
* @notice Deposit to this strategy for rewards
* @param tokenAmount Amount of Token investment
* @param deadline Number of blocks until transaction expires
* @return Amount of fToken
*/
function deposit(
uint256 tokenAmount,
uint256 deadline,
uint256 slippage
) public nonReentrant returns (uint256) {
// -----
// validate
// -----
_validateDeposit(deadline, tokenAmount, totalToken, slippage);
_updateRewards(msg.sender);
IERC20(token).safeTransferFrom(msg.sender, address(this), tokenAmount);
DepositData memory results;
UserInfo storage user = userInfo[msg.sender];
if (user.amountfToken == 0) {
user.wasUserBlacklisted = blacklisted[msg.sender];
}
if (user.timestamp == 0) {
user.timestamp = block.timestamp;
}
totalToken = totalToken.add(tokenAmount);
user.amountToken = user.amountToken.add(tokenAmount);
results.obtainedToken = tokenAmount;
// -----
// deposit Token into harvest and get fToken
// -----
results.obtainedfToken = _depositTokenToHarvestVault(
results.obtainedToken
);
// -----
// stake fToken into the NoMintRewardPool
// -----
_stakefTokenToHarvestPool(results.obtainedfToken);
user.amountfToken = user.amountfToken.add(results.obtainedfToken);
// -----
// mint parachain tokens if user is not blacklisted
// -----
if (!user.wasUserBlacklisted) {
user.amountReceiptToken = user.amountReceiptToken.add(
results.obtainedfToken
);
_mintParachainAuctionTokens(results.obtainedfToken);
}
emit Deposit(
msg.sender,
tx.origin,
results.obtainedToken,
results.obtainedfToken
);
totalDeposits = totalDeposits.add(results.obtainedfToken);
user.underlyingRatio = _getRatio(
user.amountfToken,
user.amountToken,
18
);
return results.obtainedfToken;
}
/**
* @notice Withdraw tokens and claim rewards
* @param deadline Number of blocks until transaction expires
* @return Amount of ETH obtained
*/
function withdraw(
uint256 amount,
uint256 deadline,
uint256 slippage,
uint256 ethPerToken,
uint256 ethPerFarm,
uint256 tokensPerEth //no of tokens per 1 eth
) public nonReentrant returns (uint256) {
// -----
// validation
// -----
UserInfo storage user = userInfo[msg.sender];
uint256 receiptBalance = receiptToken.balanceOf(msg.sender);
_validateWithdraw(
deadline,
amount,
user.amountfToken,
receiptBalance,
user.amountReceiptToken,
user.wasUserBlacklisted,
user.timestamp,
slippage
);
_updateRewards(msg.sender);
WithdrawData memory results;
results.initialAmountfToken = user.amountfToken;
results.prevDustEthBalance = address(this).balance;
// -----
// withdraw from HarvestRewardPool (get fToken back)
// -----
results.obtainedfToken = _unstakefTokenFromHarvestPool(amount);
// -----
// get rewards
// -----
harvestRewardPool.getReward(); //transfers FARM to this contract
// -----
// calculate rewards and do the accounting for fTokens
// -----
uint256 transferableRewards =
_calculateRewards(msg.sender, amount, results.initialAmountfToken);
(
user.amountfToken,
user.amountReceiptToken,
results.burnAmount
) = _calculatefTokenRemainings(
results.obtainedfToken,
results.initialAmountfToken,
user.wasUserBlacklisted,
user.amountReceiptToken
);
_burnParachainAuctionTokens(results.burnAmount);
// -----
// withdraw from HarvestRewardVault (return fToken and get Token back)
// -----
results.obtainedToken = _withdrawTokenFromHarvestVault(
results.obtainedfToken
);
emit ObtainedInfo(
msg.sender,
results.obtainedToken,
results.obtainedfToken
);
totalDeposits = totalDeposits.sub(results.obtainedfToken);
// -----
// calculate feeable tokens (extra Token obtained by returning fToken)
// - feeableToken/2 (goes to the treasury in ETH)
// - results.totalToken = obtainedToken + 1/2*feeableToken (goes to the user)
// -----
results.auctionedToken = 0;
(results.feeableToken, results.earnedTokens) = _calculateFeeableTokens(
amount,
results.initialAmountfToken,
results.obtainedToken,
user.amountToken,
results.obtainedfToken,
user.underlyingRatio
);
user.earnedTokens = user.earnedTokens.add(results.earnedTokens);
if (results.obtainedToken <= user.amountToken) {
user.amountToken = user.amountToken.sub(results.obtainedToken);
} else {
user.amountToken = 0;
}
results.obtainedToken = results.obtainedToken.sub(results.feeableToken);
if (results.feeableToken > 0) {
results.auctionedToken = results.feeableToken.div(2);
results.feeableToken = results.feeableToken.sub(
results.auctionedToken
);
}
results.totalToken = results.obtainedToken.add(results.feeableToken);
// -----
// swap auctioned Token to ETH
// -----
address[] memory swapPath = new address[](2);
swapPath[0] = token;
swapPath[1] = weth;
if (results.auctionedToken > 0) {
uint256 swapAuctionedTokenResult =
_swapTokenToEth(
swapPath,
results.auctionedToken,
deadline,
slippage,
ethPerToken
);
results.auctionedEth.add(swapAuctionedTokenResult);
emit ExtraTokensExchanged(
msg.sender,
results.auctionedToken,
swapAuctionedTokenResult
);
}
// -----
// check & swap FARM rewards with ETH (50% for treasury) and with Token by going through ETH first (the other 50% for user)
// -----
if (transferableRewards > 0) {
emit RewardsEarned(msg.sender, transferableRewards);
user.earnedRewards = user.earnedRewards.add(transferableRewards);
swapPath[0] = farmToken;
results.rewardsInEth = _swapTokenToEth(
swapPath,
transferableRewards,
deadline,
slippage,
ethPerFarm
);
results.auctionedRewardsInEth = results.rewardsInEth.div(2);
//50% goes to treasury in ETH
results.userRewardsInEth = results.rewardsInEth.sub(
results.auctionedRewardsInEth
);
//50% goes to user in Token (swapped below)
results.auctionedEth = results.auctionedEth.add(
results.auctionedRewardsInEth
);
emit RewardsExchanged(
msg.sender,
"ETH",
transferableRewards,
results.rewardsInEth
);
}
if (results.userRewardsInEth > 0) {
swapPath[0] = weth;
swapPath[1] = token;
uint256 userRewardsEthToTokenResult =
_swapEthToToken(
swapPath,
results.userRewardsInEth,
deadline,
slippage,
tokensPerEth
);
results.totalToken = results.totalToken.add(
userRewardsEthToTokenResult
);
emit RewardsExchanged(
msg.sender,
"Token",
transferableRewards.div(2),
userRewardsEthToTokenResult
);
}
user.rewards = user.rewards.sub(transferableRewards);
// -----
// final accounting
// -----
if (results.totalToken < totalToken) {
totalToken = totalToken.sub(results.totalToken);
} else {
totalToken = 0;
}
if (user.amountfToken == 0) {
user.amountToken = 0; //1e-18 dust
}
user.underlyingRatio = _getRatio(
user.amountfToken,
user.amountToken,
18
);
// -----
// transfer Token to user, ETH to fee address and ETH to the treasury address
// -----
if (fee > 0) {
uint256 feeToken = _calculateFee(results.totalToken);
results.totalToken = results.totalToken.sub(feeToken);
swapPath[0] = token;
swapPath[1] = weth;
uint256 feeTokenInEth =
_swapTokenToEth(
swapPath,
feeToken,
deadline,
slippage,
ethPerToken
);
safeTransferETH(feeAddress, feeTokenInEth);
user.userCollectedFees = user.userCollectedFees.add(feeTokenInEth);
}
IERC20(token).safeTransfer(msg.sender, results.totalToken);
safeTransferETH(treasuryAddress, results.auctionedEth);
user.userTreasuryEth = user.userTreasuryEth.add(results.auctionedEth);
emit Withdraw(
msg.sender,
tx.origin,
results.obtainedToken,
results.obtainedfToken,
results.auctionedEth
);
// -----
// dust check
// -----
if (address(this).balance > results.prevDustEthBalance) {
ethDust = ethDust.add(
address(this).balance.sub(results.prevDustEthBalance)
);
}
return results.totalToken;
}
} | This contract is used for printing receipt tokens Whenever someone joins a pool, a receipt token will be printed for that person | contract ReceiptToken is ERC20, Ownable {
ERC20 public underlyingToken;
address public underlyingStrategy;
constructor(address underlyingAddress, address strategy)
public
ERC20(
string(abi.encodePacked("pAT-", ERC20(underlyingAddress).name())),
string(abi.encodePacked("pAT-", ERC20(underlyingAddress).symbol()))
)
{
underlyingToken = ERC20(underlyingAddress);
underlyingStrategy = strategy;
}
function mint(address to, uint256 amount) public onlyOwner {
_mint(to, amount);
}
function burn(address from, uint256 amount) public onlyOwner {
_burn(from, amount);
}
}
| 14,857,442 | [
1,
2503,
6835,
353,
1399,
364,
19171,
16030,
2430,
3497,
4009,
502,
18626,
13471,
279,
2845,
16,
279,
16030,
1147,
903,
506,
14099,
364,
716,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
29787,
1345,
353,
4232,
39,
3462,
16,
14223,
6914,
288,
203,
565,
4232,
39,
3462,
1071,
6808,
1345,
31,
203,
565,
1758,
1071,
6808,
4525,
31,
203,
203,
565,
3885,
12,
2867,
6808,
1887,
16,
1758,
6252,
13,
203,
3639,
1071,
203,
3639,
4232,
39,
3462,
12,
203,
5411,
533,
12,
21457,
18,
3015,
4420,
329,
2932,
84,
789,
17,
3113,
4232,
39,
3462,
12,
9341,
6291,
1887,
2934,
529,
10756,
3631,
203,
5411,
533,
12,
21457,
18,
3015,
4420,
329,
2932,
84,
789,
17,
3113,
4232,
39,
3462,
12,
9341,
6291,
1887,
2934,
7175,
1435,
3719,
203,
3639,
262,
203,
565,
288,
203,
3639,
6808,
1345,
273,
4232,
39,
3462,
12,
9341,
6291,
1887,
1769,
203,
3639,
6808,
4525,
273,
6252,
31,
203,
565,
289,
203,
203,
565,
445,
312,
474,
12,
2867,
358,
16,
2254,
5034,
3844,
13,
1071,
1338,
5541,
288,
203,
3639,
389,
81,
474,
12,
869,
16,
3844,
1769,
203,
565,
289,
203,
203,
565,
445,
18305,
12,
2867,
628,
16,
2254,
5034,
3844,
13,
1071,
1338,
5541,
288,
203,
3639,
389,
70,
321,
12,
2080,
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
] |
//SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "../interfaces/IEternalFund.sol";
import "../interfaces/IEternalStorage.sol";
import "../interfaces/ITimelock.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/Context.sol";
/**
* @title The Eternal Fund contract
* @author Taken from Compound Finance (COMP) and tweaked/detailed by Nobody (me)
* @notice The Eternal Fund serves as the governing body of Eternal
*/
contract EternalFund is IEternalFund, Context {
/////–––««« Variables: Interfaces and Addresses »»»––––\\\\\
// The name of this contract
string public constant name = "Eternal Fund";
// The keccak256 hash of the Eternal Token address
bytes32 public immutable entity;
// The timelock interface
ITimelock public timelock;
// The Eternal token interface
IERC20 public eternal;
// The Eternal storage interface
IEternalStorage public eternalStorage;
// The address of the Governor Guardian
address public guardian;
/////–––««« Variable: Voting »»»––––\\\\\
// The total number of proposals
uint256 public proposalCount;
// Holds all proposal data
struct Proposal {
uint256 id; // Unique id for looking up a proposal
address proposer; // Creator of the proposal
uint256 eta; // The timestamp that the proposal will be available for execution, set once the vote succeeds
address[] targets; // The ordered list of target addresses for calls to be made
uint256[] values; // The ordered list of values (i.e. msg.value) to be passed to the calls to be made
string[] signatures; // The ordered list of function signatures to be called
bytes[] calldatas; // The ordered list of calldata to be passed to each call
uint256 startTime; // The timestamp at which voting begins: holders must delegate their votes prior to this time
uint256 endTime; // The timestamp at which voting ends: votes must be cast prior to this block
uint256 startBlock; // The block at which voting began: holders must have delegated their votes prior to this block
uint256 forVotes; // Current number of votes in favor of this proposal
uint256 againstVotes; // Current number of votes in opposition to this proposal
bool canceled; // Flag marking whether the proposal has been canceled
bool executed; // Flag marking whether the proposal has been executed
mapping (address => Receipt) receipts; // Receipts of ballots for the entire set of voters
}
// Ballot receipt record for a voter
struct Receipt {
bool hasVoted; // Whether or not a vote has been cast
bool support; // Whether or not the voter supports the proposal
uint256 votes; // The number of votes the voter had, which were cast
}
// Possible states that a proposal may be in
enum ProposalState {
Pending,
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed
}
// The official record of all proposals ever proposed
mapping (uint256 => Proposal) public proposals;
// The latest proposal for each proposer
mapping (address => uint256) public latestProposalIds;
/////–––««« Variables: Voting by signature »»»––––\\\\\
// The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
// The EIP-712 typehash for the ballot struct used by the contract
bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,bool support)");
/////–––««« Events »»»––––\\\\\
// Emitted when a new proposal is created
event ProposalCreated(uint256 id, address proposer, address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, uint256 startTime, uint256 endTime, string description);
// Emitted when the first vote is cast in a proposal
event StartBlockSet(uint256 proposalId, uint256 startBlock);
// Emitted when a vote has been cast on a proposal
event VoteCast(address voter, uint256 proposalId, bool support, uint256 votes);
// Emitted when a proposal has been canceled
event ProposalCanceled(uint256 id);
// Emitted when a proposal has been queued in the Timelock
event ProposalQueued(uint256 id, uint256 eta);
// Emitted when a proposal has been executed in the Timelock
event ProposalExecuted(uint256 id);
/////–––««« Constructor »»»––––\\\\\
constructor (address _guardian, address _eternalStorage, address _eternal, address _timelock) {
guardian = _guardian;
eternalStorage = IEternalStorage(_eternalStorage);
eternal = IERC20(_eternal);
timelock = ITimelock(_timelock);
entity = keccak256(abi.encodePacked(_eternal));
}
/////–––««« Variable state-inspection functions »»»––––\\\\\
/**
* @notice The number of votes required in order for a voter to become a proposer.
* @return 0.5 percent of the initial supply
*/
function proposalThreshold() public pure returns (uint256) {
return 5 * (10 ** 7) * (10 ** 18); // 50 000 000ETRNL = initially 0.5% (increases over time due to deflation)
}
/**
* @notice View the maximum number of operations that can be included in a proposal.
* @return The maximum number of actions per proposal
*/
function proposalMaxOperations() public pure returns (uint256) {
return 15;
}
/**
* @notice View the delay before voting on a proposal may take place, once proposed.
* @return 1 day (in seconds)
*/
function votingDelay() public pure returns (uint256) {
return 1 days;
}
/**
* @notice The duration of voting on a proposal, in blocks.
* @return 3 days (in seconds)
*/
function votingPeriod() public pure returns (uint256) {
return 3 days;
}
/////–––««« Governance logic functions »»»––––\\\\\
/**
* @notice Initiates a proposal.
* @param targets An ordered list of contract addresses used to make the calls
* @param values A list of values passed in each call
* @param signatures A list of function signatures used to make the calls
* @param calldatas A list of function parameter hashes used to make the calls
* @param description A description of the proposal
* @return The current proposal count
*
* Requirements:
*
* - Proposer must have a voting balance equal to at least 0.5 percent of the initial ETRNL supply
* - All lists must have the same length
* - Lists must contain at least one element but no more than 15 elements
* - Proposer can only have one live proposal at a time
*/
function propose(address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint256) {
require(getPriorVotes(msg.sender, block.number - 1) > proposalThreshold(), "Vote balance below threshold");
require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "Arity mismatch in proposal");
require(targets.length != 0, "Must provide actions");
require(targets.length <= proposalMaxOperations(), "Too many actions");
uint256 latestProposalId = latestProposalIds[msg.sender];
if (latestProposalId != 0) {
ProposalState proposersLatestProposalState = state(latestProposalId);
require(proposersLatestProposalState != ProposalState.Active && proposersLatestProposalState != ProposalState.Pending, "One live proposal per proposer");
}
uint256 startTime = block.timestamp + votingDelay();
uint256 endTime = block.timestamp + votingPeriod() + votingDelay();
proposalCount += 1;
proposals[proposalCount].id = proposalCount;
proposals[proposalCount].proposer = msg.sender;
proposals[proposalCount].eta = 0;
proposals[proposalCount].targets = targets;
proposals[proposalCount].values = values;
proposals[proposalCount].signatures = signatures;
proposals[proposalCount].calldatas = calldatas;
proposals[proposalCount].startTime = startTime;
proposals[proposalCount].startBlock = 0;
proposals[proposalCount].endTime = endTime;
proposals[proposalCount].forVotes = 0;
proposals[proposalCount].againstVotes = 0;
proposals[proposalCount].canceled = false;
proposals[proposalCount].executed = false;
latestProposalIds[msg.sender] = proposalCount;
emit ProposalCreated(proposalCount, msg.sender, targets, values, signatures, calldatas, startTime, endTime, description);
return proposalCount;
}
/**
* @notice Queues all of a given proposal's actions into the timelock contract.
* @param proposalId The id of the specified proposal
*
* Requirements:
*
* - The proposal needs to have passed
*/
function queue(uint256 proposalId) public {
require(state(proposalId) == ProposalState.Succeeded, "Proposal state must be Succeeded");
Proposal storage proposal = proposals[proposalId];
uint256 eta = block.timestamp + timelock.viewDelay();
for (uint256 i = 0; i < proposal.targets.length; i++) {
_queueOrRevert(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta);
}
proposal.eta = eta;
emit ProposalQueued(proposalId, eta);
}
/**
* @notice Queues an individual proposal action into the timelock contract.
* @param target The address of the contract whose function is being called
* @param value The amount of AVAX being transferred in this transaction
* @param signature The function signature of this proposal's action
* @param data The function parameters of this proposal's action
* @param eta The estimated minimum UNIX time (in seconds) at which this transaction is to be executed
*
* Requirements:
*
* - The transaction should not have been queued
*/
function _queueOrRevert(address target, uint256 value, string memory signature, bytes memory data, uint256 eta) private {
require(!timelock.queuedTransaction(keccak256(abi.encode(target, value, signature, data, eta))), "Proposal action already queued");
timelock.queueTransaction(target, value, signature, data, eta);
}
/**
* @notice Executes all of a given's proposal's actions.
* @param proposalId The id of the specified proposal
*
* Requirements:
*
* - The proposal must already be in queue
*/
function execute(uint256 proposalId) public payable {
require(state(proposalId) == ProposalState.Queued, "Proposal is not queued");
Proposal storage proposal = proposals[proposalId];
proposal.executed = true;
for (uint256 i = 0; i < proposal.targets.length; i++) {
timelock.executeTransaction{value: proposal.values[i]}(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalExecuted(proposalId);
}
/**
* @notice Cancels all of a given proposal's actions.
* @param proposalId The id of the specified proposal
*
* Requirements:
*
* - The proposal should not have been executed
* - The proposer's vote balance should be below the threshold
*/
function cancel(uint proposalId) public {
ProposalState _state = state(proposalId);
require(_state != ProposalState.Executed, "Cannot cancel executed proposal");
Proposal storage proposal = proposals[proposalId];
require(getPriorVotes(proposal.proposer, block.number - 1) < proposalThreshold(), "Proposer above threshold");
proposal.canceled = true;
for (uint256 i = 0; i < proposal.targets.length; i++) {
timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalCanceled(proposalId);
}
/**
* @notice View a given proposal's lists of actions.
* @param proposalId The id of the specified proposal
* @return targets The proposal's targets
* @return values The proposal's values
* @return signatures The proposal's signatures
* @return calldatas The proposal's calldatas
*/
function getActions(uint256 proposalId) public view returns (address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas) {
Proposal storage p = proposals[proposalId];
return (p.targets, p.values, p.signatures, p.calldatas);
}
/**
* @notice View a given proposal's ballot receipt for a given voter.
* @param proposalId The id of the specified proposal
* @param voter The address of the specified voter
* @return The ballot receipt of that voter for the proposal
*/
function getReceipt(uint256 proposalId, address voter) public view returns (Receipt memory) {
return proposals[proposalId].receipts[voter];
}
/**
* @notice View the state of a given proposal.
* @param proposalId The id of the specified proposal
* @return The state of the proposal
*
* Requirements:
*
* - Proposal must exist
*/
function state(uint256 proposalId) public view returns (ProposalState) {
require(proposalCount >= proposalId && proposalId > 0, "Invalid proposal id");
Proposal storage proposal = proposals[proposalId];
if (proposal.canceled) {
return ProposalState.Canceled;
} else if (block.timestamp <= proposal.startTime) {
return ProposalState.Pending;
} else if (block.timestamp <= proposal.endTime) {
return ProposalState.Active;
} else if (proposal.forVotes <= proposal.againstVotes) {
return ProposalState.Defeated;
} else if (proposal.eta == 0) {
return ProposalState.Succeeded;
} else if (proposal.executed) {
return ProposalState.Executed;
} else if (block.timestamp >= proposal.eta + timelock.viewGracePeriod()) {
return ProposalState.Expired;
} else {
return ProposalState.Queued;
}
}
/**
* @notice Casts a vote for a given proposal.
* @param proposalId The id of the specified proposal
* @param support Whether the user is in support of the proposal or not
*/
function castVote(uint256 proposalId, bool support) public {
return _castVote(msg.sender, proposalId, support);
}
/**
* @notice Casts a vote through signature.
* @param proposalId The id of teh specified proposal
* @param support Whether the user is in support of the proposal or not
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*
* Requirements:
*
* - Must be a valid signature
*/
function castVoteBySig(uint256 proposalId, bool support, uint8 v, bytes32 r, bytes32 s) public {
uint chainId;
// solhint-disable-next-line no-inline-assembly
assembly { chainId := chainid() }
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), chainId, address(this)));
bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Invalid signature");
return _castVote(signatory, proposalId, support);
}
/**
* @notice Casts a vote for a given voter and proposal.
* @param voter The address of the specified voter
* @param proposalId The id of the specified proposal
* @param support Whether the voter is in support of the proposal or not
*
* Requirements:
*
* - Voting period for the proposal needs to be ongoing
* - The voter must not have already voted
*/
function _castVote(address voter, uint256 proposalId, bool support) private {
require(state(proposalId) == ProposalState.Active, "Voting is closed");
Proposal storage proposal = proposals[proposalId];
if (proposal.startBlock == 0) {
proposal.startBlock = block.number - 1;
emit StartBlockSet(proposalId, block.number);
}
Receipt storage receipt = proposal.receipts[voter];
require(receipt.hasVoted == false, "Voter already voted");
uint256 votes = getPriorVotes(voter, proposal.startBlock);
if (support) {
proposal.forVotes = proposal.forVotes + votes;
} else {
proposal.againstVotes = proposal.againstVotes + votes;
}
receipt.hasVoted = true;
receipt.support = support;
receipt.votes = votes;
emit VoteCast(voter, proposalId, support, votes);
}
/**
* @notice Allow the Eternal Fund to take over control of the timelock contract.
*
* Requirements:
*
* - Only callable by the current guardian
*/
function __acceptFund() public {
require(msg.sender == guardian, "Caller must be the guardian");
timelock.acceptFund();
}
/**
* @notice Renounce the role of guardianship.
*
* Requirements:
*
* - Only callable by the current guardian
*/
function __abdicate() public {
require(msg.sender == guardian, "Caller must be the guardian");
guardian = address(0);
}
/**
* @notice Queues the transaction which will give governing power to the Eternal Fund.
*
* Requirements:
*
* - Only callable by the current guardian
*/
function __queueSetTimelockPendingAdmin(address newPendingAdmin, uint256 eta) public {
require(msg.sender == guardian, "Caller must be the guardian");
timelock.queueTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta);
}
/**
* @notice Executes the transaction which will give governing power to the Eternal Fund.
*
* Requirements:
*
* - Only callable by the current guardian
*/
function __executeSetTimelockPendingAdmin(address newPendingAdmin, uint256 eta) public {
require(msg.sender == guardian, "Caller must be the guardian");
timelock.executeTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta);
}
/////–––««« Governance-related functions »»»––––\\\\\
/**
* @notice Gets the current votes balance for a given account.
* @param account The address of the specified account
* @return The current number of votes of the account
*/
function getCurrentVotes(address account) public view override returns (uint256) {
uint256 nCheckpoints = eternalStorage.getUint(entity, keccak256(abi.encodePacked("numCheckpoints", account)));
return eternalStorage.getUint(entity, keccak256(abi.encodePacked("votes", account, nCheckpoints - 1)));
}
/**
* @notice Determine the number of votes of a given account prior to a given block.
* @param account The address of specified account
* @param blockNumber The number of the specified block
* @return The number of votes of the account before/by this block
*
* Requirements:
*
* - The given block must be finalized
*/
function getPriorVotes(address account, uint256 blockNumber) public view override returns (uint256) {
require(blockNumber < block.number, "Block is not yet finalized");
uint256 nCheckpoints = eternalStorage.getUint(entity, keccak256(abi.encodePacked("numCheckpoints", account)));
if (nCheckpoints == 0) {
// No checkpoints means no votes
return 0;
} else if (eternalStorage.getUint(entity, keccak256(abi.encodePacked("blocks", account, nCheckpoints - 1))) <= blockNumber) {
// Votes for the most recent checkpoint
return eternalStorage.getUint(entity, keccak256(abi.encodePacked("votes", account, nCheckpoints - 1)));
} else if (eternalStorage.getUint(entity, keccak256(abi.encodePacked("blocks", account, uint256(0)))) > blockNumber) {
// Only having checkpoints after the given block number means no votes
return 0;
}
uint256 lower = 0;
uint256 upper = nCheckpoints - 1;
while (upper > lower) {
uint256 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
uint256 thisBlock = eternalStorage.getUint(entity, keccak256(abi.encodePacked("blocks", account, center)));
if (thisBlock == blockNumber) {
return eternalStorage.getUint(entity, keccak256(abi.encodePacked("votes", account, center)));
} else if (thisBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return eternalStorage.getUint(entity, keccak256(abi.encodePacked("votes", account, lower)));
}
/**
* @notice Delegates the message sender's vote balance to a given user.
* @param delegatee The address of the user to whom the vote balance is being added to
*/
function delegate(address delegatee) external override {
bytes32 _delegate = keccak256(abi.encodePacked("delegates", _msgSender()));
address currentDelegate = eternalStorage.getAddress(entity, _delegate);
uint256 delegatorBalance = eternal.balanceOf(_msgSender());
eternalStorage.setAddress(entity, _delegate, delegatee);
emit DelegateChanged(_msgSender(), currentDelegate, delegatee);
moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
/**
* @notice Transfer part of a given delegates' voting balance to another new delegate.
* @param srcRep The delegate from whom we are deducting votes
* @param dstRep The delegate to whom we are transferring votes
* @param amount The specified amount of votes
*/
function moveDelegates(address srcRep, address dstRep, uint256 amount) public override {
require(_msgSender() == address(this) || _msgSender() == address(eternal), "Only callable by Eternal");
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint256 srcRepNum = eternalStorage.getUint(entity, keccak256(abi.encodePacked("numCheckpoints", srcRep)));
uint256 srcRepOld = srcRepNum > 0 ? eternalStorage.getUint(entity, keccak256(abi.encodePacked("votes", srcRep, srcRepNum - 1))) : 0;
uint256 srcRepNew = srcRepOld - amount;
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint256 dstRepNum = eternalStorage.getUint(entity, keccak256(abi.encodePacked("numCheckpoints", dstRep)));
uint256 dstRepOld = dstRepNum > 0 ? eternalStorage.getUint(entity, keccak256(abi.encodePacked("votes", dstRep, dstRepNum - 1))) : 0;
uint256 dstRepNew = dstRepOld + amount;
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
/**
* @notice Update a given user's voting balance for the current block.
* @param delegatee The address of the specified user
* @param nCheckpoints The number of times the voting balance of the user has been updated
* @param oldVotes The old voting balance of the user
* @param newVotes The new voting balance of the user
*/
function _writeCheckpoint(address delegatee, uint256 nCheckpoints, uint256 oldVotes,uint256 newVotes) private {
if (nCheckpoints > 0 && eternalStorage.getUint(entity, keccak256(abi.encodePacked("blocks", delegatee, nCheckpoints - 1))) == block.number) {
eternalStorage.setUint(entity, keccak256(abi.encodePacked("votes", delegatee, nCheckpoints - 1)), newVotes);
} else {
eternalStorage.setUint(entity, keccak256(abi.encodePacked("votes", delegatee, nCheckpoints)), newVotes);
eternalStorage.setUint(entity, keccak256(abi.encodePacked("blocks", delegatee, nCheckpoints)), block.number);
eternalStorage.setUint(entity, keccak256(abi.encodePacked("numCheckpoints", delegatee)), nCheckpoints + 1);
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
} | The timestamp at which voting ends: votes must be cast prior to this block
| uint256 endTime; | 12,810,464 | [
1,
1986,
2858,
622,
1492,
331,
17128,
3930,
30,
19588,
1297,
506,
4812,
6432,
358,
333,
1203,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
5034,
13859,
31,
12900,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
contract DSAuth is Ownable, AccessControl {
bytes32 public constant MINT_BURN_ROLE = keccak256("MINT_BURN_ROLE");
// setOwner transfers the STOS token contract ownership to another address
// along with grant new owner MINT_BURN_ROLE role and remove MINT_BURN_ROLE from old owner
// note: call transferOwnerShip will only change ownership without other roles
function setOwner(address newOwner) public onlyOwner {
require(newOwner != owner(), "New owner and current owner need to be different");
address oldOwner = owner();
transferOwnership(newOwner);
_grantAccess(MINT_BURN_ROLE, newOwner);
_revokeAccess(MINT_BURN_ROLE, oldOwner);
_setupRole(DEFAULT_ADMIN_ROLE, newOwner);
_revokeAccess(DEFAULT_ADMIN_ROLE, oldOwner);
emit OwnershipTransferred(oldOwner, newOwner);
}
// setAuthority performs the same action as grantMintBurnRole
// we need setAuthority() only because the backward compatibility with previous version contract
function setAuthority(address authorityAddress) public onlyOwner {
grantMintBurnRole(authorityAddress);
}
// grantMintBurnRole grants the MINT_BURN_ROLE role to an address
function grantMintBurnRole(address account) public onlyOwner {
_grantAccess(MINT_BURN_ROLE, account);
}
// revokeMintBurnRole revokes the MINT_BURN_ROLE role from an address
function revokeMintBurnRole(address account) public onlyOwner {
_revokeAccess(MINT_BURN_ROLE, account);
}
// internal function _grantAccess grants account with given role
function _grantAccess(bytes32 role, address account) internal {
grantRole(role, account);
emit RoleGranted(role, account, owner());
}
// internal function _revokeAccess revokes account with given role
function _revokeAccess(bytes32 role, address account) internal {
if (DEFAULT_ADMIN_ROLE == role) {
require(account != owner(), "owner cant revoke himself from admin role");
}
revokeRole(role, account);
emit RoleRevoked(role, account, owner());
}
}
contract DSStop is Pausable, Ownable {
// we need stopped() only because the backward compatibility with previous version contract
// stopped = paused
function stopped() public view returns (bool) {
return paused();
}
function stop() public onlyOwner {
_pause();
emit Paused(owner());
}
function start() public onlyOwner {
_unpause();
emit Unpaused(owner());
}
}
contract Stratos is ERC20("Stratos Token", "STOS"), DSAuth, DSStop {
event Mint(address indexed guy, uint wad);
event Burn(address indexed guy, uint wad);
uint256 MAX_SUPPLY = 1 * 10 ** 8 * 10 ** 18; // 100,000,000 STOS Token Max Supply
// deployer address is the default admin(owner)
// deployer address is the first address with MINT_BURN_ROLE role
constructor () {
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantAccess(MINT_BURN_ROLE, msg.sender);
}
function approve(address guy, uint wad) public override whenNotPaused returns (bool) {
return super.approve(guy, wad);
}
function transferFrom(address src, address dst, uint wad) public override whenNotPaused returns (bool) {
return super.transferFrom(src, dst, wad);
}
function transfer(address dst, uint wad) public override whenNotPaused returns (bool) {
return super.transfer(dst, wad);
}
function mint(address guy, uint wad) public whenNotPaused {
require(hasRole(MINT_BURN_ROLE, msg.sender), "Caller is not allowed to mint");
require(totalSupply() + wad <= MAX_SUPPLY, "Exceeds STOS token max totalSupply");
_mint(guy, wad);
emit Mint(guy, wad);
}
function burn(address guy, uint wad) public whenNotPaused {
require(hasRole(MINT_BURN_ROLE, msg.sender), "Caller is not allowed to burn");
_burn(guy, wad);
emit Burn(guy, wad);
}
function redeem(uint amount) public onlyOwner {
require(balanceOf(address(this)) >= amount, "redeem can not exceed the balance");
_transfer(address(this), owner(), amount);
}
}
| revokeMintBurnRole revokes the MINT_BURN_ROLE role from an address | function revokeMintBurnRole(address account) public onlyOwner {
_revokeAccess(MINT_BURN_ROLE, account);
}
| 7,299,439 | [
1,
9083,
3056,
49,
474,
38,
321,
2996,
5588,
601,
281,
326,
490,
3217,
67,
38,
8521,
67,
16256,
2478,
628,
392,
1758,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
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,
18007,
49,
474,
38,
321,
2996,
12,
2867,
2236,
13,
1071,
1338,
5541,
288,
203,
3639,
389,
9083,
3056,
1862,
12,
49,
3217,
67,
38,
8521,
67,
16256,
16,
2236,
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
] |
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.9;
import { Account } from './Account.sol';
import { LiquidityPosition } from './LiquidityPosition.sol';
import { Uint48Lib } from './Uint48.sol';
import { Uint48L5ArrayLib } from './Uint48L5Array.sol';
import { Protocol } from './Protocol.sol';
import { IClearingHouseStructures } from '../interfaces/clearinghouse/IClearingHouseStructures.sol';
import { IVPoolWrapper } from '../interfaces/IVPoolWrapper.sol';
/// @title Liquidity position set functions
library LiquidityPositionSet {
using LiquidityPosition for LiquidityPosition.Info;
using LiquidityPositionSet for LiquidityPosition.Set;
using Protocol for Protocol.Info;
using Uint48Lib for int24;
using Uint48Lib for uint48;
using Uint48L5ArrayLib for uint48[5];
error LPS_IllegalTicks(int24 tickLower, int24 tickUpper);
error LPS_DeactivationFailed(int24 tickLower, int24 tickUpper, uint256 liquidity);
error LPS_InactiveRange();
/**
* Internal methods
*/
function activate(
LiquidityPosition.Set storage set,
int24 tickLower,
int24 tickUpper
) internal returns (LiquidityPosition.Info storage position) {
if (tickLower > tickUpper) {
revert LPS_IllegalTicks(tickLower, tickUpper);
}
uint48 positionId;
set.active.include(positionId = tickLower.concat(tickUpper));
position = set.positions[positionId];
if (!position.isInitialized()) {
position.initialize(tickLower, tickUpper);
}
}
function deactivate(LiquidityPosition.Set storage set, LiquidityPosition.Info storage position) internal {
if (position.liquidity != 0) {
revert LPS_DeactivationFailed(position.tickLower, position.tickUpper, position.liquidity);
}
set.active.exclude(position.tickLower.concat(position.tickUpper));
}
function liquidityChange(
LiquidityPosition.Set storage set,
uint256 accountId,
uint32 poolId,
IClearingHouseStructures.LiquidityChangeParams memory liquidityChangeParams,
IClearingHouseStructures.BalanceAdjustments memory balanceAdjustments,
Protocol.Info storage protocol
) internal {
LiquidityPosition.Info storage position = set.activate(
liquidityChangeParams.tickLower,
liquidityChangeParams.tickUpper
);
position.limitOrderType = liquidityChangeParams.limitOrderType;
set.liquidityChange(
accountId,
poolId,
position,
liquidityChangeParams.liquidityDelta,
balanceAdjustments,
protocol
);
}
function liquidityChange(
LiquidityPosition.Set storage set,
uint256 accountId,
uint32 poolId,
LiquidityPosition.Info storage position,
int128 liquidity,
IClearingHouseStructures.BalanceAdjustments memory balanceAdjustments,
Protocol.Info storage protocol
) internal {
position.liquidityChange(accountId, poolId, liquidity, balanceAdjustments, protocol);
emit Account.TokenPositionChangedDueToLiquidityChanged(
accountId,
poolId,
position.tickLower,
position.tickUpper,
balanceAdjustments.vTokenIncrease
);
if (position.liquidity == 0) {
set.deactivate(position);
}
}
function closeLiquidityPosition(
LiquidityPosition.Set storage set,
uint256 accountId,
uint32 poolId,
LiquidityPosition.Info storage position,
IClearingHouseStructures.BalanceAdjustments memory balanceAdjustments,
Protocol.Info storage protocol
) internal {
set.liquidityChange(accountId, poolId, position, -int128(position.liquidity), balanceAdjustments, protocol);
}
function removeLimitOrder(
LiquidityPosition.Set storage set,
uint256 accountId,
uint32 poolId,
int24 currentTick,
int24 tickLower,
int24 tickUpper,
IClearingHouseStructures.BalanceAdjustments memory balanceAdjustments,
Protocol.Info storage protocol
) internal {
LiquidityPosition.Info storage position = set.getLiquidityPosition(tickLower, tickUpper);
position.checkValidLimitOrderRemoval(currentTick);
set.closeLiquidityPosition(accountId, poolId, position, balanceAdjustments, protocol);
}
function closeAllLiquidityPositions(
LiquidityPosition.Set storage set,
uint256 accountId,
uint32 poolId,
IClearingHouseStructures.BalanceAdjustments memory balanceAdjustments,
Protocol.Info storage protocol
) internal {
LiquidityPosition.Info storage position;
while (set.active[0] != 0) {
IClearingHouseStructures.BalanceAdjustments memory balanceAdjustmentsCurrent;
position = set.positions[set.active[0]];
set.closeLiquidityPosition(accountId, poolId, position, balanceAdjustmentsCurrent, protocol);
balanceAdjustments.vQuoteIncrease += balanceAdjustmentsCurrent.vQuoteIncrease;
balanceAdjustments.vTokenIncrease += balanceAdjustmentsCurrent.vTokenIncrease;
balanceAdjustments.traderPositionIncrease += balanceAdjustmentsCurrent.traderPositionIncrease;
}
}
/**
* Internal view methods
*/
function getLiquidityPosition(
LiquidityPosition.Set storage set,
int24 tickLower,
int24 tickUpper
) internal view returns (LiquidityPosition.Info storage position) {
if (tickLower > tickUpper) {
revert LPS_IllegalTicks(tickLower, tickUpper);
}
uint48 positionId = Uint48Lib.concat(tickLower, tickUpper);
position = set.positions[positionId];
if (!position.isInitialized()) revert LPS_InactiveRange();
return position;
}
function getInfo(LiquidityPosition.Set storage set)
internal
view
returns (IClearingHouseStructures.LiquidityPositionView[] memory liquidityPositions)
{
uint256 numberOfTokenPositions = set.active.numberOfNonZeroElements();
liquidityPositions = new IClearingHouseStructures.LiquidityPositionView[](numberOfTokenPositions);
for (uint256 i = 0; i < numberOfTokenPositions; i++) {
liquidityPositions[i].limitOrderType = set.positions[set.active[i]].limitOrderType;
liquidityPositions[i].tickLower = set.positions[set.active[i]].tickLower;
liquidityPositions[i].tickUpper = set.positions[set.active[i]].tickUpper;
liquidityPositions[i].liquidity = set.positions[set.active[i]].liquidity;
liquidityPositions[i].vTokenAmountIn = set.positions[set.active[i]].vTokenAmountIn;
liquidityPositions[i].sumALastX128 = set.positions[set.active[i]].sumALastX128;
liquidityPositions[i].sumBInsideLastX128 = set.positions[set.active[i]].sumBInsideLastX128;
liquidityPositions[i].sumFpInsideLastX128 = set.positions[set.active[i]].sumFpInsideLastX128;
liquidityPositions[i].sumFeeInsideLastX128 = set.positions[set.active[i]].sumFeeInsideLastX128;
}
}
function getNetPosition(LiquidityPosition.Set storage set, uint160 sqrtPriceCurrent)
internal
view
returns (int256 netPosition)
{
uint256 numberOfTokenPositions = set.active.numberOfNonZeroElements();
for (uint256 i = 0; i < numberOfTokenPositions; i++) {
netPosition += set.positions[set.active[i]].netPosition(sqrtPriceCurrent);
}
}
function isEmpty(LiquidityPosition.Set storage set) internal view returns (bool) {
return set.active.isEmpty();
}
function isPositionActive(
LiquidityPosition.Set storage set,
int24 tickLower,
int24 tickUpper
) internal view returns (bool) {
return set.active.exists(tickLower.concat(tickUpper));
}
function longSideRisk(LiquidityPosition.Set storage set, uint160 valuationPriceX96)
internal
view
returns (uint256 risk)
{
for (uint256 i = 0; i < set.active.length; i++) {
uint48 id = set.active[i];
risk += set.positions[id].longSideRisk(valuationPriceX96);
}
}
function marketValue(
LiquidityPosition.Set storage set,
uint160 sqrtPriceCurrent,
uint32 poolId,
Protocol.Info storage protocol
) internal view returns (int256 marketValue_) {
marketValue_ = set.marketValue(sqrtPriceCurrent, protocol.vPoolWrapper(poolId));
}
/// @notice Get the total market value of all active liquidity positions in the set.
/// @param set: Collection of active liquidity positions
/// @param sqrtPriceCurrent: Current price of the virtual asset
/// @param wrapper: address of the wrapper contract, passed once to avoid multiple sloads for wrapper
function marketValue(
LiquidityPosition.Set storage set,
uint160 sqrtPriceCurrent,
IVPoolWrapper wrapper
) internal view returns (int256 marketValue_) {
for (uint256 i = 0; i < set.active.length; i++) {
uint48 id = set.active[i];
if (id == 0) break;
marketValue_ += set.positions[id].marketValue(sqrtPriceCurrent, wrapper);
}
}
function maxNetPosition(LiquidityPosition.Set storage set) internal view returns (uint256 risk) {
for (uint256 i = 0; i < set.active.length; i++) {
uint48 id = set.active[i];
risk += set.positions[id].maxNetPosition();
}
}
}
| @title Liquidity position set functions | library LiquidityPositionSet {
using LiquidityPosition for LiquidityPosition.Info;
using LiquidityPositionSet for LiquidityPosition.Set;
using Protocol for Protocol.Info;
using Uint48Lib for int24;
using Uint48Lib for uint48;
using Uint48L5ArrayLib for uint48[5];
error LPS_IllegalTicks(int24 tickLower, int24 tickUpper);
error LPS_DeactivationFailed(int24 tickLower, int24 tickUpper, uint256 liquidity);
error LPS_InactiveRange();
function activate(
LiquidityPosition.Set storage set,
int24 tickLower,
int24 tickUpper
import { Account } from './Account.sol';
import { LiquidityPosition } from './LiquidityPosition.sol';
import { Uint48Lib } from './Uint48.sol';
import { Uint48L5ArrayLib } from './Uint48L5Array.sol';
import { Protocol } from './Protocol.sol';
import { IClearingHouseStructures } from '../interfaces/clearinghouse/IClearingHouseStructures.sol';
import { IVPoolWrapper } from '../interfaces/IVPoolWrapper.sol';
) internal returns (LiquidityPosition.Info storage position) {
if (tickLower > tickUpper) {
revert LPS_IllegalTicks(tickLower, tickUpper);
}
uint48 positionId;
set.active.include(positionId = tickLower.concat(tickUpper));
position = set.positions[positionId];
if (!position.isInitialized()) {
position.initialize(tickLower, tickUpper);
}
}
) internal returns (LiquidityPosition.Info storage position) {
if (tickLower > tickUpper) {
revert LPS_IllegalTicks(tickLower, tickUpper);
}
uint48 positionId;
set.active.include(positionId = tickLower.concat(tickUpper));
position = set.positions[positionId];
if (!position.isInitialized()) {
position.initialize(tickLower, tickUpper);
}
}
) internal returns (LiquidityPosition.Info storage position) {
if (tickLower > tickUpper) {
revert LPS_IllegalTicks(tickLower, tickUpper);
}
uint48 positionId;
set.active.include(positionId = tickLower.concat(tickUpper));
position = set.positions[positionId];
if (!position.isInitialized()) {
position.initialize(tickLower, tickUpper);
}
}
function deactivate(LiquidityPosition.Set storage set, LiquidityPosition.Info storage position) internal {
if (position.liquidity != 0) {
revert LPS_DeactivationFailed(position.tickLower, position.tickUpper, position.liquidity);
}
set.active.exclude(position.tickLower.concat(position.tickUpper));
}
function deactivate(LiquidityPosition.Set storage set, LiquidityPosition.Info storage position) internal {
if (position.liquidity != 0) {
revert LPS_DeactivationFailed(position.tickLower, position.tickUpper, position.liquidity);
}
set.active.exclude(position.tickLower.concat(position.tickUpper));
}
function liquidityChange(
LiquidityPosition.Set storage set,
uint256 accountId,
uint32 poolId,
IClearingHouseStructures.LiquidityChangeParams memory liquidityChangeParams,
IClearingHouseStructures.BalanceAdjustments memory balanceAdjustments,
Protocol.Info storage protocol
) internal {
LiquidityPosition.Info storage position = set.activate(
liquidityChangeParams.tickLower,
liquidityChangeParams.tickUpper
);
position.limitOrderType = liquidityChangeParams.limitOrderType;
set.liquidityChange(
accountId,
poolId,
position,
liquidityChangeParams.liquidityDelta,
balanceAdjustments,
protocol
);
}
function liquidityChange(
LiquidityPosition.Set storage set,
uint256 accountId,
uint32 poolId,
LiquidityPosition.Info storage position,
int128 liquidity,
IClearingHouseStructures.BalanceAdjustments memory balanceAdjustments,
Protocol.Info storage protocol
) internal {
position.liquidityChange(accountId, poolId, liquidity, balanceAdjustments, protocol);
emit Account.TokenPositionChangedDueToLiquidityChanged(
accountId,
poolId,
position.tickLower,
position.tickUpper,
balanceAdjustments.vTokenIncrease
);
if (position.liquidity == 0) {
set.deactivate(position);
}
}
function liquidityChange(
LiquidityPosition.Set storage set,
uint256 accountId,
uint32 poolId,
LiquidityPosition.Info storage position,
int128 liquidity,
IClearingHouseStructures.BalanceAdjustments memory balanceAdjustments,
Protocol.Info storage protocol
) internal {
position.liquidityChange(accountId, poolId, liquidity, balanceAdjustments, protocol);
emit Account.TokenPositionChangedDueToLiquidityChanged(
accountId,
poolId,
position.tickLower,
position.tickUpper,
balanceAdjustments.vTokenIncrease
);
if (position.liquidity == 0) {
set.deactivate(position);
}
}
function closeLiquidityPosition(
LiquidityPosition.Set storage set,
uint256 accountId,
uint32 poolId,
LiquidityPosition.Info storage position,
IClearingHouseStructures.BalanceAdjustments memory balanceAdjustments,
Protocol.Info storage protocol
) internal {
set.liquidityChange(accountId, poolId, position, -int128(position.liquidity), balanceAdjustments, protocol);
}
function removeLimitOrder(
LiquidityPosition.Set storage set,
uint256 accountId,
uint32 poolId,
int24 currentTick,
int24 tickLower,
int24 tickUpper,
IClearingHouseStructures.BalanceAdjustments memory balanceAdjustments,
Protocol.Info storage protocol
) internal {
LiquidityPosition.Info storage position = set.getLiquidityPosition(tickLower, tickUpper);
position.checkValidLimitOrderRemoval(currentTick);
set.closeLiquidityPosition(accountId, poolId, position, balanceAdjustments, protocol);
}
function closeAllLiquidityPositions(
LiquidityPosition.Set storage set,
uint256 accountId,
uint32 poolId,
IClearingHouseStructures.BalanceAdjustments memory balanceAdjustments,
Protocol.Info storage protocol
) internal {
LiquidityPosition.Info storage position;
while (set.active[0] != 0) {
IClearingHouseStructures.BalanceAdjustments memory balanceAdjustmentsCurrent;
position = set.positions[set.active[0]];
set.closeLiquidityPosition(accountId, poolId, position, balanceAdjustmentsCurrent, protocol);
balanceAdjustments.vQuoteIncrease += balanceAdjustmentsCurrent.vQuoteIncrease;
balanceAdjustments.vTokenIncrease += balanceAdjustmentsCurrent.vTokenIncrease;
balanceAdjustments.traderPositionIncrease += balanceAdjustmentsCurrent.traderPositionIncrease;
}
}
function closeAllLiquidityPositions(
LiquidityPosition.Set storage set,
uint256 accountId,
uint32 poolId,
IClearingHouseStructures.BalanceAdjustments memory balanceAdjustments,
Protocol.Info storage protocol
) internal {
LiquidityPosition.Info storage position;
while (set.active[0] != 0) {
IClearingHouseStructures.BalanceAdjustments memory balanceAdjustmentsCurrent;
position = set.positions[set.active[0]];
set.closeLiquidityPosition(accountId, poolId, position, balanceAdjustmentsCurrent, protocol);
balanceAdjustments.vQuoteIncrease += balanceAdjustmentsCurrent.vQuoteIncrease;
balanceAdjustments.vTokenIncrease += balanceAdjustmentsCurrent.vTokenIncrease;
balanceAdjustments.traderPositionIncrease += balanceAdjustmentsCurrent.traderPositionIncrease;
}
}
function getLiquidityPosition(
LiquidityPosition.Set storage set,
int24 tickLower,
int24 tickUpper
) internal view returns (LiquidityPosition.Info storage position) {
if (tickLower > tickUpper) {
revert LPS_IllegalTicks(tickLower, tickUpper);
}
uint48 positionId = Uint48Lib.concat(tickLower, tickUpper);
position = set.positions[positionId];
if (!position.isInitialized()) revert LPS_InactiveRange();
return position;
}
function getLiquidityPosition(
LiquidityPosition.Set storage set,
int24 tickLower,
int24 tickUpper
) internal view returns (LiquidityPosition.Info storage position) {
if (tickLower > tickUpper) {
revert LPS_IllegalTicks(tickLower, tickUpper);
}
uint48 positionId = Uint48Lib.concat(tickLower, tickUpper);
position = set.positions[positionId];
if (!position.isInitialized()) revert LPS_InactiveRange();
return position;
}
function getInfo(LiquidityPosition.Set storage set)
internal
view
returns (IClearingHouseStructures.LiquidityPositionView[] memory liquidityPositions)
{
uint256 numberOfTokenPositions = set.active.numberOfNonZeroElements();
liquidityPositions = new IClearingHouseStructures.LiquidityPositionView[](numberOfTokenPositions);
for (uint256 i = 0; i < numberOfTokenPositions; i++) {
liquidityPositions[i].limitOrderType = set.positions[set.active[i]].limitOrderType;
liquidityPositions[i].tickLower = set.positions[set.active[i]].tickLower;
liquidityPositions[i].tickUpper = set.positions[set.active[i]].tickUpper;
liquidityPositions[i].liquidity = set.positions[set.active[i]].liquidity;
liquidityPositions[i].vTokenAmountIn = set.positions[set.active[i]].vTokenAmountIn;
liquidityPositions[i].sumALastX128 = set.positions[set.active[i]].sumALastX128;
liquidityPositions[i].sumBInsideLastX128 = set.positions[set.active[i]].sumBInsideLastX128;
liquidityPositions[i].sumFpInsideLastX128 = set.positions[set.active[i]].sumFpInsideLastX128;
liquidityPositions[i].sumFeeInsideLastX128 = set.positions[set.active[i]].sumFeeInsideLastX128;
}
}
function getInfo(LiquidityPosition.Set storage set)
internal
view
returns (IClearingHouseStructures.LiquidityPositionView[] memory liquidityPositions)
{
uint256 numberOfTokenPositions = set.active.numberOfNonZeroElements();
liquidityPositions = new IClearingHouseStructures.LiquidityPositionView[](numberOfTokenPositions);
for (uint256 i = 0; i < numberOfTokenPositions; i++) {
liquidityPositions[i].limitOrderType = set.positions[set.active[i]].limitOrderType;
liquidityPositions[i].tickLower = set.positions[set.active[i]].tickLower;
liquidityPositions[i].tickUpper = set.positions[set.active[i]].tickUpper;
liquidityPositions[i].liquidity = set.positions[set.active[i]].liquidity;
liquidityPositions[i].vTokenAmountIn = set.positions[set.active[i]].vTokenAmountIn;
liquidityPositions[i].sumALastX128 = set.positions[set.active[i]].sumALastX128;
liquidityPositions[i].sumBInsideLastX128 = set.positions[set.active[i]].sumBInsideLastX128;
liquidityPositions[i].sumFpInsideLastX128 = set.positions[set.active[i]].sumFpInsideLastX128;
liquidityPositions[i].sumFeeInsideLastX128 = set.positions[set.active[i]].sumFeeInsideLastX128;
}
}
function getNetPosition(LiquidityPosition.Set storage set, uint160 sqrtPriceCurrent)
internal
view
returns (int256 netPosition)
{
uint256 numberOfTokenPositions = set.active.numberOfNonZeroElements();
for (uint256 i = 0; i < numberOfTokenPositions; i++) {
netPosition += set.positions[set.active[i]].netPosition(sqrtPriceCurrent);
}
}
function getNetPosition(LiquidityPosition.Set storage set, uint160 sqrtPriceCurrent)
internal
view
returns (int256 netPosition)
{
uint256 numberOfTokenPositions = set.active.numberOfNonZeroElements();
for (uint256 i = 0; i < numberOfTokenPositions; i++) {
netPosition += set.positions[set.active[i]].netPosition(sqrtPriceCurrent);
}
}
function isEmpty(LiquidityPosition.Set storage set) internal view returns (bool) {
return set.active.isEmpty();
}
function isPositionActive(
LiquidityPosition.Set storage set,
int24 tickLower,
int24 tickUpper
) internal view returns (bool) {
return set.active.exists(tickLower.concat(tickUpper));
}
function longSideRisk(LiquidityPosition.Set storage set, uint160 valuationPriceX96)
internal
view
returns (uint256 risk)
{
for (uint256 i = 0; i < set.active.length; i++) {
uint48 id = set.active[i];
risk += set.positions[id].longSideRisk(valuationPriceX96);
}
}
function longSideRisk(LiquidityPosition.Set storage set, uint160 valuationPriceX96)
internal
view
returns (uint256 risk)
{
for (uint256 i = 0; i < set.active.length; i++) {
uint48 id = set.active[i];
risk += set.positions[id].longSideRisk(valuationPriceX96);
}
}
function marketValue(
LiquidityPosition.Set storage set,
uint160 sqrtPriceCurrent,
uint32 poolId,
Protocol.Info storage protocol
) internal view returns (int256 marketValue_) {
marketValue_ = set.marketValue(sqrtPriceCurrent, protocol.vPoolWrapper(poolId));
}
function marketValue(
LiquidityPosition.Set storage set,
uint160 sqrtPriceCurrent,
IVPoolWrapper wrapper
) internal view returns (int256 marketValue_) {
for (uint256 i = 0; i < set.active.length; i++) {
uint48 id = set.active[i];
if (id == 0) break;
marketValue_ += set.positions[id].marketValue(sqrtPriceCurrent, wrapper);
}
}
function marketValue(
LiquidityPosition.Set storage set,
uint160 sqrtPriceCurrent,
IVPoolWrapper wrapper
) internal view returns (int256 marketValue_) {
for (uint256 i = 0; i < set.active.length; i++) {
uint48 id = set.active[i];
if (id == 0) break;
marketValue_ += set.positions[id].marketValue(sqrtPriceCurrent, wrapper);
}
}
function maxNetPosition(LiquidityPosition.Set storage set) internal view returns (uint256 risk) {
for (uint256 i = 0; i < set.active.length; i++) {
uint48 id = set.active[i];
risk += set.positions[id].maxNetPosition();
}
}
function maxNetPosition(LiquidityPosition.Set storage set) internal view returns (uint256 risk) {
for (uint256 i = 0; i < set.active.length; i++) {
uint48 id = set.active[i];
risk += set.positions[id].maxNetPosition();
}
}
}
| 12,619,294 | [
1,
48,
18988,
24237,
1754,
444,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
511,
18988,
24237,
2555,
694,
288,
203,
565,
1450,
511,
18988,
24237,
2555,
364,
511,
18988,
24237,
2555,
18,
966,
31,
203,
565,
1450,
511,
18988,
24237,
2555,
694,
364,
511,
18988,
24237,
2555,
18,
694,
31,
203,
565,
1450,
4547,
364,
4547,
18,
966,
31,
203,
565,
1450,
7320,
8875,
5664,
364,
509,
3247,
31,
203,
565,
1450,
7320,
8875,
5664,
364,
2254,
8875,
31,
203,
565,
1450,
7320,
8875,
48,
25,
1076,
5664,
364,
2254,
8875,
63,
25,
15533,
203,
203,
565,
555,
511,
5857,
67,
12195,
16610,
12,
474,
3247,
4024,
4070,
16,
509,
3247,
4024,
5988,
1769,
203,
565,
555,
511,
5857,
67,
758,
16908,
2925,
12,
474,
3247,
4024,
4070,
16,
509,
3247,
4024,
5988,
16,
2254,
5034,
4501,
372,
24237,
1769,
203,
565,
555,
511,
5857,
67,
24384,
2655,
5621,
203,
203,
203,
565,
445,
10235,
12,
203,
3639,
511,
18988,
24237,
2555,
18,
694,
2502,
444,
16,
203,
3639,
509,
3247,
4024,
4070,
16,
203,
3639,
509,
3247,
4024,
5988,
203,
203,
5666,
288,
6590,
289,
628,
12871,
3032,
18,
18281,
13506,
203,
5666,
288,
511,
18988,
24237,
2555,
289,
628,
12871,
48,
18988,
24237,
2555,
18,
18281,
13506,
203,
5666,
288,
7320,
8875,
5664,
289,
628,
12871,
5487,
8875,
18,
18281,
13506,
203,
5666,
288,
7320,
8875,
48,
25,
1076,
5664,
289,
628,
12871,
5487,
8875,
48,
25,
1076,
18,
18281,
13506,
203,
5666,
288,
4547,
289,
628,
12871,
5752,
18,
18281,
13506,
203,
5666,
288,
467,
4756,
5968,
44,
3793,
3823,
1823,
289,
628,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "./IERC20.sol";
import "./IETHPool.sol";
import "./IStrongPool.sol";
import "./PlatformFees.sol";
import "./ReentrancyGuard.sol";
import "./SafeMath.sol";
contract ETHPoolV3 is IETHPool, IStrongPool, ReentrancyGuard, PlatformFees {
using SafeMath for uint256;
bool public initialized;
uint256 public epochId;
uint256 public totalStaked;
mapping(address => bool) public poolContracts;
mapping(uint256 => address) public stakeOwner;
mapping(uint256 => uint256) public stakeAmount;
mapping(uint256 => uint256) public stakeTimestamp;
mapping(uint256 => bool) public stakeStatus;
uint256 private stakeId;
IERC20 private strongTokenContract;
mapping(address => mapping(uint256 => uint256)) private _ownerIdIndex;
mapping(address => uint256[]) private _ownerIds;
event FallBackLog(address sender, uint256 value);
event PaymentProcessed(address receiver, uint256 amount);
function init(
address strongAddress_,
uint256 stakeFeeNumerator_,
uint256 stakeFeeDenominator_,
uint256 unstakeFeeNumerator_,
uint256 unstakeFeeDenominator_,
uint256 minStakeAmount_,
uint256 stakeTxLimit_,
address payable feeWallet_,
address serviceAdmin_
) external {
require(!initialized, "ETH2.0Pool: init done");
PlatformFees.init(
stakeFeeNumerator_,
stakeFeeDenominator_,
unstakeFeeNumerator_,
unstakeFeeDenominator_,
minStakeAmount_,
stakeTxLimit_,
feeWallet_,
serviceAdmin_
);
ReentrancyGuard.init();
epochId = 1;
stakeId = 1;
strongTokenContract = IERC20(strongAddress_);
initialized = true;
}
function stake(uint256 amount_) external payable nonReentrant override {
require(amount_.mul(stakeFeeNumerator).div(stakeFeeDenominator) == msg.value, "ETH2.0Pool: Value can not be greater or less than staking fee");
stake_(amount_, msg.sender);
require(strongTokenContract.transferFrom(msg.sender, address(this), amount_), "ETH2.0Pool: Insufficient funds");
processPayment(feeWallet, msg.value);
}
function mineFor(address userAddress_, uint256 amount_) external override {
require(poolContracts[msg.sender], "ETH2.0Pool: Caller not authorised to call this function");
stake_(amount_, userAddress_);
require(strongTokenContract.transferFrom(msg.sender, address(this), amount_), "ETH2.0Pool: Insufficient funds");
}
function unStake(uint256[] memory stakeIds_) external payable nonReentrant override {
require(stakeIds_.length <= stakeTxLimit, "ETH2.0Pool: Input array length is greater than approved length");
uint256 userTokens = 0;
for (uint256 i = 0; i < stakeIds_.length; i++) {
require(stakeOwner[stakeIds_[i]] == msg.sender, "ETH2.0Pool: Only owner can unstake");
require(stakeStatus[stakeIds_[i]], "ETH2.0Pool: Transaction already unStaked");
stakeStatus[stakeIds_[i]] = false;
userTokens = userTokens.add(stakeAmount[stakeIds_[i]]);
if (_ownerIdExists(msg.sender, stakeIds_[i])) {
_deleteOwnerId(msg.sender, stakeIds_[i]);
}
emit Unstaked(msg.sender, stakeIds_[i], stakeAmount[stakeIds_[i]], block.timestamp);
}
if (userTokens.mul(unstakeFeeNumerator).div(unstakeFeeDenominator) != msg.value) {
revert("ETH2.0Pool: Value can not be greater or less than unstaking fee");
}
totalStaked = totalStaked.sub(userTokens);
require(strongTokenContract.transfer(msg.sender, userTokens), "ETH2.0Pool: Insufficient Strong tokens");
processPayment(feeWallet, userTokens.mul(unstakeFeeNumerator).div(unstakeFeeDenominator));
}
function stake_(uint256 amount_, address userAddress_) internal {
require(_ownerIds[userAddress_].length < stakeTxLimit, "ETH2.0Pool: User can not exceed stake tx limit");
require(amount_ >= minStakeAmount, "ETH2.0Pool: Amount can not be less than minimum staking amount");
require(userAddress_ != address(0), "ETH2.0Pool: Invalid user address");
stakeOwner[stakeId] = userAddress_;
stakeAmount[stakeId] = amount_;
stakeTimestamp[stakeId] = block.timestamp;
stakeStatus[stakeId] = true;
totalStaked = totalStaked.add(amount_);
if (!_ownerIdExists(userAddress_, stakeId)) {
_addOwnerId(userAddress_, stakeId);
}
emit Staked(userAddress_,stakeId, amount_, block.timestamp);
incrementStakeId();
}
function addVerifiedContract(address contractAddress_) external anyAdmin {
require(contractAddress_ != address(0), "ETH2.0Pool: Invalid contract address");
poolContracts[contractAddress_] = true;
}
function removeVerifiedContract(address contractAddress_) external anyAdmin {
require(poolContracts[contractAddress_], "ETH2.0Pool: Contract address not verified");
poolContracts[contractAddress_] = false;
}
function getUserIds(address user_) external view returns (uint256[] memory) {
return _ownerIds[user_];
}
function getUserIdIndex(address user_, uint256 id_) external view returns (uint256) {
return _ownerIdIndex[user_][id_];
}
// function to transfer eth to recipient account.
function processPayment(address payable recipient_, uint256 amount_) private {
(bool sent,) = recipient_.call{value : amount_}("");
require(sent, "ETH2.0Pool: Failed to send Ether");
emit PaymentProcessed(recipient_, amount_);
}
// function to increment the id counter of Staking entries
function incrementStakeId() private {
stakeId = stakeId.add(1);
}
function _deleteOwnerId(address owner_, uint256 id_) internal {
uint256 lastIndex = _ownerIds[owner_].length.sub(1);
uint256 lastId = _ownerIds[owner_][lastIndex];
if (id_ == lastId) {
_ownerIdIndex[owner_][id_] = 0;
_ownerIds[owner_].pop();
} else {
uint256 indexOfId = _ownerIdIndex[owner_][id_];
_ownerIdIndex[owner_][id_] = 0;
_ownerIds[owner_][indexOfId] = lastId;
_ownerIdIndex[owner_][lastId] = indexOfId;
_ownerIds[owner_].pop();
}
}
function _addOwnerId(address owner, uint256 id) internal {
uint256 len = _ownerIds[owner].length;
_ownerIdIndex[owner][id] = len;
_ownerIds[owner].push(id);
}
function _ownerIdExists(address owner, uint256 id) internal view returns (bool) {
if (_ownerIds[owner].length == 0) return false;
uint256 index = _ownerIdIndex[owner][id];
return id == _ownerIds[owner][index];
}
function setTokenContract(IERC20 tokenAddress) external onlyOwner {
strongTokenContract = tokenAddress;
}
function withdrawToken(IERC20 token, address recipient, uint256 amount) external onlyOwner {
require(token.transfer(recipient, amount));
}
fallback() external payable {
emit FallBackLog(msg.sender, msg.value);
}
receive() external nonReentrant payable {
processPayment(feeWallet, msg.value);
emit FallBackLog(msg.sender, msg.value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IETHPool {
event Staked(address user, uint256 stakeId, uint256 amount, uint256 timestamp);
event Unstaked(address user, uint256 stakeId, uint256 amount, uint256 timestamp);
function stake(uint256 amount) external payable;
function unStake(uint256[] memory stakeIds) external payable;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IStrongPool {
function mineFor(address miner, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^ 0.8.0;
import "./Ownable.sol";
import "./IPlatformFees.sol";
contract PlatformFees is Ownable, IPlatformFees {
uint256 public stakeFeeNumerator;
uint256 public stakeFeeDenominator;
uint256 public unstakeFeeNumerator;
uint256 public unstakeFeeDenominator;
uint256 public minStakeAmount;
uint256 public stakeTxLimit;
address payable public feeWallet;
bool private initDone;
function init(
uint256 stakeFeeNumerator_,
uint256 stakeFeeDenominator_,
uint256 unstakeFeeNumerator_,
uint256 unstakeFeeDenominator_,
uint256 minStakeAmount_,
uint256 stakeTxLimit_,
address payable feeWallet_,
address serviceAdmin
) internal {
require(!initDone, "PlatformFee: init done");
stakeFeeNumerator = stakeFeeNumerator_;
stakeFeeDenominator = stakeFeeDenominator_;
unstakeFeeNumerator = unstakeFeeNumerator_;
unstakeFeeDenominator = unstakeFeeDenominator_;
minStakeAmount = minStakeAmount_;
stakeTxLimit = stakeTxLimit_;
feeWallet = feeWallet_;
Ownable.init(serviceAdmin);
initDone = true;
}
function setStakeFeeNumerator(uint256 numerator_) external override anyAdmin {
stakeFeeNumerator = numerator_;
}
function setStakeFeeDenominator(uint256 denominator_) external override anyAdmin {
require(denominator_ > 0, "PlatformFee: denominator can not be zero");
stakeFeeDenominator = denominator_;
}
function setUnstakeFeeNumerator(uint256 numerator_) external override anyAdmin {
unstakeFeeNumerator = numerator_;
}
function setUnstakeFeeDenominator(uint256 denominator_) external override anyAdmin {
require(denominator_ > 0, "PlatformFee: denominator can not be zero");
unstakeFeeDenominator = denominator_;
}
function setMinStakeAmount(uint256 amount_) external override anyAdmin {
require(amount_ > 0, "PlatformFee: amount can not be zero");
minStakeAmount = amount_;
}
function setStakeTxLimit(uint256 limit_) external override anyAdmin {
require(limit_ > 0, "PlatformFee: limit can not zero");
stakeTxLimit = limit_;
}
function setFeeWallet(address payable feeWallet_) external override anyAdmin {
require(feeWallet_ != address(0), "PlatformFee: address can not be zero address");
feeWallet = feeWallet_;
}
}
// 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;
bool private init_;
function init()internal{
require(!init_, "ReentrancyGuard: init done");
_status = _NOT_ENTERED;
init_ = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./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;
address private _serviceAdmin;
bool private initialized;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event NewServiceAdmin(address indexed previousServiceAdmin, address indexed newServiceAdmin);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function init(address serviceAdmin_) internal {
require(!initialized, "Ownable: init done");
_setOwner(_msgSender());
_setServiceAdmin(serviceAdmin_);
initialized = true;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Returns the address of the current service admin.
*/
function serviceAdmin() public view virtual returns (address) {
return _serviceAdmin;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Throws if called by any account other than the service Admin.
*/
modifier onlyServiceAdmin() {
require(serviceAdmin() == _msgSender(), "Ownable: caller is not the serviceAdmin");
_;
}
modifier anyAdmin(){
require(serviceAdmin() == _msgSender() || owner() == _msgSender(), "Ownable: Caller is not authorized");
_;
}
/**
* @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() external 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) external 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);
}
function _setServiceAdmin(address newServiceAdmin) private {
address oldServiceAdmin = _serviceAdmin;
_serviceAdmin = newServiceAdmin;
emit NewServiceAdmin(oldServiceAdmin, newServiceAdmin);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IPlatformFees {
function setStakeFeeNumerator(uint256 numerator_) external;
function setStakeFeeDenominator(uint256 denominator_) external;
function setUnstakeFeeNumerator(uint256 numerator_) external;
function setUnstakeFeeDenominator(uint256 denominator_) external;
function setMinStakeAmount(uint256 _amount) external;
function setStakeTxLimit(uint256 limit_) external;
function setFeeWallet(address payable feeWallet_) external;
}
// 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;
}
} | * @dev Initializes the contract setting the deployer as the initial owner./ | function init(address serviceAdmin_) internal {
require(!initialized, "Ownable: init done");
_setOwner(_msgSender());
_setServiceAdmin(serviceAdmin_);
initialized = true;
}
| 1,711,669 | [
1,
9685,
326,
6835,
3637,
326,
7286,
264,
487,
326,
2172,
3410,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1208,
12,
2867,
1156,
4446,
67,
13,
2713,
288,
203,
3639,
2583,
12,
5,
13227,
16,
315,
5460,
429,
30,
1208,
2731,
8863,
203,
3639,
389,
542,
5541,
24899,
3576,
12021,
10663,
203,
3639,
389,
542,
1179,
4446,
12,
3278,
4446,
67,
1769,
203,
3639,
6454,
273,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.15;
contract ETHLotteryManagerInterface {
function register();
}
contract ETHLotteryInterface {
function accumulate();
}
contract ETHLottery {
bytes32 public name = 'ETHLottery - Last 1 Byte Lottery';
address public manager_address;
address public owner;
bool public open;
uint256 public jackpot;
uint256 public fee;
uint256 public owner_fee;
uint256 public create_block;
uint256 public result_block;
uint256 public winners_count;
bytes32 public result_hash;
bytes1 public result;
address public accumulated_from;
address public accumulate_to;
mapping (bytes1 => address[]) bettings;
mapping (address => uint256) credits;
event Balance(uint256 _balance);
event Result(bytes1 _result);
event Open(bool _open);
event Play(address indexed _sender, bytes1 _byte, uint256 _time);
event Withdraw(address indexed _sender, uint256 _amount, uint256 _time);
event Destroy();
event Accumulate(address _accumulate_to, uint256 _amount);
function ETHLottery(address _manager, uint256 _fee, uint256 _jackpot, uint256 _owner_fee, address _accumulated_from) {
owner = msg.sender;
open = true;
create_block = block.number;
manager_address = _manager;
fee = _fee;
jackpot = _jackpot;
owner_fee = _owner_fee;
// accumulate
if (_accumulated_from != owner) {
accumulated_from = _accumulated_from;
ETHLotteryInterface lottery = ETHLotteryInterface(accumulated_from);
lottery.accumulate();
}
// register with manager
ETHLotteryManagerInterface manager = ETHLotteryManagerInterface(manager_address);
manager.register();
Open(open);
}
modifier isOwner() {
require(msg.sender == owner);
_;
}
modifier isOriginalOwner() {
// used tx.origin on purpose instead of
// msg.sender, as we want to get the original
// starter of the transaction to be owner
require(tx.origin == owner);
_;
}
modifier isOpen() {
require(open);
_;
}
modifier isClosed() {
require(!open);
_;
}
modifier isPaid() {
require(msg.value >= fee);
_;
}
modifier hasPrize() {
require(credits[msg.sender] > 0);
_;
}
modifier isAccumulated() {
require(result_hash != 0 && winners_count == 0);
_;
}
modifier hasResultHash() {
require(
block.number >= result_block &&
block.number <= result_block + 256 &&
block.blockhash(result_block) != result_hash
);
_;
}
function play(bytes1 _byte) payable isOpen isPaid returns (bool) {
bettings[_byte].push(msg.sender);
if (this.balance >= jackpot) {
uint256 owner_fee_amount = (this.balance * owner_fee) / 100;
// this is the transaction which
// will generate the block used
// to count until the 10th in order
// to get the lottery result.
if (!owner.send(owner_fee_amount)) {
return false;
}
open = false;
// block offset hardcoded to 10
result_block = block.number + 10;
Open(open);
}
Balance(this.balance);
Play(msg.sender, _byte, now);
return true;
}
// This method is only used if we miss the 256th block
// containing the result hash, lottery() should be used instead
// this method as this is duplicated from lottery()
function manual_lottery(bytes32 _result_hash) isClosed isOwner {
result_hash = _result_hash;
result = result_hash[31];
address[] storage winners = bettings[result];
winners_count = winners.length;
if (winners_count > 0) {
uint256 credit = this.balance / winners_count;
for (uint256 i = 0; i < winners_count; i++) {
credits[winners[i]] = credit;
}
}
Result(result);
}
function lottery() isClosed hasResultHash isOwner {
result_hash = block.blockhash(result_block);
// get last byte (31st) from block hash as result
result = result_hash[31];
address[] storage winners = bettings[result];
winners_count = winners.length;
if (winners_count > 0) {
uint256 credit = this.balance / winners_count;
for (uint256 i = 0; i < winners_count; i++) {
credits[winners[i]] = credit;
}
}
Result(result);
}
function withdraw() isClosed hasPrize returns (bool) {
uint256 credit = credits[msg.sender];
// zero credit before send preventing re-entrancy
// as msg.sender can be a contract and call us back
credits[msg.sender] = 0;
if (!msg.sender.send(credit)) {
// transfer failed, return credit for withdraw
credits[msg.sender] = credit;
return false;
}
Withdraw(msg.sender, credit, now);
return true;
}
function accumulate() isOriginalOwner isClosed isAccumulated {
accumulate_to = msg.sender;
if (msg.sender.send(this.balance)) {
Accumulate(msg.sender, this.balance);
}
}
function destruct() isClosed isOwner {
Destroy();
selfdestruct(owner);
}
} | register with manager | ETHLotteryManagerInterface manager = ETHLotteryManagerInterface(manager_address);
| 13,010,160 | [
1,
4861,
598,
3301,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
512,
2455,
48,
352,
387,
93,
29931,
3301,
273,
512,
2455,
48,
352,
387,
93,
29931,
12,
4181,
67,
2867,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
/// @author Nazariy Vavryk [[email protected]] - reNFT Labs [https://twitter.com/renftlabs]
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721Holder.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "hardhat/console.sol";
contract TestGame is Ownable, ERC721Holder, ReentrancyGuard {
event Received(address, uint256);
event PrizeTransfer(address to, address nftishka, uint256 id, uint256 prizeIx);
struct Nft {
address adr;
uint256 id;
}
struct Players {
address[256] addresses;
mapping(address => bool) contains;
uint8 numPlayers;
}
mapping(address => bool) public testTest;
address private chainlinkVrfCoordinator = 0xdD3782915140c8f3b190B5D67eAc6dc5760C46E9;
address private chainlinkLinkToken = 0xa36085F69e2889c224210F603D836748e7dC0088;
bytes32 private chainlinkKeyHash = 0x6c3699283bda56ad74f6b855546325b68d482e983852a7a82979cc4807b641f4;
uint256 private chainlinkCallFee = 0.1 * 10**18;
uint256 public ticketPrice = 0.0001 ether;
uint32 public timeBeforeGameStart = 1609718399;
uint8[255] public playersOrder;
uint256[8] public entropies;
Players public players;
Nft[255] public nfts;
mapping(uint8 => uint8) public swaps;
mapping(uint8 => uint8) public spaws;
mapping(address => bool) public depositors;
bool private initComplete = true;
uint32 public lastAction;
uint16 public thinkTime = 10800;
uint8 public currPlayer = 0;
modifier onlyWhitelisted() {
require(depositors[msg.sender], "you are not allowed to deposit");
_;
}
function addDepositors(address[] calldata ds) external onlyOwner {
for (uint256 i = 0; i < ds.length; i++) {
depositors[ds[i]] = true;
}
}
modifier youShallNotPatheth(uint8 missed) {
uint256 currTime = now;
require(currTime > lastAction, "timestamps are incorrect");
uint256 elapsed = currTime - lastAction;
uint256 playersSkipped = elapsed / thinkTime;
// someone has skipped their turn. We track this on the front-end
if (missed != 0) {
require(playersSkipped > 0, "zero players skipped");
require(playersSkipped < 255, "too many players skipped");
require(playersSkipped == missed, "playersSkipped not eq missed");
require(currPlayer < 256, "currPlayer exceeds 255");
} else {
require(playersSkipped == 0, "playersSkipped not zero");
}
require(players.addresses[playersOrder[currPlayer + missed]] == msg.sender, "not your turn");
_;
}
constructor() public {
depositors[0x465DCa9995D6c2a81A9Be80fBCeD5a770dEE3daE] = true;
depositors[0x426923E98e347158D5C471a9391edaEa95516473] = true;
// each entropy is 32 chunks of uint8
// so the below is sufficient randomness for 64 players
// entropies = [
// 11579208923731619542357098500868790785326984665640564039457584007913129639935,
// 11579208923731619542357098008687907853269984665640564039457584007913129639935
// ];
}
function deposit(ERC721[] calldata _nfts, uint256[] calldata tokenIds) public onlyWhitelisted {
require(_nfts.length == tokenIds.length, "variable lengths");
for (uint256 i = 0; i < _nfts.length; i++) {
_nfts[i].transferFrom(msg.sender, address(this), tokenIds[i]);
}
}
function buyTicket() public payable nonReentrant {
require(msg.value >= ticketPrice, "sent ether too low");
require(players.numPlayers < 256, "total number of players reached");
require(players.contains[msg.sender] == false, "cant buy more");
players.contains[msg.sender] = true;
players.addresses[players.numPlayers + 1] = msg.sender;
players.numPlayers++;
}
function unwrap(uint8 missed) external nonReentrant youShallNotPatheth(missed) {
currPlayer += missed + 1;
lastAction = uint32(now);
}
/// @param _sender - index from playersOrder arr that you are stealing from
/// @param _from - index from playersOrder who to steal from
/// @param missed - how many players missed their turn since lastAction
function steal(
uint8 _sender,
uint8 _from,
uint8 missed
) external nonReentrant youShallNotPatheth(missed) {
require(_sender > _from, "cant steal from someone who unwrapped after");
// console.log("_sender %s, _from %s", _sender, _from);
uint8 sender = playersOrder[_sender]; // strictly greater than zero
uint8 from = playersOrder[_from]; // strictly greater than zero
require(sender > 0, "strictly greater than zero sender");
require(from > 0, "strictly greater than zero from");
require(currPlayer + missed < 256, "its a pickle, no doubt about it");
require(players.addresses[playersOrder[currPlayer + missed]] == players.addresses[sender], "not your order");
require(players.addresses[sender] == msg.sender, "sender is not valid");
require(spaws[from] == 0, "cant steal from them again");
require(swaps[sender] == 0, "you cant steal again. You can in Verkhovna Rada.");
// console.log("sender %s, from %s", sender, from);
swaps[sender] = from;
spaws[from] = sender;
currPlayer += missed + 1;
lastAction = uint32(now);
}
/// @param startIx - index from which to start looping the prizes
/// @param endIx - index on which to end looping the prizes (exclusive)
/// @dev start and end indices would be useful in case we hit
/// the block gas limit, or we want to better control our transaction
/// costs
/// swaps \in {1, 255}. 0 signifies absence. I stole from
/// spaws is an image of swaps.
function finito(
uint8[256] calldata op,
uint8 startIx,
uint8 endIx
) external onlyOwner {
require(startIx > 0, "there is no player at 0");
for (uint8 i = startIx; i < endIx; i++) {
uint8 playerIx = playersOrder[i - 1];
uint8 prizeIx;
uint8 stoleIx = swaps[playerIx];
uint8 stealerIx = spaws[playerIx];
if (stoleIx == 0 && stealerIx == 0) {
prizeIx = playersOrder[i - 1] - 1;
} else if (stealerIx != 0) {
prizeIx = op[stealerIx - 1];
} else {
bool end = false;
while (!end) {
prizeIx = stoleIx;
stoleIx = swaps[stoleIx];
if (stoleIx == 0) {
end = true;
}
}
prizeIx = op[prizeIx - 1];
}
// event PrizeTransfer(address to, address nftishka, uint256 id, uint256 prizeIx);
emit PrizeTransfer(players.addresses[playerIx], nfts[prizeIx].adr, nfts[prizeIx].id, prizeIx);
// emit PrizeTransfer();
}
}
function onERC721Received(
address,
address,
uint256,
bytes memory
) public override returns (bytes4) {
revert("we are saving you your NFT, you are welcome");
}
receive() external payable {
emit Received(msg.sender, msg.value);
}
function setTicketPrice(uint256 v) external onlyOwner {
ticketPrice = v;
}
function player(uint8 i) external view returns (address, uint8) {
return (players.addresses[i], players.numPlayers);
}
function testSetLastAction(uint32 _lastAction) external onlyOwner {
lastAction = _lastAction;
}
function testSetPlayersOrder(uint8[255] calldata _playersOrder) external onlyOwner {
playersOrder = _playersOrder;
}
function withdrawERC721(ERC721 nft, uint256 tokenId) external onlyOwner {
nft.transferFrom(address(this), msg.sender, tokenId);
}
function withdrawERC20(ERC20 token) external onlyOwner {
token.transfer(msg.sender, token.balanceOf(address(this)));
}
function withdrawEth() external onlyOwner {
msg.sender.transfer(address(this).balance);
}
}
| strictly greater than zero
| uint8 from = playersOrder[_from]; | 5,473,489 | [
1,
13948,
715,
6802,
2353,
3634,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
628,
273,
18115,
2448,
63,
67,
2080,
15533,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x765f64Be4D190287E8049A71D12a334Fc52b8E0a/sources/contracts/vaults/Para4626.sol | @notice Withdraw weth from the pool @param assets The amount of weth being withdrawn @param receiver The account that will receive weth @param owner The account that will pay receipt tokens @return shares The amount of shares burnt | function withdraw(
uint256 assets,
address receiver,
address owner
) external nonReentrant onlyRole(WHITELIST_ROLE) returns (uint256 shares) {
if (receiver == address(0)) {
revert InvalidAddress();
}
if (assets == 0) {
revert ParameterOutOfBounds();
}
shares = previewWithdraw(assets);
_withdraw(msg.sender, receiver, owner, assets, shares);
}
| 9,793,383 | [
1,
1190,
9446,
341,
546,
628,
326,
2845,
225,
7176,
1021,
3844,
434,
341,
546,
3832,
598,
9446,
82,
225,
5971,
1021,
2236,
716,
903,
6798,
341,
546,
225,
3410,
1021,
2236,
716,
903,
8843,
16030,
2430,
327,
24123,
1021,
3844,
434,
24123,
18305,
88,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
598,
9446,
12,
203,
3639,
2254,
5034,
7176,
16,
203,
3639,
1758,
5971,
16,
203,
3639,
1758,
3410,
203,
565,
262,
3903,
1661,
426,
8230,
970,
1338,
2996,
12,
16861,
7085,
67,
16256,
13,
1135,
261,
11890,
5034,
24123,
13,
288,
203,
3639,
309,
261,
24454,
422,
1758,
12,
20,
3719,
288,
203,
5411,
15226,
1962,
1887,
5621,
203,
3639,
289,
203,
3639,
309,
261,
9971,
422,
374,
13,
288,
203,
5411,
15226,
5498,
11224,
5694,
5621,
203,
3639,
289,
203,
203,
3639,
24123,
273,
10143,
1190,
9446,
12,
9971,
1769,
203,
203,
3639,
389,
1918,
9446,
12,
3576,
18,
15330,
16,
5971,
16,
3410,
16,
7176,
16,
24123,
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
] |
./full_match/4/0x07e9BF60268551d2D5Cc9fAbCbAeE1b7385D45e0/sources/browser/Untitled.sol | pay referral 10% pay 6 parent 40% | function payIndex1(uint32 _userId,uint8 _planIndex, uint32 _referrerId,uint256 _paidAmount, uint[8] memory prcnt) internal returns(bool)
{
boosterGain[_userId][_planIndex] += uint128(boosterGain[_userId][0] * prcnt[0] / 100000000);
uint32 pId = _userId;
uint256 tmp;
uint8 i;
for(i=0;i<6;i++)
{
( ,pId,,,,,,) = mscInterface(mscContractAddress).userInfos(networkId,0,true, pId);
boosterGain[pId][i] += uint128(_paidAmount * prcnt[1] / 100000000);
}
tmp = 0;
for(i=0;i<5;i++)
{
( ,pId,,,,,,) = mscInterface(mscContractAddress).userInfos(networkId,1,false, _userId);
autoPoolGain[_userId][_planIndex][i] += uint128(_paidAmount * prcnt[i+2] / 100000000);
}
}
| 12,373,289 | [
1,
10239,
1278,
29084,
1728,
9,
8843,
1666,
982,
225,
8063,
9,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
8843,
1016,
21,
12,
11890,
1578,
389,
18991,
16,
11890,
28,
389,
7088,
1016,
16,
2254,
1578,
389,
1734,
11110,
548,
16,
11890,
5034,
389,
29434,
6275,
16,
2254,
63,
28,
65,
3778,
846,
13085,
13,
2713,
1135,
12,
6430,
13,
203,
565,
288,
203,
3639,
14994,
264,
43,
530,
63,
67,
18991,
6362,
67,
7088,
1016,
65,
1011,
2254,
10392,
12,
25018,
264,
43,
530,
63,
67,
18991,
6362,
20,
65,
380,
846,
13085,
63,
20,
65,
342,
2130,
9449,
1769,
203,
203,
3639,
2254,
1578,
293,
548,
273,
389,
18991,
31,
203,
3639,
2254,
5034,
1853,
31,
203,
3639,
2254,
28,
277,
31,
203,
3639,
364,
12,
77,
33,
20,
31,
77,
32,
26,
31,
77,
27245,
203,
3639,
288,
203,
5411,
261,
269,
84,
548,
30495,
16408,
13,
273,
312,
1017,
1358,
12,
959,
71,
8924,
1887,
2934,
1355,
7655,
12,
5185,
548,
16,
20,
16,
3767,
16,
293,
548,
1769,
7010,
5411,
14994,
264,
43,
530,
63,
84,
548,
6362,
77,
65,
1011,
2254,
10392,
24899,
29434,
6275,
380,
846,
13085,
63,
21,
65,
342,
2130,
9449,
1769,
7010,
3639,
289,
203,
203,
3639,
1853,
273,
374,
31,
203,
3639,
364,
12,
77,
33,
20,
31,
77,
32,
25,
31,
77,
27245,
203,
3639,
288,
203,
5411,
261,
269,
84,
548,
30495,
16408,
13,
273,
312,
1017,
1358,
12,
959,
71,
8924,
1887,
2934,
1355,
7655,
12,
5185,
548,
16,
21,
16,
5743,
16,
389,
18991,
1769,
203,
5411,
3656,
2864,
43,
530,
63,
67,
18991,
6362,
67,
2
] |
./full_match/1/0xc258fF338322b6852C281936D4EdEff8AdfF23eE/sources/src/sgSender.sol | address for the pancake swap router
| address public immutable pancakeSwapRouterAddress; | 4,833,545 | [
1,
2867,
364,
326,
2800,
23780,
7720,
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,
1758,
1071,
11732,
2800,
23780,
12521,
8259,
1887,
31,
3639,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/utils/Counters.sol
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_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);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.8.0;
/**
* @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 {}
}
// File: contracts/lowgas.sol
// Amended by HashLips
/**
!Disclaimer!
These contracts have been used to create tutorials,
and was created for the purpose to teach people
how to create smart contracts on the blockchain.
please review this code on your own before using any of
the following code for production.
The developer will not be responsible or liable for all loss or
damage whatsoever caused by you participating in any way in the
experimental code, whether putting money into the contract or
using the code for your own project.
*/
pragma solidity >=0.7.0 <0.9.0;
contract MetaVoyager is ERC721, Ownable {
using Strings for uint256;
using Counters for Counters.Counter;
Counters.Counter private supply;
string public uriPrefix = "";
string public uriSuffix = ".json";
string public hiddenMetadataUri;
uint256 public cost = 0.01 ether;
uint256 public maxSupply = 10000;
uint256 public maxMintAmountPerTx = 5;
bool public paused = true;
bool public revealed = false;
constructor() ERC721("MetaVoyager", "MV") {
setHiddenMetadataUri("ipfs://__CID__/hidden.json");
}
modifier mintCompliance(uint256 _mintAmount) {
require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!");
require(supply.current() + _mintAmount <= maxSupply, "Max supply exceeded!");
_;
}
function totalSupply() public view returns (uint256) {
return supply.current();
}
function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) {
require(!paused, "The contract is paused!");
require(msg.value >= cost * _mintAmount, "Insufficient funds!");
_mintLoop(msg.sender, _mintAmount);
}
function mintForAddress(uint256 _mintAmount, address _receiver) public mintCompliance(_mintAmount) onlyOwner {
_mintLoop(_receiver, _mintAmount);
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount);
uint256 currentTokenId = 1;
uint256 ownedTokenIndex = 0;
while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) {
address currentTokenOwner = ownerOf(currentTokenId);
if (currentTokenOwner == _owner) {
ownedTokenIds[ownedTokenIndex] = currentTokenId;
ownedTokenIndex++;
}
currentTokenId++;
}
return ownedTokenIds;
}
function tokenURI(uint256 _tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(_tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if (revealed == false) {
return hiddenMetadataUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix))
: "";
}
function setRevealed(bool _state) public onlyOwner {
revealed = _state;
}
function setCost(uint256 _cost) public onlyOwner {
cost = _cost;
}
function setMaxMintAmountPerTx(uint256 _maxMintAmountPerTx) public onlyOwner {
maxMintAmountPerTx = _maxMintAmountPerTx;
}
function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner {
hiddenMetadataUri = _hiddenMetadataUri;
}
function setUriPrefix(string memory _uriPrefix) public onlyOwner {
uriPrefix = _uriPrefix;
}
function setUriSuffix(string memory _uriSuffix) public onlyOwner {
uriSuffix = _uriSuffix;
}
function setPaused(bool _state) public onlyOwner {
paused = _state;
}
function withdraw() public onlyOwner {
// This will pay HashLips 5% of the initial sale.
// You can remove this if you want, or keep it in to support HashLips and his channel.
// =============================================================================
(bool hs, ) = payable(0x943590A42C27D08e3744202c4Ae5eD55c2dE240D).call{value: address(this).balance * 5 / 100}("");
require(hs);
// =============================================================================
// This will transfer the remaining contract balance to the owner.
// Do not remove this otherwise you will not be able to withdraw the funds.
// =============================================================================
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
require(os);
// =============================================================================
}
function _mintLoop(address _receiver, uint256 _mintAmount) internal {
for (uint256 i = 0; i < _mintAmount; i++) {
supply.increment();
_safeMint(_receiver, supply.current());
}
}
function _baseURI() internal view virtual override returns (string memory) {
return uriPrefix;
}
} | File: contracts/lowgas.sol Amended by HashLips*/ | contract MetaVoyager is ERC721, Ownable {
using Strings for uint256;
using Counters for Counters.Counter;
Counters.Counter private supply;
string public uriPrefix = "";
string public uriSuffix = ".json";
string public hiddenMetadataUri;
uint256 public cost = 0.01 ether;
uint256 public maxSupply = 10000;
uint256 public maxMintAmountPerTx = 5;
bool public paused = true;
bool public revealed = false;
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
}
!Disclaimer!
These contracts have been used to create tutorials,
and was created for the purpose to teach people
how to create smart contracts on the blockchain.
please review this code on your own before using any of
the following code for production.
The developer will not be responsible or liable for all loss or
damage whatsoever caused by you participating in any way in the
experimental code, whether putting money into the contract or
using the code for your own project.
pragma solidity >=0.7.0 <0.9.0;
constructor() ERC721("MetaVoyager", "MV") {
}
modifier mintCompliance(uint256 _mintAmount) {
require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!");
require(supply.current() + _mintAmount <= maxSupply, "Max supply exceeded!");
_;
}
function totalSupply() public view returns (uint256) {
return supply.current();
}
function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) {
require(!paused, "The contract is paused!");
require(msg.value >= cost * _mintAmount, "Insufficient funds!");
_mintLoop(msg.sender, _mintAmount);
}
function mintForAddress(uint256 _mintAmount, address _receiver) public mintCompliance(_mintAmount) onlyOwner {
_mintLoop(_receiver, _mintAmount);
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount);
uint256 currentTokenId = 1;
uint256 ownedTokenIndex = 0;
while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) {
address currentTokenOwner = ownerOf(currentTokenId);
if (currentTokenOwner == _owner) {
ownedTokenIds[ownedTokenIndex] = currentTokenId;
ownedTokenIndex++;
}
currentTokenId++;
}
return ownedTokenIds;
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount);
uint256 currentTokenId = 1;
uint256 ownedTokenIndex = 0;
while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) {
address currentTokenOwner = ownerOf(currentTokenId);
if (currentTokenOwner == _owner) {
ownedTokenIds[ownedTokenIndex] = currentTokenId;
ownedTokenIndex++;
}
currentTokenId++;
}
return ownedTokenIds;
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount);
uint256 currentTokenId = 1;
uint256 ownedTokenIndex = 0;
while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) {
address currentTokenOwner = ownerOf(currentTokenId);
if (currentTokenOwner == _owner) {
ownedTokenIds[ownedTokenIndex] = currentTokenId;
ownedTokenIndex++;
}
currentTokenId++;
}
return ownedTokenIds;
}
function tokenURI(uint256 _tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(_tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if (revealed == false) {
return hiddenMetadataUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix))
: "";
}
function tokenURI(uint256 _tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(_tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if (revealed == false) {
return hiddenMetadataUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix))
: "";
}
function setRevealed(bool _state) public onlyOwner {
revealed = _state;
}
function setCost(uint256 _cost) public onlyOwner {
cost = _cost;
}
function setMaxMintAmountPerTx(uint256 _maxMintAmountPerTx) public onlyOwner {
maxMintAmountPerTx = _maxMintAmountPerTx;
}
function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner {
hiddenMetadataUri = _hiddenMetadataUri;
}
function setUriPrefix(string memory _uriPrefix) public onlyOwner {
uriPrefix = _uriPrefix;
}
function setUriSuffix(string memory _uriSuffix) public onlyOwner {
uriSuffix = _uriSuffix;
}
function setPaused(bool _state) public onlyOwner {
paused = _state;
}
function withdraw() public onlyOwner {
require(hs);
require(os);
}
(bool hs, ) = payable(0x943590A42C27D08e3744202c4Ae5eD55c2dE240D).call{value: address(this).balance * 5 / 100}("");
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
function _mintLoop(address _receiver, uint256 _mintAmount) internal {
for (uint256 i = 0; i < _mintAmount; i++) {
supply.increment();
_safeMint(_receiver, supply.current());
}
}
function _mintLoop(address _receiver, uint256 _mintAmount) internal {
for (uint256 i = 0; i < _mintAmount; i++) {
supply.increment();
_safeMint(_receiver, supply.current());
}
}
function _baseURI() internal view virtual override returns (string memory) {
return uriPrefix;
}
} | 10,481,790 | [
1,
812,
30,
20092,
19,
821,
31604,
18,
18281,
3986,
3934,
635,
2474,
48,
7146,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
6565,
58,
13372,
6817,
353,
4232,
39,
27,
5340,
16,
14223,
6914,
288,
203,
225,
1450,
8139,
364,
2254,
5034,
31,
203,
225,
1450,
9354,
87,
364,
9354,
87,
18,
4789,
31,
203,
203,
225,
9354,
87,
18,
4789,
3238,
14467,
31,
203,
203,
225,
533,
1071,
2003,
2244,
273,
1408,
31,
203,
225,
533,
1071,
2003,
5791,
273,
3552,
1977,
14432,
203,
225,
533,
1071,
5949,
2277,
3006,
31,
203,
21281,
225,
2254,
5034,
1071,
6991,
273,
374,
18,
1611,
225,
2437,
31,
203,
225,
2254,
5034,
1071,
943,
3088,
1283,
273,
12619,
31,
203,
225,
2254,
5034,
1071,
943,
49,
474,
6275,
2173,
4188,
273,
1381,
31,
203,
203,
225,
1426,
1071,
17781,
273,
638,
31,
203,
225,
1426,
1071,
283,
537,
18931,
273,
629,
31,
203,
203,
565,
445,
389,
5771,
1345,
5912,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
1147,
548,
203,
97,
203,
203,
203,
203,
203,
565,
401,
1669,
830,
69,
4417,
5,
203,
203,
565,
8646,
20092,
1240,
2118,
1399,
358,
752,
268,
22378,
87,
16,
203,
565,
471,
1703,
2522,
364,
326,
13115,
358,
6489,
497,
16951,
203,
565,
3661,
358,
752,
13706,
20092,
603,
326,
16766,
18,
203,
565,
9582,
10725,
333,
981,
603,
3433,
4953,
1865,
1450,
1281,
434,
203,
565,
326,
3751,
981,
364,
12449,
18,
203,
565,
1021,
8751,
903,
486,
506,
14549,
578,
328,
2214,
364,
777,
8324,
578,
7010,
565,
302,
301,
410,
4121,
2048,
6084,
15848,
635,
1846,
30891,
1776,
2
] |
pragma solidity ^0.6.2;
// SPDX-License-Identifier: MIT
abstract contract Context {
function _MSGSENDER583() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA879() 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;
}
}
// SPDX-License-Identifier: MIT
interface IERC20 {
function TOTALSUPPLY430() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF616(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER244(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE387(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE425(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM381(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER617(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL460(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// SPDX-License-Identifier: MIT
library SafeMath {
function ADD135(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB321(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB321(a, b, "SafeMath: subtraction overflow");
}
function SUB321(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 MUL733(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 DIV136(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV136(a, b, "SafeMath: division by zero");
}
function DIV136(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 MOD593(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD593(a, b, "SafeMath: modulo by zero");
}
function MOD593(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
library Address {
function ISCONTRACT469(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
function SENDVALUE193(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 FUNCTIONCALL340(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALL340(target, data, "Address: low-level call failed");
}
function FUNCTIONCALL340(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return _FUNCTIONCALLWITHVALUE922(target, data, 0, errorMessage);
}
function FUNCTIONCALLWITHVALUE944(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALLWITHVALUE944(target, data, value, "Address: low-level call with value failed");
}
function FUNCTIONCALLWITHVALUE944(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 _FUNCTIONCALLWITHVALUE922(target, data, value, errorMessage);
}
function _FUNCTIONCALLWITHVALUE922(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING
require(ISCONTRACT469(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
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 NAME100() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL131() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS904() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
function TOTALSUPPLY430() public view override returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF616(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER244(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER73(_MSGSENDER583(), recipient, amount);
return true;
}
function ALLOWANCE387(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE425(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_APPROVE319(_MSGSENDER583(), spender, amount);
return true;
}
function TRANSFERFROM381(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER73(sender, recipient, amount);
_APPROVE319(sender, _MSGSENDER583(), _allowances[sender][_MSGSENDER583()].SUB321(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE808(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE319(_MSGSENDER583(), spender, _allowances[_MSGSENDER583()][spender].ADD135(addedValue));
return true;
}
function DECREASEALLOWANCE515(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE319(_MSGSENDER583(), spender, _allowances[_MSGSENDER583()][spender].SUB321(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER73(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");
_BEFORETOKENTRANSFER129(sender, recipient, amount);
_balances[sender] = _balances[sender].SUB321(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD135(amount);
emit TRANSFER617(sender, recipient, amount);
}
function _MINT517(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER129(address(0), account, amount);
_totalSupply = _totalSupply.ADD135(amount);
_balances[account] = _balances[account].ADD135(amount);
emit TRANSFER617(address(0), account, amount);
}
function _BURN171(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_BEFORETOKENTRANSFER129(account, address(0), amount);
_balances[account] = _balances[account].SUB321(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB321(amount);
emit TRANSFER617(account, address(0), amount);
}
function _APPROVE319(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 APPROVAL460(owner, spender, amount);
}
function _SETUPDECIMALS874(uint8 decimals_) internal { //inject NONSTANDARD NAMING
_decimals = decimals_;
}
function _BEFORETOKENTRANSFER129(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING
}
// SPDX-License-Identifier: MIT
abstract contract ERC20Capped is ERC20 {
uint256 private _cap;
constructor (uint256 cap) public {
require(cap > 0, "ERC20Capped: cap is 0");
_cap = cap;
}
function CAP360() public view returns (uint256) { //inject NONSTANDARD NAMING
return _cap;
}
function _BEFORETOKENTRANSFER129(address from, address to, uint256 amount) internal virtual override { //inject NONSTANDARD NAMING
super._BEFORETOKENTRANSFER129(from, to, amount);
if (from == address(0)) { // When minting tokens
require(TOTALSUPPLY430().ADD135(amount) <= _cap, "ERC20Capped: cap exceeded");
}
}
}
// SPDX-License-Identifier: MIT
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED797(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
address msgSender = _MSGSENDER583();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED797(address(0), msgSender);
}
function OWNER971() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER607() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER583(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP525() public virtual ONLYOWNER607 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED797(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP777(address newOwner) public virtual ONLYOWNER607 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED797(_owner, newOwner);
_owner = newOwner;
}
}
interface IUniswapV2Router01 {
function FACTORY439() external pure returns (address); //inject NONSTANDARD NAMING
function WETH181() external pure returns (address); //inject NONSTANDARD NAMING
function ADDLIQUIDITY85( //inject NONSTANDARD NAMING
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function ADDLIQUIDITYETH216( //inject NONSTANDARD NAMING
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function REMOVELIQUIDITY344( //inject NONSTANDARD NAMING
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function REMOVELIQUIDITYETH742( //inject NONSTANDARD NAMING
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function REMOVELIQUIDITYWITHPERMIT491( //inject NONSTANDARD NAMING
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function REMOVELIQUIDITYETHWITHPERMIT317( //inject NONSTANDARD NAMING
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function SWAPEXACTTOKENSFORTOKENS917( //inject NONSTANDARD NAMING
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function SWAPTOKENSFOREXACTTOKENS879( //inject NONSTANDARD NAMING
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function SWAPEXACTETHFORTOKENS817(uint amountOutMin, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING
external
payable
returns (uint[] memory amounts);
function SWAPTOKENSFOREXACTETH856(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING
external
returns (uint[] memory amounts);
function SWAPEXACTTOKENSFORETH218(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING
external
returns (uint[] memory amounts);
function SWAPETHFOREXACTTOKENS998(uint amountOut, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING
external
payable
returns (uint[] memory amounts);
function QUOTE315(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); //inject NONSTANDARD NAMING
function GETAMOUNTOUT816(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); //inject NONSTANDARD NAMING
function GETAMOUNTIN684(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); //inject NONSTANDARD NAMING
function GETAMOUNTSOUT241(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); //inject NONSTANDARD NAMING
function GETAMOUNTSIN775(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); //inject NONSTANDARD NAMING
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function REMOVELIQUIDITYETHSUPPORTINGFEEONTRANSFERTOKENS846( //inject NONSTANDARD NAMING
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function REMOVELIQUIDITYETHWITHPERMITSUPPORTINGFEEONTRANSFERTOKENS1( //inject NONSTANDARD NAMING
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function SWAPEXACTTOKENSFORTOKENSSUPPORTINGFEEONTRANSFERTOKENS219( //inject NONSTANDARD NAMING
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function SWAPEXACTETHFORTOKENSSUPPORTINGFEEONTRANSFERTOKENS501( //inject NONSTANDARD NAMING
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function SWAPEXACTTOKENSFORETHSUPPORTINGFEEONTRANSFERTOKENS54( //inject NONSTANDARD NAMING
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
interface IUniswapV2Pair {
event APPROVAL460(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
event TRANSFER617(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
function NAME100() external pure returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL131() external pure returns (string memory); //inject NONSTANDARD NAMING
function DECIMALS904() external pure returns (uint8); //inject NONSTANDARD NAMING
function TOTALSUPPLY430() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF616(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function ALLOWANCE387(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE425(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFER244(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM381(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function DOMAIN_SEPARATOR749() external view returns (bytes32); //inject NONSTANDARD NAMING
function PERMIT_TYPEHASH945() external pure returns (bytes32); //inject NONSTANDARD NAMING
function NONCES546(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function PERMIT654(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING
event MINT786(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING
event BURN405(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING
event SWAP722( //inject NONSTANDARD NAMING
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event SYNC303(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING
function MINIMUM_LIQUIDITY735() external pure returns (uint); //inject NONSTANDARD NAMING
function FACTORY439() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN0934() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN1318() external view returns (address); //inject NONSTANDARD NAMING
function GETRESERVES691() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING
function PRICE0CUMULATIVELAST150() external view returns (uint); //inject NONSTANDARD NAMING
function PRICE1CUMULATIVELAST277() external view returns (uint); //inject NONSTANDARD NAMING
function KLAST634() external view returns (uint); //inject NONSTANDARD NAMING
function MINT615(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING
function BURN664(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING
function SWAP816(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING
function SKIM21(address to) external; //inject NONSTANDARD NAMING
function SYNC269() external; //inject NONSTANDARD NAMING
function INITIALIZE267(address, address) external; //inject NONSTANDARD NAMING
}
interface IUniswapV2Factory {
event PAIRCREATED762(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING
function FEETO789() external view returns (address); //inject NONSTANDARD NAMING
function FEETOSETTER578() external view returns (address); //inject NONSTANDARD NAMING
function GETPAIR592(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRS410(uint) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRSLENGTH90() external view returns (uint); //inject NONSTANDARD NAMING
function CREATEPAIR614(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING
function SETFEETO894(address) external; //inject NONSTANDARD NAMING
function SETFEETOSETTER1(address) external; //inject NONSTANDARD NAMING
}
interface IWETH {
function DEPOSIT145() external payable; //inject NONSTANDARD NAMING
function TRANSFER244(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function WITHDRAW78(uint) external; //inject NONSTANDARD NAMING
}
contract CGLB is ERC20Capped, Ownable {
using SafeMath for uint;
address public UNIPAIR;
address public DAI = address(0x6B175474E89094C44Da98b954EedeAC495271d0F);
IUniswapV2Router02 public UNIROUTER = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
IUniswapV2Factory public UNIFACTORY = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f);
bool public isRunning = false;
bool private liquidityFlag;
uint public constant supplycap690 = (10**4)*(10**18); //inject NONSTANDARD NAMING
uint public constant tokensforinitialliquidity143 = 3*(10**3)*(10**18); //inject NONSTANDARD NAMING
bytes32 public airdropRoot;
mapping (address => bool) public claimedAirdrop;
string public website = "www.cglb.fi";
constructor() public ERC20Capped(supplycap690) ERC20("Cant go lower boys", "CGLB") {
airdropRoot = 0x185065ab3d54b516ee3ed54dc30e04758300a4b41e207cf3ba91715f378d7728;
}
function TRANSFER244(address recipient, uint256 amount) //inject NONSTANDARD NAMING
public override
returns (bool) {
require(msg.sender == UNIPAIR || msg.sender == address(UNIROUTER));
super.TRANSFER244(recipient, amount);
return true;
}
function TRANSFERFROM381(address sender, address recipient, uint256 amount) //inject NONSTANDARD NAMING
public override
returns (bool) {
require(liquidityFlag);
_TRANSFER73(sender, recipient, amount);
return true;
}
function ADDLIQUIDITYTOUNISWAPPAIR951( //inject NONSTANDARD NAMING
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountDAIDesired,
uint256 amountDAImin
) public payable {
require(isRunning);
require(IERC20(DAI).TRANSFERFROM381(msg.sender, address(this), amountDAIDesired));
require(IERC20(DAI).APPROVE425(address(UNIROUTER), amountDAIDesired));
_TRANSFER73(msg.sender, address(this), amountTokenDesired);
liquidityFlag = true;
(uint amountToken, uint amountDAI, uint liquidity) = UNIROUTER.ADDLIQUIDITY85(
address(this),
DAI,
amountTokenDesired,
amountDAIDesired,
amountTokenMin,
amountDAImin,
msg.sender,
now + 10 minutes
);
liquidityFlag = false;
//sends dust back
if (amountTokenDesired - amountToken > 0 ) _TRANSFER73(address(this), msg.sender, amountTokenDesired-amountToken);
if (amountDAIDesired - amountDAI > 0) require(IERC20(DAI).TRANSFER244(msg.sender, amountDAIDesired - amountDAI));
}
function ADDINITIALLIQUIDITYWITHPAIR729() public ONLYOWNER607 { //inject NONSTANDARD NAMING
CREATEUNISWAPPAIR64();
uint256 amountDAI = IERC20(DAI).BALANCEOF616(address(this));
require(IERC20(DAI).TRANSFER244(UNIPAIR, amountDAI));
_MINT517(UNIPAIR, tokensforinitialliquidity143);
IUniswapV2Pair(UNIPAIR).MINT615(msg.sender);
isRunning = true;
}
function ADDINITIALLIQUIDITY209() public ONLYOWNER607 { //inject NONSTANDARD NAMING
uint256 amountDAI = IERC20(DAI).BALANCEOF616(address(this));
require(IERC20(DAI).TRANSFER244(UNIPAIR, amountDAI));
_MINT517(UNIPAIR, tokensforinitialliquidity143);
IUniswapV2Pair(UNIPAIR).MINT615(msg.sender);
isRunning = true;
}
function SETAIRDROPROOT894(bytes32 _root) public ONLYOWNER607 { //inject NONSTANDARD NAMING
airdropRoot = _root;
}
function SETPAIR246(address _pair) public ONLYOWNER607 { //inject NONSTANDARD NAMING
UNIPAIR = _pair;
}
function CREATEUNISWAPPAIR64() internal { //inject NONSTANDARD NAMING
require(UNIPAIR == address(0), "Token: pool already created");
UNIPAIR = UNIFACTORY.CREATEPAIR614(
DAI,
address(this)
);
}
function CHECKPROOF499(bytes memory proof, bytes32 root, bytes32 hash) internal view returns (bool) { //inject NONSTANDARD NAMING
bytes32 el;
bytes32 h = hash;
for (uint256 i = 32; i <= proof.length; i += 32) {
assembly {
el := mload(add(proof, i))
}
if (h < el) {
h = keccak256(abi.encodePacked(h, el));
} else {
h = keccak256(abi.encodePacked(el, h));
}
}
return h == root;
}
function CLAIMAIRDROP701(bytes memory proof, uint amount) public { //inject NONSTANDARD NAMING
require(!claimedAirdrop[msg.sender]);
bytes32 hash = keccak256(abi.encodePacked(msg.sender, amount));
require(CHECKPROOF499(proof, airdropRoot, hash), "Invalid proof");
claimedAirdrop[msg.sender] = true;
_MINT517(msg.sender, amount);
}
function WITHDRAWERC20742(address token) ONLYOWNER607 public { //inject NONSTANDARD NAMING
uint balance = IERC20(token).BALANCEOF616(address(this));
require(IERC20(token).TRANSFER244(msg.sender, balance));
}
} | inject NONSTANDARD NAMING
| function TRANSFER244(address recipient, uint256 amount) public virtual override returns (bool) { | 1,820,524 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4235,
17598,
3247,
24,
12,
2867,
8027,
16,
2254,
5034,
3844,
13,
1071,
5024,
3849,
1135,
261,
6430,
13,
288,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xf4Aa0f1013c81DBC7F87C5509F62268142a2975f/sources/contracts/lybra/governance/LybraGovernance.sol | * @dev Amount of votes already cast passes the threshold limit./ | function _quorumReached(uint256 proposalId) internal view override returns (bool){
mapping(uint8 => uint256) storage supportVotes = proposalData[proposalId].supportVotes;
uint256 forVotes = supportVotes[uint8(VoteType.For)];
uint256 abstainVotes = supportVotes[uint8(VoteType.Abstain)];
return forVotes + abstainVotes >= quorum(proposalSnapshot(proposalId));
}
| 3,136,121 | [
1,
6275,
434,
19588,
1818,
4812,
11656,
326,
5573,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
372,
16105,
23646,
12,
11890,
5034,
14708,
548,
13,
2713,
1476,
3849,
1135,
261,
6430,
15329,
203,
3639,
2874,
12,
11890,
28,
516,
2254,
5034,
13,
2502,
2865,
29637,
273,
14708,
751,
63,
685,
8016,
548,
8009,
13261,
29637,
31,
203,
3639,
2254,
5034,
364,
29637,
273,
2865,
29637,
63,
11890,
28,
12,
19338,
559,
18,
1290,
13,
15533,
203,
3639,
2254,
5034,
1223,
334,
530,
29637,
273,
2865,
29637,
63,
11890,
28,
12,
19338,
559,
18,
5895,
334,
530,
13,
15533,
203,
3639,
327,
364,
29637,
397,
1223,
334,
530,
29637,
1545,
31854,
12,
685,
8016,
4568,
12,
685,
8016,
548,
10019,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
// @unsupported: ovm
pragma solidity 0.8.9;
pragma experimental ABIEncoderV2;
import "../polygon/tunnel/FxBaseRootTunnel.sol";
import "./MessengerWrapper.sol";
/**
* @dev A MessengerWrapper for Polygon - https://docs.matic.network/docs
* @notice Deployed on layer-1
*/
contract PolygonMessengerWrapper is FxBaseRootTunnel, MessengerWrapper {
constructor(
address _l1BridgeAddress,
address _checkpointManager,
address _fxRoot,
address _fxChildTunnel
)
public
MessengerWrapper(_l1BridgeAddress)
FxBaseRootTunnel(_checkpointManager, _fxRoot)
{
setFxChildTunnel(_fxChildTunnel);
}
/**
* @dev Sends a message to the l2MessengerProxy from layer-1
* @param _calldata The data that l2MessengerProxy will be called with
* @notice The msg.sender is sent to the L2_PolygonMessengerProxy and checked there.
*/
function sendCrossDomainMessage(bytes memory _calldata) public override {
_sendMessageToChild(
abi.encode(msg.sender, _calldata)
);
}
function verifySender(address l1BridgeCaller, bytes memory /*_data*/) public view override {
require(l1BridgeCaller == address(this), "L1_PLGN_WPR: Caller must be this contract");
}
function _processMessageFromChild(bytes memory message) internal override {
(bool success,) = l1BridgeAddress.call(message);
require(success, "L1_PLGN_WPR: Call to L1 Bridge failed");
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {RLPReader} from "../lib/RLPReader.sol";
import {MerklePatriciaProof} from "../lib/MerklePatriciaProof.sol";
import {Merkle} from "../lib/Merkle.sol";
import "../lib/ExitPayloadReader.sol";
interface IFxStateSender {
function sendMessageToChild(address _receiver, bytes calldata _data) external;
}
contract ICheckpointManager {
struct HeaderBlock {
bytes32 root;
uint256 start;
uint256 end;
uint256 createdAt;
address proposer;
}
/**
* @notice mapping of checkpoint header numbers to block details
* @dev These checkpoints are submited by plasma contracts
*/
mapping(uint256 => HeaderBlock) public headerBlocks;
}
abstract contract FxBaseRootTunnel {
using RLPReader for RLPReader.RLPItem;
using Merkle for bytes32;
using ExitPayloadReader for bytes;
using ExitPayloadReader for ExitPayloadReader.ExitPayload;
using ExitPayloadReader for ExitPayloadReader.Log;
using ExitPayloadReader for ExitPayloadReader.LogTopics;
using ExitPayloadReader for ExitPayloadReader.Receipt;
// keccak256(MessageSent(bytes))
bytes32 public constant SEND_MESSAGE_EVENT_SIG = 0x8c5261668696ce22758910d05bab8f186d6eb247ceac2af2e82c7dc17669b036;
// state sender contract
IFxStateSender public fxRoot;
// root chain manager
ICheckpointManager public checkpointManager;
// child tunnel contract which receives and sends messages
address public fxChildTunnel;
// storage to avoid duplicate exits
mapping(bytes32 => bool) public processedExits;
constructor(address _checkpointManager, address _fxRoot) {
checkpointManager = ICheckpointManager(_checkpointManager);
fxRoot = IFxStateSender(_fxRoot);
}
// set fxChildTunnel if not set already
function setFxChildTunnel(address _fxChildTunnel) public {
require(fxChildTunnel == address(0x0), "FxBaseRootTunnel: CHILD_TUNNEL_ALREADY_SET");
fxChildTunnel = _fxChildTunnel;
}
/**
* @notice Send bytes message to Child Tunnel
* @param message bytes message that will be sent to Child Tunnel
* some message examples -
* abi.encode(tokenId);
* abi.encode(tokenId, tokenMetadata);
* abi.encode(messageType, messageData);
*/
function _sendMessageToChild(bytes memory message) internal {
fxRoot.sendMessageToChild(fxChildTunnel, message);
}
function _validateAndExtractMessage(bytes memory inputData) internal returns (bytes memory) {
ExitPayloadReader.ExitPayload memory payload = inputData.toExitPayload();
bytes memory branchMaskBytes = payload.getBranchMaskAsBytes();
uint256 blockNumber = payload.getBlockNumber();
// checking if exit has already been processed
// unique exit is identified using hash of (blockNumber, branchMask, receiptLogIndex)
bytes32 exitHash = keccak256(
abi.encodePacked(
blockNumber,
// first 2 nibbles are dropped while generating nibble array
// this allows branch masks that are valid but bypass exitHash check (changing first 2 nibbles only)
// so converting to nibble array and then hashing it
MerklePatriciaProof._getNibbleArray(branchMaskBytes),
payload.getReceiptLogIndex()
)
);
require(processedExits[exitHash] == false, "FxRootTunnel: EXIT_ALREADY_PROCESSED");
processedExits[exitHash] = true;
ExitPayloadReader.Receipt memory receipt = payload.getReceipt();
ExitPayloadReader.Log memory log = receipt.getLog();
// check child tunnel
require(fxChildTunnel == log.getEmitter(), "FxRootTunnel: INVALID_FX_CHILD_TUNNEL");
bytes32 receiptRoot = payload.getReceiptRoot();
// verify receipt inclusion
require(
MerklePatriciaProof.verify(receipt.toBytes(), branchMaskBytes, payload.getReceiptProof(), receiptRoot),
"FxRootTunnel: INVALID_RECEIPT_PROOF"
);
// verify checkpoint inclusion
_checkBlockMembershipInCheckpoint(
blockNumber,
payload.getBlockTime(),
payload.getTxRoot(),
receiptRoot,
payload.getHeaderNumber(),
payload.getBlockProof()
);
ExitPayloadReader.LogTopics memory topics = log.getTopics();
require(
bytes32(topics.getField(0).toUint()) == SEND_MESSAGE_EVENT_SIG, // topic0 is event sig
"FxRootTunnel: INVALID_SIGNATURE"
);
// received message data
bytes memory message = abi.decode(log.getData(), (bytes)); // event decodes params again, so decoding bytes to get message
return message;
}
function _checkBlockMembershipInCheckpoint(
uint256 blockNumber,
uint256 blockTime,
bytes32 txRoot,
bytes32 receiptRoot,
uint256 headerNumber,
bytes memory blockProof
) private view returns (uint256) {
(bytes32 headerRoot, uint256 startBlock, , uint256 createdAt, ) = checkpointManager.headerBlocks(headerNumber);
require(
keccak256(abi.encodePacked(blockNumber, blockTime, txRoot, receiptRoot)).checkMembership(
blockNumber - startBlock,
headerRoot,
blockProof
),
"FxRootTunnel: INVALID_HEADER"
);
return createdAt;
}
/**
* @notice receive message from L2 to L1, validated by proof
* @dev This function verifies if the transaction actually happened on child chain
*
* @param inputData RLP encoded data of the reference tx containing following list of fields
* 0 - headerNumber - Checkpoint header block number containing the reference tx
* 1 - blockProof - Proof that the block header (in the child chain) is a leaf in the submitted merkle root
* 2 - blockNumber - Block number containing the reference tx on child chain
* 3 - blockTime - Reference tx block time
* 4 - txRoot - Transactions root of block
* 5 - receiptRoot - Receipts root of block
* 6 - receipt - Receipt of the reference transaction
* 7 - receiptProof - Merkle proof of the reference receipt
* 8 - branchMask - 32 bits denoting the path of receipt in merkle tree
* 9 - receiptLogIndex - Log Index to read from the receipt
*/
function receiveMessage(bytes memory inputData) public virtual {
bytes memory message = _validateAndExtractMessage(inputData);
_processMessageFromChild(message);
}
/**
* @notice Process message received from Child Tunnel
* @dev function needs to be implemented to handle message as per requirement
* This is called by onStateReceive function.
* Since it is called via a system call, any event will not be emitted during its execution.
* @param message bytes message that was sent from Child Tunnel
*/
function _processMessageFromChild(bytes memory message) internal virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <=0.8.9;
pragma experimental ABIEncoderV2;
import "../interfaces/IMessengerWrapper.sol";
abstract contract MessengerWrapper is IMessengerWrapper {
address public immutable l1BridgeAddress;
constructor(address _l1BridgeAddress) internal {
l1BridgeAddress = _l1BridgeAddress;
}
modifier onlyL1Bridge {
require(msg.sender == l1BridgeAddress, "MW: Sender must be the L1 Bridge");
_;
}
}
/*
* @author Hamdi Allam [email protected]
* Please reach out with any questions or concerns
*/
pragma solidity ^0.8.0;
library RLPReader {
uint8 constant STRING_SHORT_START = 0x80;
uint8 constant STRING_LONG_START = 0xb8;
uint8 constant LIST_SHORT_START = 0xc0;
uint8 constant LIST_LONG_START = 0xf8;
uint8 constant WORD_SIZE = 32;
struct RLPItem {
uint256 len;
uint256 memPtr;
}
struct Iterator {
RLPItem item; // Item that's being iterated over.
uint256 nextPtr; // Position of the next item in the list.
}
/*
* @dev Returns the next element in the iteration. Reverts if it has not next element.
* @param self The iterator.
* @return The next element in the iteration.
*/
function next(Iterator memory self) internal pure returns (RLPItem memory) {
require(hasNext(self));
uint256 ptr = self.nextPtr;
uint256 itemLength = _itemLength(ptr);
self.nextPtr = ptr + itemLength;
return RLPItem(itemLength, ptr);
}
/*
* @dev Returns true if the iteration has more elements.
* @param self The iterator.
* @return true if the iteration has more elements.
*/
function hasNext(Iterator memory self) internal pure returns (bool) {
RLPItem memory item = self.item;
return self.nextPtr < item.memPtr + item.len;
}
/*
* @param item RLP encoded bytes
*/
function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) {
uint256 memPtr;
assembly {
memPtr := add(item, 0x20)
}
return RLPItem(item.length, memPtr);
}
/*
* @dev Create an iterator. Reverts if item is not a list.
* @param self The RLP item.
* @return An 'Iterator' over the item.
*/
function iterator(RLPItem memory self) internal pure returns (Iterator memory) {
require(isList(self));
uint256 ptr = self.memPtr + _payloadOffset(self.memPtr);
return Iterator(self, ptr);
}
/*
* @param item RLP encoded bytes
*/
function rlpLen(RLPItem memory item) internal pure returns (uint256) {
return item.len;
}
/*
* @param item RLP encoded bytes
*/
function payloadLen(RLPItem memory item) internal pure returns (uint256) {
return item.len - _payloadOffset(item.memPtr);
}
/*
* @param item RLP encoded list in bytes
*/
function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) {
require(isList(item));
uint256 items = numItems(item);
RLPItem[] memory result = new RLPItem[](items);
uint256 memPtr = item.memPtr + _payloadOffset(item.memPtr);
uint256 dataLen;
for (uint256 i = 0; i < items; i++) {
dataLen = _itemLength(memPtr);
result[i] = RLPItem(dataLen, memPtr);
memPtr = memPtr + dataLen;
}
return result;
}
// @return indicator whether encoded payload is a list. negate this function call for isData.
function isList(RLPItem memory item) internal pure returns (bool) {
if (item.len == 0) return false;
uint8 byte0;
uint256 memPtr = item.memPtr;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < LIST_SHORT_START) return false;
return true;
}
/*
* @dev A cheaper version of keccak256(toRlpBytes(item)) that avoids copying memory.
* @return keccak256 hash of RLP encoded bytes.
*/
function rlpBytesKeccak256(RLPItem memory item) internal pure returns (bytes32) {
uint256 ptr = item.memPtr;
uint256 len = item.len;
bytes32 result;
assembly {
result := keccak256(ptr, len)
}
return result;
}
function payloadLocation(RLPItem memory item) internal pure returns (uint256, uint256) {
uint256 offset = _payloadOffset(item.memPtr);
uint256 memPtr = item.memPtr + offset;
uint256 len = item.len - offset; // data length
return (memPtr, len);
}
/*
* @dev A cheaper version of keccak256(toBytes(item)) that avoids copying memory.
* @return keccak256 hash of the item payload.
*/
function payloadKeccak256(RLPItem memory item) internal pure returns (bytes32) {
(uint256 memPtr, uint256 len) = payloadLocation(item);
bytes32 result;
assembly {
result := keccak256(memPtr, len)
}
return result;
}
/** RLPItem conversions into data types **/
// @returns raw rlp encoding in bytes
function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) {
bytes memory result = new bytes(item.len);
if (result.length == 0) return result;
uint256 ptr;
assembly {
ptr := add(0x20, result)
}
copy(item.memPtr, ptr, item.len);
return result;
}
// any non-zero byte is considered true
function toBoolean(RLPItem memory item) internal pure returns (bool) {
require(item.len == 1);
uint256 result;
uint256 memPtr = item.memPtr;
assembly {
result := byte(0, mload(memPtr))
}
return result == 0 ? false : true;
}
function toAddress(RLPItem memory item) internal pure returns (address) {
// 1 byte for the length prefix
require(item.len == 21);
return address(uint160(toUint(item)));
}
function toUint(RLPItem memory item) internal pure returns (uint256) {
require(item.len > 0 && item.len <= 33);
uint256 offset = _payloadOffset(item.memPtr);
uint256 len = item.len - offset;
uint256 result;
uint256 memPtr = item.memPtr + offset;
assembly {
result := mload(memPtr)
// shfit to the correct location if neccesary
if lt(len, 32) {
result := div(result, exp(256, sub(32, len)))
}
}
return result;
}
// enforces 32 byte length
function toUintStrict(RLPItem memory item) internal pure returns (uint256) {
// one byte prefix
require(item.len == 33);
uint256 result;
uint256 memPtr = item.memPtr + 1;
assembly {
result := mload(memPtr)
}
return result;
}
function toBytes(RLPItem memory item) internal pure returns (bytes memory) {
require(item.len > 0);
uint256 offset = _payloadOffset(item.memPtr);
uint256 len = item.len - offset; // data length
bytes memory result = new bytes(len);
uint256 destPtr;
assembly {
destPtr := add(0x20, result)
}
copy(item.memPtr + offset, destPtr, len);
return result;
}
/*
* Private Helpers
*/
// @return number of payload items inside an encoded list.
function numItems(RLPItem memory item) private pure returns (uint256) {
if (item.len == 0) return 0;
uint256 count = 0;
uint256 currPtr = item.memPtr + _payloadOffset(item.memPtr);
uint256 endPtr = item.memPtr + item.len;
while (currPtr < endPtr) {
currPtr = currPtr + _itemLength(currPtr); // skip over an item
count++;
}
return count;
}
// @return entire rlp item byte length
function _itemLength(uint256 memPtr) private pure returns (uint256) {
uint256 itemLen;
uint256 byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START) itemLen = 1;
else if (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START + 1;
else if (byte0 < LIST_SHORT_START) {
assembly {
let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is
memPtr := add(memPtr, 1) // skip over the first byte
/* 32 byte word size */
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len
itemLen := add(dataLen, add(byteLen, 1))
}
} else if (byte0 < LIST_LONG_START) {
itemLen = byte0 - LIST_SHORT_START + 1;
} else {
assembly {
let byteLen := sub(byte0, 0xf7)
memPtr := add(memPtr, 1)
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length
itemLen := add(dataLen, add(byteLen, 1))
}
}
return itemLen;
}
// @return number of bytes until the data
function _payloadOffset(uint256 memPtr) private pure returns (uint256) {
uint256 byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START) return 0;
else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)) return 1;
else if (byte0 < LIST_SHORT_START)
// being explicit
return byte0 - (STRING_LONG_START - 1) + 1;
else return byte0 - (LIST_LONG_START - 1) + 1;
}
/*
* @param src Pointer to source
* @param dest Pointer to destination
* @param len Amount of memory to copy from the source
*/
function copy(
uint256 src,
uint256 dest,
uint256 len
) private pure {
if (len == 0) return;
// copy as many word sizes as possible
for (; len >= WORD_SIZE; len -= WORD_SIZE) {
assembly {
mstore(dest, mload(src))
}
src += WORD_SIZE;
dest += WORD_SIZE;
}
if (len == 0) return;
// left over bytes. Mask is used to remove unwanted bytes from the word
uint256 mask = 256**(WORD_SIZE - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask)) // zero out src
let destpart := and(mload(dest), mask) // retrieve the bytes
mstore(dest, or(destpart, srcpart))
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {RLPReader} from "./RLPReader.sol";
library MerklePatriciaProof {
/*
* @dev Verifies a merkle patricia proof.
* @param value The terminating value in the trie.
* @param encodedPath The path in the trie leading to value.
* @param rlpParentNodes The rlp encoded stack of nodes.
* @param root The root hash of the trie.
* @return The boolean validity of the proof.
*/
function verify(
bytes memory value,
bytes memory encodedPath,
bytes memory rlpParentNodes,
bytes32 root
) internal pure returns (bool) {
RLPReader.RLPItem memory item = RLPReader.toRlpItem(rlpParentNodes);
RLPReader.RLPItem[] memory parentNodes = RLPReader.toList(item);
bytes memory currentNode;
RLPReader.RLPItem[] memory currentNodeList;
bytes32 nodeKey = root;
uint256 pathPtr = 0;
bytes memory path = _getNibbleArray(encodedPath);
if (path.length == 0) {
return false;
}
for (uint256 i = 0; i < parentNodes.length; i++) {
if (pathPtr > path.length) {
return false;
}
currentNode = RLPReader.toRlpBytes(parentNodes[i]);
if (nodeKey != keccak256(currentNode)) {
return false;
}
currentNodeList = RLPReader.toList(parentNodes[i]);
if (currentNodeList.length == 17) {
if (pathPtr == path.length) {
if (keccak256(RLPReader.toBytes(currentNodeList[16])) == keccak256(value)) {
return true;
} else {
return false;
}
}
uint8 nextPathNibble = uint8(path[pathPtr]);
if (nextPathNibble > 16) {
return false;
}
nodeKey = bytes32(RLPReader.toUintStrict(currentNodeList[nextPathNibble]));
pathPtr += 1;
} else if (currentNodeList.length == 2) {
uint256 traversed = _nibblesToTraverse(RLPReader.toBytes(currentNodeList[0]), path, pathPtr);
if (pathPtr + traversed == path.length) {
//leaf node
if (keccak256(RLPReader.toBytes(currentNodeList[1])) == keccak256(value)) {
return true;
} else {
return false;
}
}
//extension node
if (traversed == 0) {
return false;
}
pathPtr += traversed;
nodeKey = bytes32(RLPReader.toUintStrict(currentNodeList[1]));
} else {
return false;
}
}
}
function _nibblesToTraverse(
bytes memory encodedPartialPath,
bytes memory path,
uint256 pathPtr
) private pure returns (uint256) {
uint256 len = 0;
// encodedPartialPath has elements that are each two hex characters (1 byte), but partialPath
// and slicedPath have elements that are each one hex character (1 nibble)
bytes memory partialPath = _getNibbleArray(encodedPartialPath);
bytes memory slicedPath = new bytes(partialPath.length);
// pathPtr counts nibbles in path
// partialPath.length is a number of nibbles
for (uint256 i = pathPtr; i < pathPtr + partialPath.length; i++) {
bytes1 pathNibble = path[i];
slicedPath[i - pathPtr] = pathNibble;
}
if (keccak256(partialPath) == keccak256(slicedPath)) {
len = partialPath.length;
} else {
len = 0;
}
return len;
}
// bytes b must be hp encoded
function _getNibbleArray(bytes memory b) internal pure returns (bytes memory) {
bytes memory nibbles = "";
if (b.length > 0) {
uint8 offset;
uint8 hpNibble = uint8(_getNthNibbleOfBytes(0, b));
if (hpNibble == 1 || hpNibble == 3) {
nibbles = new bytes(b.length * 2 - 1);
bytes1 oddNibble = _getNthNibbleOfBytes(1, b);
nibbles[0] = oddNibble;
offset = 1;
} else {
nibbles = new bytes(b.length * 2 - 2);
offset = 0;
}
for (uint256 i = offset; i < nibbles.length; i++) {
nibbles[i] = _getNthNibbleOfBytes(i - offset + 2, b);
}
}
return nibbles;
}
function _getNthNibbleOfBytes(uint256 n, bytes memory str) private pure returns (bytes1) {
return bytes1(n % 2 == 0 ? uint8(str[n / 2]) / 0x10 : uint8(str[n / 2]) % 0x10);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library Merkle {
function checkMembership(
bytes32 leaf,
uint256 index,
bytes32 rootHash,
bytes memory proof
) internal pure returns (bool) {
require(proof.length % 32 == 0, "Invalid proof length");
uint256 proofHeight = proof.length / 32;
// Proof of size n means, height of the tree is n+1.
// In a tree of height n+1, max #leafs possible is 2 ^ n
require(index < 2**proofHeight, "Leaf index is too big");
bytes32 proofElement;
bytes32 computedHash = leaf;
for (uint256 i = 32; i <= proof.length; i += 32) {
assembly {
proofElement := mload(add(proof, i))
}
if (index % 2 == 0) {
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
index = index / 2;
}
return computedHash == rootHash;
}
}
pragma solidity ^0.8.0;
import {RLPReader} from "./RLPReader.sol";
library ExitPayloadReader {
using RLPReader for bytes;
using RLPReader for RLPReader.RLPItem;
uint8 constant WORD_SIZE = 32;
struct ExitPayload {
RLPReader.RLPItem[] data;
}
struct Receipt {
RLPReader.RLPItem[] data;
bytes raw;
uint256 logIndex;
}
struct Log {
RLPReader.RLPItem data;
RLPReader.RLPItem[] list;
}
struct LogTopics {
RLPReader.RLPItem[] data;
}
// copy paste of private copy() from RLPReader to avoid changing of existing contracts
function copy(
uint256 src,
uint256 dest,
uint256 len
) private pure {
if (len == 0) return;
// copy as many word sizes as possible
for (; len >= WORD_SIZE; len -= WORD_SIZE) {
assembly {
mstore(dest, mload(src))
}
src += WORD_SIZE;
dest += WORD_SIZE;
}
// left over bytes. Mask is used to remove unwanted bytes from the word
uint256 mask = 256**(WORD_SIZE - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask)) // zero out src
let destpart := and(mload(dest), mask) // retrieve the bytes
mstore(dest, or(destpart, srcpart))
}
}
function toExitPayload(bytes memory data) internal pure returns (ExitPayload memory) {
RLPReader.RLPItem[] memory payloadData = data.toRlpItem().toList();
return ExitPayload(payloadData);
}
function getHeaderNumber(ExitPayload memory payload) internal pure returns (uint256) {
return payload.data[0].toUint();
}
function getBlockProof(ExitPayload memory payload) internal pure returns (bytes memory) {
return payload.data[1].toBytes();
}
function getBlockNumber(ExitPayload memory payload) internal pure returns (uint256) {
return payload.data[2].toUint();
}
function getBlockTime(ExitPayload memory payload) internal pure returns (uint256) {
return payload.data[3].toUint();
}
function getTxRoot(ExitPayload memory payload) internal pure returns (bytes32) {
return bytes32(payload.data[4].toUint());
}
function getReceiptRoot(ExitPayload memory payload) internal pure returns (bytes32) {
return bytes32(payload.data[5].toUint());
}
function getReceipt(ExitPayload memory payload) internal pure returns (Receipt memory receipt) {
receipt.raw = payload.data[6].toBytes();
RLPReader.RLPItem memory receiptItem = receipt.raw.toRlpItem();
if (receiptItem.isList()) {
// legacy tx
receipt.data = receiptItem.toList();
} else {
// pop first byte before parsting receipt
bytes memory typedBytes = receipt.raw;
bytes memory result = new bytes(typedBytes.length - 1);
uint256 srcPtr;
uint256 destPtr;
assembly {
srcPtr := add(33, typedBytes)
destPtr := add(0x20, result)
}
copy(srcPtr, destPtr, result.length);
receipt.data = result.toRlpItem().toList();
}
receipt.logIndex = getReceiptLogIndex(payload);
return receipt;
}
function getReceiptProof(ExitPayload memory payload) internal pure returns (bytes memory) {
return payload.data[7].toBytes();
}
function getBranchMaskAsBytes(ExitPayload memory payload) internal pure returns (bytes memory) {
return payload.data[8].toBytes();
}
function getBranchMaskAsUint(ExitPayload memory payload) internal pure returns (uint256) {
return payload.data[8].toUint();
}
function getReceiptLogIndex(ExitPayload memory payload) internal pure returns (uint256) {
return payload.data[9].toUint();
}
// Receipt methods
function toBytes(Receipt memory receipt) internal pure returns (bytes memory) {
return receipt.raw;
}
function getLog(Receipt memory receipt) internal pure returns (Log memory) {
RLPReader.RLPItem memory logData = receipt.data[3].toList()[receipt.logIndex];
return Log(logData, logData.toList());
}
// Log methods
function getEmitter(Log memory log) internal pure returns (address) {
return RLPReader.toAddress(log.list[0]);
}
function getTopics(Log memory log) internal pure returns (LogTopics memory) {
return LogTopics(log.list[1].toList());
}
function getData(Log memory log) internal pure returns (bytes memory) {
return log.list[2].toBytes();
}
function toRlpBytes(Log memory log) internal pure returns (bytes memory) {
return log.data.toRlpBytes();
}
// LogTopics methods
function getField(LogTopics memory topics, uint256 index) internal pure returns (RLPReader.RLPItem memory) {
return topics.data[index];
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <=0.8.9;
pragma experimental ABIEncoderV2;
interface IMessengerWrapper {
function sendCrossDomainMessage(bytes memory _calldata) external;
function verifySender(address l1BridgeCaller, bytes memory _data) external;
} | Proof of size n means, height of the tree is n+1. In a tree of height n+1, max #leafs possible is 2 ^ n | ) internal pure returns (bool) {
require(proof.length % 32 == 0, "Invalid proof length");
uint256 proofHeight = proof.length / 32;
require(index < 2**proofHeight, "Leaf index is too big");
bytes32 proofElement;
bytes32 computedHash = leaf;
for (uint256 i = 32; i <= proof.length; i += 32) {
assembly {
proofElement := mload(add(proof, i))
}
if (index % 2 == 0) {
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
index = index / 2;
}
return computedHash == rootHash;
}
| 159,520 | [
1,
20439,
434,
963,
290,
4696,
16,
2072,
434,
326,
2151,
353,
290,
15,
21,
18,
657,
279,
2151,
434,
2072,
290,
15,
21,
16,
943,
7839,
87,
3323,
353,
576,
3602,
290,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
262,
2713,
16618,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
12,
24207,
18,
2469,
738,
3847,
422,
374,
16,
315,
1941,
14601,
769,
8863,
203,
3639,
2254,
5034,
14601,
2686,
273,
14601,
18,
2469,
342,
3847,
31,
203,
3639,
2583,
12,
1615,
411,
576,
636,
24207,
2686,
16,
315,
9858,
770,
353,
4885,
5446,
8863,
203,
203,
3639,
1731,
1578,
14601,
1046,
31,
203,
3639,
1731,
1578,
8470,
2310,
273,
7839,
31,
203,
3639,
364,
261,
11890,
5034,
277,
273,
3847,
31,
277,
1648,
14601,
18,
2469,
31,
277,
1011,
3847,
13,
288,
203,
5411,
19931,
288,
203,
7734,
14601,
1046,
519,
312,
945,
12,
1289,
12,
24207,
16,
277,
3719,
203,
5411,
289,
203,
203,
5411,
309,
261,
1615,
738,
576,
422,
374,
13,
288,
203,
7734,
8470,
2310,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
20307,
2310,
16,
14601,
1046,
10019,
203,
7734,
8470,
2310,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
24207,
1046,
16,
8470,
2310,
10019,
203,
5411,
289,
203,
203,
5411,
770,
273,
770,
342,
576,
31,
203,
3639,
289,
203,
3639,
327,
8470,
2310,
422,
1365,
2310,
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
] |
./full_match/1/0x2b4fA931ADc5D6b58674230208787A3dF0bD2121/sources/contracts/v1/ERC721.sol | * @dev See {IERC721-transferFrom}./solhint-disable-next-line max-line-length | function transferFrom(address from, address to, uint256 tokenId) public virtual override {
require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not steward.");
_transfer(from, to, tokenId);
}
| 3,096,281 | [
1,
9704,
288,
45,
654,
39,
27,
5340,
17,
13866,
1265,
5496,
19,
18281,
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,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7412,
1265,
12,
2867,
628,
16,
1758,
358,
16,
2254,
5034,
1147,
548,
13,
1071,
5024,
3849,
288,
203,
3639,
2583,
24899,
291,
31639,
1162,
5541,
12,
3576,
18,
15330,
16,
1147,
548,
3631,
315,
654,
39,
27,
5340,
30,
7412,
4894,
353,
486,
384,
359,
1060,
1199,
1769,
203,
3639,
389,
13866,
12,
2080,
16,
358,
16,
1147,
548,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/42/0xb39E3f484952bA3179ca64e43C851928f88297fe/sources/Controller.sol | * @notice Return the address of the Artem token @return The address of Artem/ | function getArtemAddress() public view returns (address) {
return 0x4Fda31D257bda1759FEfA7c7bEE10513C4570d47;
}
| 8,956,590 | [
1,
990,
326,
1758,
434,
326,
1201,
874,
1147,
327,
1021,
1758,
434,
1201,
874,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
336,
686,
874,
1887,
1435,
1071,
1476,
1135,
261,
2867,
13,
288,
203,
203,
3639,
327,
374,
92,
24,
42,
2414,
6938,
40,
2947,
27,
70,
2414,
4033,
6162,
8090,
29534,
27,
71,
27,
70,
9383,
21661,
3437,
39,
7950,
7301,
72,
9462,
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
] |
// Сочетаемость глаголов (и отглагольных частей речи) с предложным
// паттерном.
// LC->07.08.2018
facts гл_предл language=Russian
{
arity=3
//violation_score=-5
generic
return=boolean
}
#define ГЛ_ИНФ(v) инфинитив:v{}, глагол:v{}
#region Предлог_В
// ------------------- С ПРЕДЛОГОМ 'В' ---------------------------
#region Предложный
// Глаголы и отглагольные части речи, присоединяющие
// предложное дополнение с предлогом В и сущ. в предложном падеже.
wordentry_set Гл_В_Предл =
{
rus_verbs:взорваться{}, // В Дагестане взорвался автомобиль
// вернуть после перекомпиляции rus_verbs:подорожать{}, // В Дагестане подорожал хлеб
rus_verbs:воевать{}, // Воевал во Франции.
rus_verbs:устать{}, // Устали в дороге?
rus_verbs:изнывать{}, // В Лондоне Черчилль изнывал от нетерпения.
rus_verbs:решить{}, // Что решат в правительстве?
rus_verbs:выскакивать{}, // Один из бойцов на улицу выскакивает.
rus_verbs:обстоять{}, // В действительности же дело обстояло не так.
rus_verbs:подыматься{},
rus_verbs:поехать{}, // поедем в такси!
rus_verbs:уехать{}, // он уехал в такси
rus_verbs:прибыть{}, // они прибыли в качестве независимых наблюдателей
rus_verbs:ОБЛАЧИТЬ{},
rus_verbs:ОБЛАЧАТЬ{},
rus_verbs:ОБЛАЧИТЬСЯ{},
rus_verbs:ОБЛАЧАТЬСЯ{},
rus_verbs:НАРЯДИТЬСЯ{},
rus_verbs:НАРЯЖАТЬСЯ{},
rus_verbs:ПОВАЛЯТЬСЯ{}, // повалявшись в снегу, бежать обратно в тепло.
rus_verbs:ПОКРЫВАТЬ{}, // Во многих местах ее покрывали трещины, наросты и довольно плоские выступы. (ПОКРЫВАТЬ)
rus_verbs:ПРОЖИГАТЬ{}, // Синий луч искрился белыми пятнами и прожигал в земле дымящуюся борозду. (ПРОЖИГАТЬ)
rus_verbs:МЫЧАТЬ{}, // В огромной куче тел жалобно мычали задавленные трупами и раненые бизоны. (МЫЧАТЬ)
rus_verbs:РАЗБОЙНИЧАТЬ{}, // Эти существа обычно разбойничали в трехстах милях отсюда (РАЗБОЙНИЧАТЬ)
rus_verbs:МАЯЧИТЬ{}, // В отдалении маячили огромные серые туши мастодонтов и мамонтов с изогнутыми бивнями. (МАЯЧИТЬ/ЗАМАЯЧИТЬ)
rus_verbs:ЗАМАЯЧИТЬ{},
rus_verbs:НЕСТИСЬ{}, // Кони неслись вперед в свободном и легком галопе (НЕСТИСЬ)
rus_verbs:ДОБЫТЬ{}, // Они надеялись застать "медвежий народ" врасплох и добыть в бою голову величайшего из воинов. (ДОБЫТЬ)
rus_verbs:СПУСТИТЬ{}, // Время от времени грохот или вопль объявляли о спущенной где-то во дворце ловушке. (СПУСТИТЬ)
rus_verbs:ОБРАЗОВЫВАТЬСЯ{}, // Она сузила глаза, на лице ее стала образовываться маска безумия. (ОБРАЗОВЫВАТЬСЯ)
rus_verbs:КИШЕТЬ{}, // в этом районе кишмя кишели разбойники и драконы. (КИШЕТЬ)
rus_verbs:ДЫШАТЬ{}, // Она тяжело дышала в тисках гнева (ДЫШАТЬ)
rus_verbs:ЗАДЕВАТЬ{}, // тот задевал в нем какую-то струну (ЗАДЕВАТЬ)
rus_verbs:УСТУПИТЬ{}, // Так что теперь уступи мне в этом. (УСТУПИТЬ)
rus_verbs:ТЕРЯТЬ{}, // Хотя он хорошо питался, он терял в весе (ТЕРЯТЬ/ПОТЕРЯТЬ)
rus_verbs:ПоТЕРЯТЬ{},
rus_verbs:УТЕРЯТЬ{},
rus_verbs:РАСТЕРЯТЬ{},
rus_verbs:СМЫКАТЬСЯ{}, // Словно медленно смыкающийся во сне глаз, отверстие медленно закрывалось. (СМЫКАТЬСЯ/СОМКНУТЬСЯ, + оборот с СЛОВНО/БУДТО + вин.п.)
rus_verbs:СОМКНУТЬСЯ{},
rus_verbs:РАЗВОРОШИТЬ{}, // Вольф не узнал никаких отдельных слов, но звуки и взаимодействующая высота тонов разворошили что-то в его памяти. (РАЗВОРОШИТЬ)
rus_verbs:ПРОСТОЯТЬ{}, // Он поднялся и некоторое время простоял в задумчивости. (ПРОСТОЯТЬ,ВЫСТОЯТЬ,ПОСТОЯТЬ)
rus_verbs:ВЫСТОЯТЬ{},
rus_verbs:ПОСТОЯТЬ{},
rus_verbs:ВЗВЕСИТЬ{}, // Он поднял и взвесил в руке один из рогов изобилия. (ВЗВЕСИТЬ/ВЗВЕШИВАТЬ)
rus_verbs:ВЗВЕШИВАТЬ{},
rus_verbs:ДРЕЙФОВАТЬ{}, // Он и тогда не упадет, а будет дрейфовать в отбрасываемой диском тени. (ДРЕЙФОВАТЬ)
прилагательное:быстрый{}, // Кисель быстр в приготовлении
rus_verbs:призвать{}, // В День Воли белорусов призвали побороть страх и лень
rus_verbs:призывать{},
rus_verbs:ВОСПОЛЬЗОВАТЬСЯ{}, // этими деньгами смогу воспользоваться в отпуске (ВОСПОЛЬЗОВАТЬСЯ)
rus_verbs:КОНКУРИРОВАТЬ{}, // Наши клубы могли бы в Англии конкурировать с лидерами (КОНКУРИРОВАТЬ)
rus_verbs:ПОЗВАТЬ{}, // Американскую телеведущую позвали замуж в прямом эфире (ПОЗВАТЬ)
rus_verbs:ВЫХОДИТЬ{}, // Районные газеты Вологодчины будут выходить в цвете и новом формате (ВЫХОДИТЬ)
rus_verbs:РАЗВОРАЧИВАТЬСЯ{}, // Сюжет фэнтези разворачивается в двух мирах (РАЗВОРАЧИВАТЬСЯ)
rus_verbs:ОБСУДИТЬ{}, // В Самаре обсудили перспективы информатизации ветеринарии (ОБСУДИТЬ)
rus_verbs:ВЗДРОГНУТЬ{}, // она сильно вздрогнула во сне (ВЗДРОГНУТЬ)
rus_verbs:ПРЕДСТАВЛЯТЬ{}, // Сенаторы, представляющие в Комитете по разведке обе партии, поддержали эту просьбу (ПРЕДСТАВЛЯТЬ)
rus_verbs:ДОМИНИРОВАТЬ{}, // в химическом составе одной из планет доминирует метан (ДОМИНИРОВАТЬ)
rus_verbs:ОТКРЫТЬ{}, // Крым открыл в Москве собственный туристический офис (ОТКРЫТЬ)
rus_verbs:ПОКАЗАТЬ{}, // В Пушкинском музее показали золото инков (ПОКАЗАТЬ)
rus_verbs:наблюдать{}, // Наблюдаемый в отражении цвет излучения
rus_verbs:ПРОЛЕТЕТЬ{}, // Крупный астероид пролетел в непосредственной близости от Земли (ПРОЛЕТЕТЬ)
rus_verbs:РАССЛЕДОВАТЬ{}, // В Дагестане расследуют убийство федерального судьи (РАССЛЕДОВАТЬ)
rus_verbs:ВОЗОБНОВИТЬСЯ{}, // В Кемеровской области возобновилось движение по трассам международного значения (ВОЗОБНОВИТЬСЯ)
rus_verbs:ИЗМЕНИТЬСЯ{}, // изменилась она во всем (ИЗМЕНИТЬСЯ)
rus_verbs:СВЕРКАТЬ{}, // за широким окном комнаты город сверкал во тьме разноцветными огнями (СВЕРКАТЬ)
rus_verbs:СКОНЧАТЬСЯ{}, // В Риме скончался режиссёр знаменитого сериала «Спрут» (СКОНЧАТЬСЯ)
rus_verbs:ПРЯТАТЬСЯ{}, // Cкрытые спутники прячутся в кольцах Сатурна (ПРЯТАТЬСЯ)
rus_verbs:ВЫЗЫВАТЬ{}, // этот человек всегда вызывал во мне восхищение (ВЫЗЫВАТЬ)
rus_verbs:ВЫПУСТИТЬ{}, // Избирательные бюллетени могут выпустить в форме брошюры (ВЫПУСТИТЬ)
rus_verbs:НАЧИНАТЬСЯ{}, // В Москве начинается «марш в защиту детей» (НАЧИНАТЬСЯ)
rus_verbs:ЗАСТРЕЛИТЬ{}, // В Дагестане застрелили преподавателя медресе (ЗАСТРЕЛИТЬ)
rus_verbs:УРАВНЯТЬ{}, // Госзаказчиков уравняют в правах с поставщиками (УРАВНЯТЬ)
rus_verbs:промахнуться{}, // в первой половине невероятным образом промахнулся экс-форвард московского ЦСКА
rus_verbs:ОБЫГРАТЬ{}, // "Рубин" сенсационно обыграл в Мадриде вторую команду Испании (ОБЫГРАТЬ)
rus_verbs:ВКЛЮЧИТЬ{}, // В Челябинской области включен аварийный роуминг (ВКЛЮЧИТЬ)
rus_verbs:УЧАСТИТЬСЯ{}, // В селах Балаковского района участились случаи поджогов стогов сена (УЧАСТИТЬСЯ)
rus_verbs:СПАСТИ{}, // В Австралии спасли повисшего на проводе коршуна (СПАСТИ)
rus_verbs:ВЫПАСТЬ{}, // Отдельные фрагменты достигли земли, выпав в виде метеоритного дождя (ВЫПАСТЬ)
rus_verbs:НАГРАДИТЬ{}, // В Лондоне наградили лауреатов премии Brit Awards (НАГРАДИТЬ)
rus_verbs:ОТКРЫТЬСЯ{}, // в Москве открылся первый международный кинофестиваль
rus_verbs:ПОДНИМАТЬСЯ{}, // во мне поднималось раздражение
rus_verbs:ЗАВЕРШИТЬСЯ{}, // В Италии завершился традиционный Венецианский карнавал (ЗАВЕРШИТЬСЯ)
инфинитив:проводить{ вид:несоверш }, // Кузбасские депутаты проводят в Кемерове прием граждан
глагол:проводить{ вид:несоверш },
деепричастие:проводя{},
rus_verbs:отсутствовать{}, // Хозяйка квартиры в этот момент отсутствовала
rus_verbs:доложить{}, // об итогах своего визита он намерен доложить в американском сенате и Белом доме (ДОЛОЖИТЬ ОБ, В предл)
rus_verbs:ИЗДЕВАТЬСЯ{}, // В Эйлате издеваются над туристами (ИЗДЕВАТЬСЯ В предл)
rus_verbs:НАРУШИТЬ{}, // В нескольких регионах нарушено наземное транспортное сообщение (НАРУШИТЬ В предл)
rus_verbs:БЕЖАТЬ{}, // далеко внизу во тьме бежала невидимая река (БЕЖАТЬ В предл)
rus_verbs:СОБРАТЬСЯ{}, // Дмитрий оглядел собравшихся во дворе мальчишек (СОБРАТЬСЯ В предл)
rus_verbs:ПОСЛЫШАТЬСЯ{}, // далеко вверху во тьме послышался ответ (ПОСЛЫШАТЬСЯ В предл)
rus_verbs:ПОКАЗАТЬСЯ{}, // во дворе показалась высокая фигура (ПОКАЗАТЬСЯ В предл)
rus_verbs:УЛЫБНУТЬСЯ{}, // Дмитрий горько улыбнулся во тьме (УЛЫБНУТЬСЯ В предл)
rus_verbs:ТЯНУТЬСЯ{}, // убежища тянулись во всех направлениях (ТЯНУТЬСЯ В предл)
rus_verbs:РАНИТЬ{}, // В американском университете ранили человека (РАНИТЬ В предл)
rus_verbs:ЗАХВАТИТЬ{}, // Пираты освободили корабль, захваченный в Гвинейском заливе (ЗАХВАТИТЬ В предл)
rus_verbs:РАЗБЕГАТЬСЯ{}, // люди разбегались во всех направлениях (РАЗБЕГАТЬСЯ В предл)
rus_verbs:ПОГАСНУТЬ{}, // во всем доме погас свет (ПОГАСНУТЬ В предл)
rus_verbs:ПОШЕВЕЛИТЬСЯ{}, // Дмитрий пошевелился во сне (ПОШЕВЕЛИТЬСЯ В предл)
rus_verbs:ЗАСТОНАТЬ{}, // раненый застонал во сне (ЗАСТОНАТЬ В предл)
прилагательное:ВИНОВАТЫЙ{}, // во всем виновато вино (ВИНОВАТЫЙ В)
rus_verbs:ОСТАВЛЯТЬ{}, // США оставляют в районе Персидского залива только один авианосец (ОСТАВЛЯТЬ В предл)
rus_verbs:ОТКАЗЫВАТЬСЯ{}, // В России отказываются от планов авиагруппы в Арктике (ОТКАЗЫВАТЬСЯ В предл)
rus_verbs:ЛИКВИДИРОВАТЬ{}, // В Кабардино-Балкарии ликвидирован подпольный завод по переработке нефти (ЛИКВИДИРОВАТЬ В предл)
rus_verbs:РАЗОБЛАЧИТЬ{}, // В США разоблачили крупнейшую махинацию с кредитками (РАЗОБЛАЧИТЬ В предл)
rus_verbs:СХВАТИТЬ{}, // их схватили во сне (СХВАТИТЬ В предл)
rus_verbs:НАЧАТЬ{}, // В Белгороде начали сбор подписей за отставку мэра (НАЧАТЬ В предл)
rus_verbs:РАСТИ{}, // Cамая маленькая муха растёт в голове муравья (РАСТИ В предл)
rus_verbs:похитить{}, // Двое россиян, похищенных террористами в Сирии, освобождены (похитить в предл)
rus_verbs:УЧАСТВОВАТЬ{}, // были застрелены два испанских гражданских гвардейца , участвовавших в слежке (УЧАСТВОВАТЬ В)
rus_verbs:УСЫНОВИТЬ{}, // Американцы забирают усыновленных в России детей (УСЫНОВИТЬ В)
rus_verbs:ПРОИЗВЕСТИ{}, // вы не увидите мясо или молоко , произведенное в районе (ПРОИЗВЕСТИ В предл)
rus_verbs:ОРИЕНТИРОВАТЬСЯ{}, // призван помочь госслужащему правильно ориентироваться в сложных нравственных коллизиях (ОРИЕНТИРОВАТЬСЯ В)
rus_verbs:ПОВРЕДИТЬ{}, // В зале игровых автоматов повреждены стены и потолок (ПОВРЕДИТЬ В предл)
rus_verbs:ИЗЪЯТЬ{}, // В настоящее время в детском учреждении изъяты суточные пробы пищи (ИЗЪЯТЬ В предл)
rus_verbs:СОДЕРЖАТЬСЯ{}, // осужденных , содержащихся в помещениях штрафного изолятора (СОДЕРЖАТЬСЯ В)
rus_verbs:ОТЧИСЛИТЬ{}, // был отчислен за неуспеваемость в 2007 году (ОТЧИСЛИТЬ В предл)
rus_verbs:проходить{}, // находился на санкционированном митинге , проходившем в рамках празднования Дня народного единства (проходить в предл)
rus_verbs:ПОДУМЫВАТЬ{}, // сейчас в правительстве Приамурья подумывают о создании специального пункта помощи туристам (ПОДУМЫВАТЬ В)
rus_verbs:ОТРАПОРТОВЫВАТЬ{}, // главы субъектов не просто отрапортовывали в Москве (ОТРАПОРТОВЫВАТЬ В предл)
rus_verbs:ВЕСТИСЬ{}, // в городе ведутся работы по установке праздничной иллюминации (ВЕСТИСЬ В)
rus_verbs:ОДОБРИТЬ{}, // Одобренным в первом чтении законопроектом (ОДОБРИТЬ В)
rus_verbs:ЗАМЫЛИТЬСЯ{}, // ему легче исправлять , то , что замылилось в глазах предыдущего руководства (ЗАМЫЛИТЬСЯ В)
rus_verbs:АВТОРИЗОВАТЬСЯ{}, // потом имеют право авторизоваться в системе Международного бакалавриата (АВТОРИЗОВАТЬСЯ В)
rus_verbs:ОПУСТИТЬСЯ{}, // Россия опустилась в списке на шесть позиций (ОПУСТИТЬСЯ В предл)
rus_verbs:СГОРЕТЬ{}, // Совладелец сгоревшего в Бразилии ночного клуба сдался полиции (СГОРЕТЬ В)
частица:нет{}, // В этом нет сомнения.
частица:нету{}, // В этом нету сомнения.
rus_verbs:поджечь{}, // Поджегший себя в Москве мужчина оказался ветераном-афганцем
rus_verbs:ввести{}, // В Молдавии введен запрет на амнистию или помилование педофилов.
прилагательное:ДОСТУПНЫЙ{}, // Наиболее интересные таблички доступны в основной экспозиции музея (ДОСТУПНЫЙ В)
rus_verbs:ПОВИСНУТЬ{}, // вопрос повис в мглистом демократическом воздухе (ПОВИСНУТЬ В)
rus_verbs:ВЗОРВАТЬ{}, // В Ираке смертник взорвал в мечети группу туркменов (ВЗОРВАТЬ В)
rus_verbs:ОТНЯТЬ{}, // В Финляндии у россиянки, прибывшей по туристической визе, отняли детей (ОТНЯТЬ В)
rus_verbs:НАЙТИ{}, // Я недавно посетил врача и у меня в глазах нашли какую-то фигню (НАЙТИ В предл)
rus_verbs:ЗАСТРЕЛИТЬСЯ{}, // Девушка, застрелившаяся в центре Киева, была замешана в скандале с влиятельными людьми (ЗАСТРЕЛИТЬСЯ В)
rus_verbs:стартовать{}, // В Страсбурге сегодня стартует зимняя сессия Парламентской ассамблеи Совета Европы (стартовать в)
rus_verbs:ЗАКЛАДЫВАТЬСЯ{}, // Отношение к деньгам закладывается в детстве (ЗАКЛАДЫВАТЬСЯ В)
rus_verbs:НАПИВАТЬСЯ{}, // Депутатам помешают напиваться в здании Госдумы (НАПИВАТЬСЯ В)
rus_verbs:ВЫПРАВИТЬСЯ{}, // Прежде всего было заявлено, что мировая экономика каким-то образом сама выправится в процессе бизнес-цикла (ВЫПРАВИТЬСЯ В)
rus_verbs:ЯВЛЯТЬСЯ{}, // она являлась ко мне во всех моих снах (ЯВЛЯТЬСЯ В)
rus_verbs:СТАЖИРОВАТЬСЯ{}, // сейчас я стажируюсь в одной компании (СТАЖИРОВАТЬСЯ В)
rus_verbs:ОБСТРЕЛЯТЬ{}, // Уроженцы Чечни, обстрелявшие полицейских в центре Москвы, арестованы (ОБСТРЕЛЯТЬ В)
rus_verbs:РАСПРОСТРАНИТЬ{}, // Воски — распространённые в растительном и животном мире сложные эфиры высших жирных кислот и высших высокомолекулярных спиртов (РАСПРОСТРАНИТЬ В)
rus_verbs:ПРИВЕСТИ{}, // Сравнительная фугасность некоторых взрывчатых веществ приведена в следующей таблице (ПРИВЕСТИ В)
rus_verbs:ЗАПОДОЗРИТЬ{}, // Чиновников Минкультуры заподозрили в афере с заповедными землями (ЗАПОДОЗРИТЬ В)
rus_verbs:НАСТУПАТЬ{}, // В Гренландии стали наступать ледники (НАСТУПАТЬ В)
rus_verbs:ВЫДЕЛЯТЬСЯ{}, // В истории Земли выделяются следующие ледниковые эры (ВЫДЕЛЯТЬСЯ В)
rus_verbs:ПРЕДСТАВИТЬ{}, // Данные представлены в хронологическом порядке (ПРЕДСТАВИТЬ В)
rus_verbs:ОБРУШИТЬСЯ{}, // В Северной Осетии на воинскую часть обрушилась снежная лавина (ОБРУШИТЬСЯ В, НА)
rus_verbs:ПОДАВАТЬ{}, // Готовые компоты подают в столовых и кафе (ПОДАВАТЬ В)
rus_verbs:ГОТОВИТЬ{}, // Сегодня компот готовят в домашних условиях из сухофруктов или замороженных фруктов и ягод (ГОТОВИТЬ В)
rus_verbs:ВОЗДЕЛЫВАТЬСЯ{}, // в настоящее время он повсеместно возделывается в огородах (ВОЗДЕЛЫВАТЬСЯ В)
rus_verbs:РАСКЛАДЫВАТЬ{}, // Созревшие семенные экземпляры раскладывают на солнце или в теплом месте, где они делаются мягкими (РАСКЛАДЫВАТЬСЯ В, НА)
rus_verbs:РАСКЛАДЫВАТЬСЯ{},
rus_verbs:СОБИРАТЬСЯ{}, // Обыкновенно огурцы собираются в полуспелом состоянии (СОБИРАТЬСЯ В)
rus_verbs:ПРОГРЕМЕТЬ{}, // В торговом центре Ижевска прогремел взрыв (ПРОГРЕМЕТЬ В)
rus_verbs:СНЯТЬ{}, // чтобы снять их во всей красоте. (СНЯТЬ В)
rus_verbs:ЯВИТЬСЯ{}, // она явилась к нему во сне. (ЯВИТЬСЯ В)
rus_verbs:ВЕРИТЬ{}, // мы же во всем верили капитану. (ВЕРИТЬ В предл)
rus_verbs:выдержать{}, // Игра выдержана в научно-фантастическом стиле. (ВЫДЕРЖАННЫЙ В)
rus_verbs:ПРЕОДОЛЕТЬ{}, // мы пытались преодолеть ее во многих местах. (ПРЕОДОЛЕТЬ В)
инфинитив:НАПИСАТЬ{ aux stress="напис^ать" }, // Программа, написанная в спешке, выполнила недопустимую операцию. (НАПИСАТЬ В)
глагол:НАПИСАТЬ{ aux stress="напис^ать" },
прилагательное:НАПИСАННЫЙ{},
rus_verbs:ЕСТЬ{}, // ты даже во сне ел. (ЕСТЬ/кушать В)
rus_verbs:УСЕСТЬСЯ{}, // Он удобно уселся в кресле. (УСЕСТЬСЯ В)
rus_verbs:ТОРГОВАТЬ{}, // Он торгует в палатке. (ТОРГОВАТЬ В)
rus_verbs:СОВМЕСТИТЬ{}, // Он совместил в себе писателя и художника. (СОВМЕСТИТЬ В)
rus_verbs:ЗАБЫВАТЬ{}, // об этом нельзя забывать даже во сне. (ЗАБЫВАТЬ В)
rus_verbs:поговорить{}, // Давайте поговорим об этом в присутствии адвоката
rus_verbs:убрать{}, // В вагонах метро для комфорта пассажиров уберут сиденья (УБРАТЬ В, ДЛЯ)
rus_verbs:упасть{}, // В Таиланде на автобус с российскими туристами упал башенный кран (УПАСТЬ В, НА)
rus_verbs:раскрыть{}, // В России раскрыли крупнейшую в стране сеть фальшивомонетчиков (РАСКРЫТЬ В)
rus_verbs:соединить{}, // соединить в себе (СОЕДИНИТЬ В предл)
rus_verbs:избрать{}, // В Южной Корее избран новый президент (ИЗБРАТЬ В предл)
rus_verbs:проводиться{}, // Обыски проводятся в воронежском Доме прав человека (ПРОВОДИТЬСЯ В)
безлич_глагол:хватает{}, // В этой статье не хватает ссылок на источники информации. (БЕЗЛИЧ хватать в)
rus_verbs:наносить{}, // В ближнем бою наносит мощные удары своим костлявым кулаком. (НАНОСИТЬ В + предл.)
rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА)
прилагательное:известный{}, // В Европе сахар был известен ещё римлянам. (ИЗВЕСТНЫЙ В)
rus_verbs:выработать{}, // Способы, выработанные во Франции, перешли затем в Германию и другие страны Европы. (ВЫРАБОТАТЬ В)
rus_verbs:КУЛЬТИВИРОВАТЬСЯ{}, // Культивируется в регионах с умеренным климатом с умеренным количеством осадков и требует плодородной почвы. (КУЛЬТИВИРОВАТЬСЯ В)
rus_verbs:чаять{}, // мама души не чаяла в своих детях (ЧАЯТЬ В)
rus_verbs:улыбаться{}, // Вадим улыбался во сне. (УЛЫБАТЬСЯ В)
rus_verbs:растеряться{}, // Приезжие растерялись в бетонном лабиринте улиц (РАСТЕРЯТЬСЯ В)
rus_verbs:выть{}, // выли волки где-то в лесу (ВЫТЬ В)
rus_verbs:ЗАВЕРИТЬ{}, // выступавший заверил нас в намерении выполнить обещание (ЗАВЕРИТЬ В)
rus_verbs:ИСЧЕЗНУТЬ{}, // звери исчезли во мраке. (ИСЧЕЗНУТЬ В)
rus_verbs:ВСТАТЬ{}, // встать во главе человечества. (ВСТАТЬ В)
rus_verbs:УПОТРЕБЛЯТЬ{}, // В Тибете употребляют кирпичный зелёный чай. (УПОТРЕБЛЯТЬ В)
rus_verbs:ПОДАВАТЬСЯ{}, // Напиток охлаждается и подаётся в холодном виде. (ПОДАВАТЬСЯ В)
rus_verbs:ИСПОЛЬЗОВАТЬСЯ{}, // в игре используются текстуры большего разрешения (ИСПОЛЬЗОВАТЬСЯ В)
rus_verbs:объявить{}, // В газете объявили о конкурсе.
rus_verbs:ВСПЫХНУТЬ{}, // во мне вспыхнул гнев. (ВСПЫХНУТЬ В)
rus_verbs:КРЫТЬСЯ{}, // В его словах кроется угроза. (КРЫТЬСЯ В)
rus_verbs:подняться{}, // В классе вдруг поднялся шум. (подняться в)
rus_verbs:наступить{}, // В классе наступила полная тишина. (наступить в)
rus_verbs:кипеть{}, // В нём кипит злоба. (кипеть в)
rus_verbs:соединиться{}, // В нём соединились храбрость и великодушие. (соединиться в)
инфинитив:ПАРИТЬ{ aux stress="пар^ить"}, // Высоко в небе парит орёл, плавно описывая круги. (ПАРИТЬ В)
глагол:ПАРИТЬ{ aux stress="пар^ить"},
деепричастие:паря{ aux stress="пар^я" },
прилагательное:ПАРЯЩИЙ{},
прилагательное:ПАРИВШИЙ{},
rus_verbs:СИЯТЬ{}, // Главы собора сияли в лучах солнца. (СИЯТЬ В)
rus_verbs:РАСПОЛОЖИТЬ{}, // Гостиница расположена глубоко в горах. (РАСПОЛОЖИТЬ В)
rus_verbs:развиваться{}, // Действие в комедии развивается в двух планах. (развиваться в)
rus_verbs:ПОСАДИТЬ{}, // Дети посадили у нас во дворе цветы. (ПОСАДИТЬ В)
rus_verbs:ИСКОРЕНЯТЬ{}, // Дурные привычки следует искоренять в самом начале. (ИСКОРЕНЯТЬ В)
rus_verbs:ВОССТАНОВИТЬ{}, // Его восстановили в правах. (ВОССТАНОВИТЬ В)
rus_verbs:ПОЛАГАТЬСЯ{}, // мы полагаемся на него в этих вопросах (ПОЛАГАТЬСЯ В)
rus_verbs:УМИРАТЬ{}, // они умирали во сне. (УМИРАТЬ В)
rus_verbs:ПРИБАВИТЬ{}, // Она сильно прибавила в весе. (ПРИБАВИТЬ В)
rus_verbs:посмотреть{}, // Посмотрите в списке. (посмотреть в)
rus_verbs:производиться{}, // Выдача новых паспортов будет производиться в следующем порядке (производиться в)
rus_verbs:принять{}, // Документ принят в следующей редакции (принять в)
rus_verbs:сверкнуть{}, // меч его сверкнул во тьме. (сверкнуть в)
rus_verbs:ВЫРАБАТЫВАТЬ{}, // ты должен вырабатывать в себе силу воли (ВЫРАБАТЫВАТЬ В)
rus_verbs:достать{}, // Эти сведения мы достали в Волгограде. (достать в)
rus_verbs:звучать{}, // в доме звучала музыка (звучать в)
rus_verbs:колебаться{}, // колеблется в выборе (колебаться в)
rus_verbs:мешать{}, // мешать в кастрюле суп (мешать в)
rus_verbs:нарастать{}, // во мне нарастал гнев (нарастать в)
rus_verbs:отбыть{}, // Вадим отбыл в неизвестном направлении (отбыть в)
rus_verbs:светиться{}, // во всем доме светилось только окно ее спальни. (светиться в)
rus_verbs:вычитывать{}, // вычитывать в книге
rus_verbs:гудеть{}, // У него в ушах гудит.
rus_verbs:давать{}, // В этой лавке дают в долг?
rus_verbs:поблескивать{}, // Красивое стеклышко поблескивало в пыльной траве у дорожки.
rus_verbs:разойтись{}, // Они разошлись в темноте.
rus_verbs:прибежать{}, // Мальчик прибежал в слезах.
rus_verbs:биться{}, // Она билась в истерике.
rus_verbs:регистрироваться{}, // регистрироваться в системе
rus_verbs:считать{}, // я буду считать в уме
rus_verbs:трахаться{}, // трахаться в гамаке
rus_verbs:сконцентрироваться{}, // сконцентрироваться в одной точке
rus_verbs:разрушать{}, // разрушать в дробилке
rus_verbs:засидеться{}, // засидеться в гостях
rus_verbs:засиживаться{}, // засиживаться в гостях
rus_verbs:утопить{}, // утопить лодку в реке (утопить в реке)
rus_verbs:навестить{}, // навестить в доме престарелых
rus_verbs:запомнить{}, // запомнить в кэше
rus_verbs:убивать{}, // убивать в помещении полиции (-score убивать неодуш. дом.)
rus_verbs:базироваться{}, // установка базируется в черте города (ngram черта города - проверить что есть проверка)
rus_verbs:покупать{}, // Чаще всего россияне покупают в интернете бытовую технику.
rus_verbs:ходить{}, // ходить в пальто (сделать ХОДИТЬ + в + ОДЕЖДА предл.п.)
rus_verbs:заложить{}, // диверсанты заложили в помещении бомбу
rus_verbs:оглядываться{}, // оглядываться в зеркале
rus_verbs:нарисовать{}, // нарисовать в тетрадке
rus_verbs:пробить{}, // пробить отверствие в стене
rus_verbs:повертеть{}, // повертеть в руке
rus_verbs:вертеть{}, // Я вертел в руках
rus_verbs:рваться{}, // Веревка рвется в месте надреза
rus_verbs:распространяться{}, // распространяться в среде наркоманов
rus_verbs:попрощаться{}, // попрощаться в здании морга
rus_verbs:соображать{}, // соображать в уме
инфинитив:просыпаться{ вид:несоверш }, глагол:просыпаться{ вид:несоверш }, // просыпаться в чужой кровати
rus_verbs:заехать{}, // Коля заехал в гости (в гости - устойчивый наречный оборот)
rus_verbs:разобрать{}, // разобрать в гараже
rus_verbs:помереть{}, // помереть в пути
rus_verbs:различить{}, // различить в темноте
rus_verbs:рисовать{}, // рисовать в графическом редакторе
rus_verbs:проследить{}, // проследить в записях камер слежения
rus_verbs:совершаться{}, // Правосудие совершается в суде
rus_verbs:задремать{}, // задремать в кровати
rus_verbs:ругаться{}, // ругаться в комнате
rus_verbs:зазвучать{}, // зазвучать в радиоприемниках
rus_verbs:задохнуться{}, // задохнуться в воде
rus_verbs:порождать{}, // порождать в неокрепших умах
rus_verbs:отдыхать{}, // отдыхать в санатории
rus_verbs:упоминаться{}, // упоминаться в предыдущем сообщении
rus_verbs:образовать{}, // образовать в пробирке темную взвесь
rus_verbs:отмечать{}, // отмечать в списке
rus_verbs:подчеркнуть{}, // подчеркнуть в блокноте
rus_verbs:плясать{}, // плясать в откружении незнакомых людей
rus_verbs:повысить{}, // повысить в звании
rus_verbs:поджидать{}, // поджидать в подъезде
rus_verbs:отказать{}, // отказать в пересмотре дела
rus_verbs:раствориться{}, // раствориться в бензине
rus_verbs:отражать{}, // отражать в стихах
rus_verbs:дремать{}, // дремать в гамаке
rus_verbs:применяться{}, // применяться в домашних условиях
rus_verbs:присниться{}, // присниться во сне
rus_verbs:трястись{}, // трястись в драндулете
rus_verbs:сохранять{}, // сохранять в неприкосновенности
rus_verbs:расстрелять{}, // расстрелять в ложбине
rus_verbs:рассчитать{}, // рассчитать в программе
rus_verbs:перебирать{}, // перебирать в руке
rus_verbs:разбиться{}, // разбиться в аварии
rus_verbs:поискать{}, // поискать в углу
rus_verbs:мучиться{}, // мучиться в тесной клетке
rus_verbs:замелькать{}, // замелькать в телевизоре
rus_verbs:грустить{}, // грустить в одиночестве
rus_verbs:крутить{}, // крутить в банке
rus_verbs:объявиться{}, // объявиться в городе
rus_verbs:подготовить{}, // подготовить в тайне
rus_verbs:различать{}, // различать в смеси
rus_verbs:обнаруживать{}, // обнаруживать в крови
rus_verbs:киснуть{}, // киснуть в захолустье
rus_verbs:оборваться{}, // оборваться в начале фразы
rus_verbs:запутаться{}, // запутаться в веревках
rus_verbs:общаться{}, // общаться в интимной обстановке
rus_verbs:сочинить{}, // сочинить в ресторане
rus_verbs:изобрести{}, // изобрести в домашней лаборатории
rus_verbs:прокомментировать{}, // прокомментировать в своем блоге
rus_verbs:давить{}, // давить в зародыше
rus_verbs:повториться{}, // повториться в новом обличье
rus_verbs:отставать{}, // отставать в общем зачете
rus_verbs:разработать{}, // разработать в лаборатории
rus_verbs:качать{}, // качать в кроватке
rus_verbs:заменить{}, // заменить в двигателе
rus_verbs:задыхаться{}, // задыхаться в душной и влажной атмосфере
rus_verbs:забегать{}, // забегать в спешке
rus_verbs:наделать{}, // наделать в решении ошибок
rus_verbs:исказиться{}, // исказиться в кривом зеркале
rus_verbs:тушить{}, // тушить в помещении пожар
rus_verbs:охранять{}, // охранять в здании входы
rus_verbs:приметить{}, // приметить в кустах
rus_verbs:скрыть{}, // скрыть в складках одежды
rus_verbs:удерживать{}, // удерживать в заложниках
rus_verbs:увеличиваться{}, // увеличиваться в размере
rus_verbs:красоваться{}, // красоваться в новом платье
rus_verbs:сохраниться{}, // сохраниться в тепле
rus_verbs:лечить{}, // лечить в стационаре
rus_verbs:смешаться{}, // смешаться в баке
rus_verbs:прокатиться{}, // прокатиться в троллейбусе
rus_verbs:договариваться{}, // договариваться в закрытом кабинете
rus_verbs:опубликовать{}, // опубликовать в официальном блоге
rus_verbs:охотиться{}, // охотиться в прериях
rus_verbs:отражаться{}, // отражаться в окне
rus_verbs:понизить{}, // понизить в должности
rus_verbs:обедать{}, // обедать в ресторане
rus_verbs:посидеть{}, // посидеть в тени
rus_verbs:сообщаться{}, // сообщаться в оппозиционной газете
rus_verbs:свершиться{}, // свершиться в суде
rus_verbs:ночевать{}, // ночевать в гостинице
rus_verbs:темнеть{}, // темнеть в воде
rus_verbs:гибнуть{}, // гибнуть в застенках
rus_verbs:усиливаться{}, // усиливаться в направлении главного удара
rus_verbs:расплыться{}, // расплыться в улыбке
rus_verbs:превышать{}, // превышать в несколько раз
rus_verbs:проживать{}, // проживать в отдельной коморке
rus_verbs:голубеть{}, // голубеть в тепле
rus_verbs:исследовать{}, // исследовать в естественных условиях
rus_verbs:обитать{}, // обитать в лесу
rus_verbs:скучать{}, // скучать в одиночестве
rus_verbs:сталкиваться{}, // сталкиваться в воздухе
rus_verbs:таиться{}, // таиться в глубине
rus_verbs:спасать{}, // спасать в море
rus_verbs:заблудиться{}, // заблудиться в лесу
rus_verbs:создаться{}, // создаться в новом виде
rus_verbs:пошарить{}, // пошарить в кармане
rus_verbs:планировать{}, // планировать в программе
rus_verbs:отбить{}, // отбить в нижней части
rus_verbs:отрицать{}, // отрицать в суде свою вину
rus_verbs:основать{}, // основать в пустыне новый город
rus_verbs:двоить{}, // двоить в глазах
rus_verbs:устоять{}, // устоять в лодке
rus_verbs:унять{}, // унять в ногах дрожь
rus_verbs:отзываться{}, // отзываться в обзоре
rus_verbs:притормозить{}, // притормозить в траве
rus_verbs:читаться{}, // читаться в глазах
rus_verbs:житься{}, // житься в деревне
rus_verbs:заиграть{}, // заиграть в жилах
rus_verbs:шевелить{}, // шевелить в воде
rus_verbs:зазвенеть{}, // зазвенеть в ушах
rus_verbs:зависнуть{}, // зависнуть в библиотеке
rus_verbs:затаить{}, // затаить в душе обиду
rus_verbs:сознаться{}, // сознаться в совершении
rus_verbs:протекать{}, // протекать в легкой форме
rus_verbs:выясняться{}, // выясняться в ходе эксперимента
rus_verbs:скрестить{}, // скрестить в неволе
rus_verbs:наводить{}, // наводить в комнате порядок
rus_verbs:значиться{}, // значиться в документах
rus_verbs:заинтересовать{}, // заинтересовать в получении результатов
rus_verbs:познакомить{}, // познакомить в непринужденной обстановке
rus_verbs:рассеяться{}, // рассеяться в воздухе
rus_verbs:грохнуть{}, // грохнуть в подвале
rus_verbs:обвинять{}, // обвинять в вымогательстве
rus_verbs:столпиться{}, // столпиться в фойе
rus_verbs:порыться{}, // порыться в сумке
rus_verbs:ослабить{}, // ослабить в верхней части
rus_verbs:обнаруживаться{}, // обнаруживаться в кармане куртки
rus_verbs:спастись{}, // спастись в хижине
rus_verbs:прерваться{}, // прерваться в середине фразы
rus_verbs:применять{}, // применять в повседневной работе
rus_verbs:строиться{}, // строиться в зоне отчуждения
rus_verbs:путешествовать{}, // путешествовать в самолете
rus_verbs:побеждать{}, // побеждать в честной битве
rus_verbs:погубить{}, // погубить в себе артиста
rus_verbs:рассматриваться{}, // рассматриваться в следующей главе
rus_verbs:продаваться{}, // продаваться в специализированном магазине
rus_verbs:разместиться{}, // разместиться в аудитории
rus_verbs:повидать{}, // повидать в жизни
rus_verbs:настигнуть{}, // настигнуть в пригородах
rus_verbs:сгрудиться{}, // сгрудиться в центре загона
rus_verbs:укрыться{}, // укрыться в доме
rus_verbs:расплакаться{}, // расплакаться в суде
rus_verbs:пролежать{}, // пролежать в канаве
rus_verbs:замерзнуть{}, // замерзнуть в ледяной воде
rus_verbs:поскользнуться{}, // поскользнуться в коридоре
rus_verbs:таскать{}, // таскать в руках
rus_verbs:нападать{}, // нападать в вольере
rus_verbs:просматривать{}, // просматривать в браузере
rus_verbs:обдумать{}, // обдумать в дороге
rus_verbs:обвинить{}, // обвинить в измене
rus_verbs:останавливать{}, // останавливать в дверях
rus_verbs:теряться{}, // теряться в догадках
rus_verbs:погибать{}, // погибать в бою
rus_verbs:обозначать{}, // обозначать в списке
rus_verbs:запрещать{}, // запрещать в парке
rus_verbs:долететь{}, // долететь в вертолёте
rus_verbs:тесниться{}, // тесниться в каморке
rus_verbs:уменьшаться{}, // уменьшаться в размере
rus_verbs:издавать{}, // издавать в небольшом издательстве
rus_verbs:хоронить{}, // хоронить в море
rus_verbs:перемениться{}, // перемениться в лице
rus_verbs:установиться{}, // установиться в северных областях
rus_verbs:прикидывать{}, // прикидывать в уме
rus_verbs:затаиться{}, // затаиться в траве
rus_verbs:раздобыть{}, // раздобыть в аптеке
rus_verbs:перебросить{}, // перебросить в товарном составе
rus_verbs:погружаться{}, // погружаться в батискафе
rus_verbs:поживать{}, // поживать в одиночестве
rus_verbs:признаваться{}, // признаваться в любви
rus_verbs:захватывать{}, // захватывать в здании
rus_verbs:покачиваться{}, // покачиваться в лодке
rus_verbs:крутиться{}, // крутиться в колесе
rus_verbs:помещаться{}, // помещаться в ящике
rus_verbs:питаться{}, // питаться в столовой
rus_verbs:отдохнуть{}, // отдохнуть в пансионате
rus_verbs:кататься{}, // кататься в коляске
rus_verbs:поработать{}, // поработать в цеху
rus_verbs:подразумевать{}, // подразумевать в задании
rus_verbs:ограбить{}, // ограбить в подворотне
rus_verbs:преуспеть{}, // преуспеть в бизнесе
rus_verbs:заерзать{}, // заерзать в кресле
rus_verbs:разъяснить{}, // разъяснить в другой статье
rus_verbs:продвинуться{}, // продвинуться в изучении
rus_verbs:поколебаться{}, // поколебаться в начале
rus_verbs:засомневаться{}, // засомневаться в честности
rus_verbs:приникнуть{}, // приникнуть в уме
rus_verbs:скривить{}, // скривить в усмешке
rus_verbs:рассечь{}, // рассечь в центре опухоли
rus_verbs:перепутать{}, // перепутать в роддоме
rus_verbs:посмеяться{}, // посмеяться в перерыве
rus_verbs:отмечаться{}, // отмечаться в полицейском участке
rus_verbs:накопиться{}, // накопиться в отстойнике
rus_verbs:уносить{}, // уносить в руках
rus_verbs:навещать{}, // навещать в больнице
rus_verbs:остыть{}, // остыть в проточной воде
rus_verbs:запереться{}, // запереться в комнате
rus_verbs:обогнать{}, // обогнать в первом круге
rus_verbs:убеждаться{}, // убеждаться в неизбежности
rus_verbs:подбирать{}, // подбирать в магазине
rus_verbs:уничтожать{}, // уничтожать в полете
rus_verbs:путаться{}, // путаться в показаниях
rus_verbs:притаиться{}, // притаиться в темноте
rus_verbs:проплывать{}, // проплывать в лодке
rus_verbs:засесть{}, // засесть в окопе
rus_verbs:подцепить{}, // подцепить в баре
rus_verbs:насчитать{}, // насчитать в диктанте несколько ошибок
rus_verbs:оправдаться{}, // оправдаться в суде
rus_verbs:созреть{}, // созреть в естественных условиях
rus_verbs:раскрываться{}, // раскрываться в подходящих условиях
rus_verbs:ожидаться{}, // ожидаться в верхней части
rus_verbs:одеваться{}, // одеваться в дорогих бутиках
rus_verbs:упрекнуть{}, // упрекнуть в недостатке опыта
rus_verbs:грабить{}, // грабить в подворотне
rus_verbs:ужинать{}, // ужинать в ресторане
rus_verbs:гонять{}, // гонять в жилах
rus_verbs:уверить{}, // уверить в безопасности
rus_verbs:потеряться{}, // потеряться в лесу
rus_verbs:устанавливаться{}, // устанавливаться в комнате
rus_verbs:предоставлять{}, // предоставлять в суде
rus_verbs:протянуться{}, // протянуться в стене
rus_verbs:допрашивать{}, // допрашивать в бункере
rus_verbs:проработать{}, // проработать в кабинете
rus_verbs:сосредоточить{}, // сосредоточить в своих руках
rus_verbs:утвердить{}, // утвердить в должности
rus_verbs:сочинять{}, // сочинять в дороге
rus_verbs:померкнуть{}, // померкнуть в глазах
rus_verbs:показываться{}, // показываться в окошке
rus_verbs:похудеть{}, // похудеть в талии
rus_verbs:проделывать{}, // проделывать в стене
rus_verbs:прославиться{}, // прославиться в интернете
rus_verbs:сдохнуть{}, // сдохнуть в нищете
rus_verbs:раскинуться{}, // раскинуться в степи
rus_verbs:развить{}, // развить в себе способности
rus_verbs:уставать{}, // уставать в цеху
rus_verbs:укрепить{}, // укрепить в земле
rus_verbs:числиться{}, // числиться в списке
rus_verbs:образовывать{}, // образовывать в смеси
rus_verbs:екнуть{}, // екнуть в груди
rus_verbs:одобрять{}, // одобрять в своей речи
rus_verbs:запить{}, // запить в одиночестве
rus_verbs:забыться{}, // забыться в тяжелом сне
rus_verbs:чернеть{}, // чернеть в кислой среде
rus_verbs:размещаться{}, // размещаться в гараже
rus_verbs:соорудить{}, // соорудить в гараже
rus_verbs:развивать{}, // развивать в себе
rus_verbs:пастись{}, // пастись в пойме
rus_verbs:формироваться{}, // формироваться в верхних слоях атмосферы
rus_verbs:ослабнуть{}, // ослабнуть в сочленении
rus_verbs:таить{}, // таить в себе
инфинитив:пробегать{ вид:несоверш }, глагол:пробегать{ вид:несоверш }, // пробегать в спешке
rus_verbs:приостановиться{}, // приостановиться в конце
rus_verbs:топтаться{}, // топтаться в грязи
rus_verbs:громить{}, // громить в финале
rus_verbs:заменять{}, // заменять в основном составе
rus_verbs:подъезжать{}, // подъезжать в колясках
rus_verbs:вычислить{}, // вычислить в уме
rus_verbs:заказывать{}, // заказывать в магазине
rus_verbs:осуществить{}, // осуществить в реальных условиях
rus_verbs:обосноваться{}, // обосноваться в дупле
rus_verbs:пытать{}, // пытать в камере
rus_verbs:поменять{}, // поменять в магазине
rus_verbs:совершиться{}, // совершиться в суде
rus_verbs:пролетать{}, // пролетать в вертолете
rus_verbs:сбыться{}, // сбыться во сне
rus_verbs:разговориться{}, // разговориться в отделении
rus_verbs:преподнести{}, // преподнести в красивой упаковке
rus_verbs:напечатать{}, // напечатать в типографии
rus_verbs:прорвать{}, // прорвать в центре
rus_verbs:раскачиваться{}, // раскачиваться в кресле
rus_verbs:задерживаться{}, // задерживаться в дверях
rus_verbs:угощать{}, // угощать в кафе
rus_verbs:проступать{}, // проступать в глубине
rus_verbs:шарить{}, // шарить в математике
rus_verbs:увеличивать{}, // увеличивать в конце
rus_verbs:расцвести{}, // расцвести в оранжерее
rus_verbs:закипеть{}, // закипеть в баке
rus_verbs:подлететь{}, // подлететь в вертолете
rus_verbs:рыться{}, // рыться в куче
rus_verbs:пожить{}, // пожить в гостинице
rus_verbs:добираться{}, // добираться в попутном транспорте
rus_verbs:перекрыть{}, // перекрыть в коридоре
rus_verbs:продержаться{}, // продержаться в барокамере
rus_verbs:разыскивать{}, // разыскивать в толпе
rus_verbs:освобождать{}, // освобождать в зале суда
rus_verbs:подметить{}, // подметить в человеке
rus_verbs:передвигаться{}, // передвигаться в узкой юбке
rus_verbs:продумать{}, // продумать в уме
rus_verbs:извиваться{}, // извиваться в траве
rus_verbs:процитировать{}, // процитировать в статье
rus_verbs:прогуливаться{}, // прогуливаться в парке
rus_verbs:защемить{}, // защемить в двери
rus_verbs:увеличиться{}, // увеличиться в объеме
rus_verbs:проявиться{}, // проявиться в результатах
rus_verbs:заскользить{}, // заскользить в ботинках
rus_verbs:пересказать{}, // пересказать в своем выступлении
rus_verbs:протестовать{}, // протестовать в здании парламента
rus_verbs:указываться{}, // указываться в путеводителе
rus_verbs:копошиться{}, // копошиться в песке
rus_verbs:проигнорировать{}, // проигнорировать в своей работе
rus_verbs:купаться{}, // купаться в речке
rus_verbs:подсчитать{}, // подсчитать в уме
rus_verbs:разволноваться{}, // разволноваться в классе
rus_verbs:придумывать{}, // придумывать в своем воображении
rus_verbs:предусмотреть{}, // предусмотреть в программе
rus_verbs:завертеться{}, // завертеться в колесе
rus_verbs:зачерпнуть{}, // зачерпнуть в ручье
rus_verbs:очистить{}, // очистить в химической лаборатории
rus_verbs:прозвенеть{}, // прозвенеть в коридорах
rus_verbs:уменьшиться{}, // уменьшиться в размере
rus_verbs:колыхаться{}, // колыхаться в проточной воде
rus_verbs:ознакомиться{}, // ознакомиться в автобусе
rus_verbs:ржать{}, // ржать в аудитории
rus_verbs:раскинуть{}, // раскинуть в микрорайоне
rus_verbs:разлиться{}, // разлиться в воде
rus_verbs:сквозить{}, // сквозить в словах
rus_verbs:задушить{}, // задушить в объятиях
rus_verbs:осудить{}, // осудить в особом порядке
rus_verbs:разгромить{}, // разгромить в честном поединке
rus_verbs:подслушать{}, // подслушать в кулуарах
rus_verbs:проповедовать{}, // проповедовать в сельских районах
rus_verbs:озарить{}, // озарить во сне
rus_verbs:потирать{}, // потирать в предвкушении
rus_verbs:описываться{}, // описываться в статье
rus_verbs:качаться{}, // качаться в кроватке
rus_verbs:усилить{}, // усилить в центре
rus_verbs:прохаживаться{}, // прохаживаться в новом костюме
rus_verbs:полечить{}, // полечить в больничке
rus_verbs:сниматься{}, // сниматься в римейке
rus_verbs:сыскать{}, // сыскать в наших краях
rus_verbs:поприветствовать{}, // поприветствовать в коридоре
rus_verbs:подтвердиться{}, // подтвердиться в эксперименте
rus_verbs:плескаться{}, // плескаться в теплой водичке
rus_verbs:расширяться{}, // расширяться в первом сегменте
rus_verbs:мерещиться{}, // мерещиться в тумане
rus_verbs:сгущаться{}, // сгущаться в воздухе
rus_verbs:храпеть{}, // храпеть во сне
rus_verbs:подержать{}, // подержать в руках
rus_verbs:накинуться{}, // накинуться в подворотне
rus_verbs:планироваться{}, // планироваться в закрытом режиме
rus_verbs:пробудить{}, // пробудить в себе
rus_verbs:побриться{}, // побриться в ванной
rus_verbs:сгинуть{}, // сгинуть в пучине
rus_verbs:окрестить{}, // окрестить в церкви
инфинитив:резюмировать{ вид:соверш }, глагол:резюмировать{ вид:соверш }, // резюмировать в конце выступления
rus_verbs:замкнуться{}, // замкнуться в себе
rus_verbs:прибавлять{}, // прибавлять в весе
rus_verbs:проплыть{}, // проплыть в лодке
rus_verbs:растворяться{}, // растворяться в тумане
rus_verbs:упрекать{}, // упрекать в небрежности
rus_verbs:затеряться{}, // затеряться в лабиринте
rus_verbs:перечитывать{}, // перечитывать в поезде
rus_verbs:перелететь{}, // перелететь в вертолете
rus_verbs:оживать{}, // оживать в теплой воде
rus_verbs:заглохнуть{}, // заглохнуть в полете
rus_verbs:кольнуть{}, // кольнуть в боку
rus_verbs:копаться{}, // копаться в куче
rus_verbs:развлекаться{}, // развлекаться в клубе
rus_verbs:отливать{}, // отливать в кустах
rus_verbs:зажить{}, // зажить в деревне
rus_verbs:одолжить{}, // одолжить в соседнем кабинете
rus_verbs:заклинать{}, // заклинать в своей речи
rus_verbs:различаться{}, // различаться в мелочах
rus_verbs:печататься{}, // печататься в типографии
rus_verbs:угадываться{}, // угадываться в контурах
rus_verbs:обрывать{}, // обрывать в начале
rus_verbs:поглаживать{}, // поглаживать в кармане
rus_verbs:подписывать{}, // подписывать в присутствии понятых
rus_verbs:добывать{}, // добывать в разломе
rus_verbs:скопиться{}, // скопиться в воротах
rus_verbs:повстречать{}, // повстречать в бане
rus_verbs:совпасть{}, // совпасть в упрощенном виде
rus_verbs:разрываться{}, // разрываться в точке спайки
rus_verbs:улавливать{}, // улавливать в датчике
rus_verbs:повстречаться{}, // повстречаться в лифте
rus_verbs:отразить{}, // отразить в отчете
rus_verbs:пояснять{}, // пояснять в примечаниях
rus_verbs:накормить{}, // накормить в столовке
rus_verbs:поужинать{}, // поужинать в ресторане
инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть в суде
инфинитив:спеть{ вид:несоверш }, глагол:спеть{ вид:несоверш },
rus_verbs:топить{}, // топить в молоке
rus_verbs:освоить{}, // освоить в работе
rus_verbs:зародиться{}, // зародиться в голове
rus_verbs:отплыть{}, // отплыть в старой лодке
rus_verbs:отстаивать{}, // отстаивать в суде
rus_verbs:осуждать{}, // осуждать в своем выступлении
rus_verbs:переговорить{}, // переговорить в перерыве
rus_verbs:разгораться{}, // разгораться в сердце
rus_verbs:укрыть{}, // укрыть в шалаше
rus_verbs:томиться{}, // томиться в застенках
rus_verbs:клубиться{}, // клубиться в воздухе
rus_verbs:сжигать{}, // сжигать в топке
rus_verbs:позавтракать{}, // позавтракать в кафешке
rus_verbs:функционировать{}, // функционировать в лабораторных условиях
rus_verbs:смять{}, // смять в руке
rus_verbs:разместить{}, // разместить в интернете
rus_verbs:пронести{}, // пронести в потайном кармане
rus_verbs:руководствоваться{}, // руководствоваться в работе
rus_verbs:нашарить{}, // нашарить в потемках
rus_verbs:закрутить{}, // закрутить в вихре
rus_verbs:просматриваться{}, // просматриваться в дальней перспективе
rus_verbs:распознать{}, // распознать в незнакомце
rus_verbs:повеситься{}, // повеситься в камере
rus_verbs:обшарить{}, // обшарить в поисках наркотиков
rus_verbs:наполняться{}, // наполняется в карьере
rus_verbs:засвистеть{}, // засвистеть в воздухе
rus_verbs:процветать{}, // процветать в мягком климате
rus_verbs:шуршать{}, // шуршать в простенке
rus_verbs:подхватывать{}, // подхватывать в полете
инфинитив:роиться{}, глагол:роиться{}, // роиться в воздухе
прилагательное:роившийся{}, прилагательное:роящийся{},
// деепричастие:роясь{ aux stress="ро^ясь" },
rus_verbs:преобладать{}, // преобладать в тексте
rus_verbs:посветлеть{}, // посветлеть в лице
rus_verbs:игнорировать{}, // игнорировать в рекомендациях
rus_verbs:обсуждаться{}, // обсуждаться в кулуарах
rus_verbs:отказывать{}, // отказывать в визе
rus_verbs:ощупывать{}, // ощупывать в кармане
rus_verbs:разливаться{}, // разливаться в цеху
rus_verbs:расписаться{}, // расписаться в получении
rus_verbs:учинить{}, // учинить в казарме
rus_verbs:плестись{}, // плестись в хвосте
rus_verbs:объявляться{}, // объявляться в группе
rus_verbs:повышаться{}, // повышаться в первой части
rus_verbs:напрягать{}, // напрягать в паху
rus_verbs:разрабатывать{}, // разрабатывать в студии
rus_verbs:хлопотать{}, // хлопотать в мэрии
rus_verbs:прерывать{}, // прерывать в самом начале
rus_verbs:каяться{}, // каяться в грехах
rus_verbs:освоиться{}, // освоиться в кабине
rus_verbs:подплыть{}, // подплыть в лодке
rus_verbs:замигать{}, // замигать в темноте
rus_verbs:оскорблять{}, // оскорблять в выступлении
rus_verbs:торжествовать{}, // торжествовать в душе
rus_verbs:поправлять{}, // поправлять в прологе
rus_verbs:угадывать{}, // угадывать в размытом изображении
rus_verbs:потоптаться{}, // потоптаться в прихожей
rus_verbs:переправиться{}, // переправиться в лодочке
rus_verbs:увериться{}, // увериться в невиновности
rus_verbs:забрезжить{}, // забрезжить в конце тоннеля
rus_verbs:утвердиться{}, // утвердиться во мнении
rus_verbs:завывать{}, // завывать в трубе
rus_verbs:заварить{}, // заварить в заварнике
rus_verbs:скомкать{}, // скомкать в руке
rus_verbs:перемещаться{}, // перемещаться в капсуле
инфинитив:писаться{ aux stress="пис^аться" }, глагол:писаться{ aux stress="пис^аться" }, // писаться в первом поле
rus_verbs:праздновать{}, // праздновать в баре
rus_verbs:мигать{}, // мигать в темноте
rus_verbs:обучить{}, // обучить в мастерской
rus_verbs:орудовать{}, // орудовать в кладовке
rus_verbs:упорствовать{}, // упорствовать в заблуждении
rus_verbs:переминаться{}, // переминаться в прихожей
rus_verbs:подрасти{}, // подрасти в теплице
rus_verbs:предписываться{}, // предписываться в законе
rus_verbs:приписать{}, // приписать в конце
rus_verbs:задаваться{}, // задаваться в своей статье
rus_verbs:чинить{}, // чинить в домашних условиях
rus_verbs:раздеваться{}, // раздеваться в пляжной кабинке
rus_verbs:пообедать{}, // пообедать в ресторанчике
rus_verbs:жрать{}, // жрать в чуланчике
rus_verbs:исполняться{}, // исполняться в антракте
rus_verbs:гнить{}, // гнить в тюрьме
rus_verbs:глодать{}, // глодать в конуре
rus_verbs:прослушать{}, // прослушать в дороге
rus_verbs:истратить{}, // истратить в кабаке
rus_verbs:стареть{}, // стареть в одиночестве
rus_verbs:разжечь{}, // разжечь в сердце
rus_verbs:совещаться{}, // совещаться в кабинете
rus_verbs:покачивать{}, // покачивать в кроватке
rus_verbs:отсидеть{}, // отсидеть в одиночке
rus_verbs:формировать{}, // формировать в умах
rus_verbs:захрапеть{}, // захрапеть во сне
rus_verbs:петься{}, // петься в хоре
rus_verbs:объехать{}, // объехать в автобусе
rus_verbs:поселить{}, // поселить в гостинице
rus_verbs:предаться{}, // предаться в книге
rus_verbs:заворочаться{}, // заворочаться во сне
rus_verbs:напрятать{}, // напрятать в карманах
rus_verbs:очухаться{}, // очухаться в незнакомом месте
rus_verbs:ограничивать{}, // ограничивать в движениях
rus_verbs:завертеть{}, // завертеть в руках
rus_verbs:печатать{}, // печатать в редакторе
rus_verbs:теплиться{}, // теплиться в сердце
rus_verbs:увязнуть{}, // увязнуть в зыбучем песке
rus_verbs:усмотреть{}, // усмотреть в обращении
rus_verbs:отыскаться{}, // отыскаться в запасах
rus_verbs:потушить{}, // потушить в горле огонь
rus_verbs:поубавиться{}, // поубавиться в размере
rus_verbs:зафиксировать{}, // зафиксировать в постоянной памяти
rus_verbs:смыть{}, // смыть в ванной
rus_verbs:заместить{}, // заместить в кресле
rus_verbs:угасать{}, // угасать в одиночестве
rus_verbs:сразить{}, // сразить в споре
rus_verbs:фигурировать{}, // фигурировать в бюллетене
rus_verbs:расплываться{}, // расплываться в глазах
rus_verbs:сосчитать{}, // сосчитать в уме
rus_verbs:сгуститься{}, // сгуститься в воздухе
rus_verbs:цитировать{}, // цитировать в своей статье
rus_verbs:помяться{}, // помяться в давке
rus_verbs:затрагивать{}, // затрагивать в процессе выполнения
rus_verbs:обтереть{}, // обтереть в гараже
rus_verbs:подстрелить{}, // подстрелить в пойме реки
rus_verbs:растереть{}, // растереть в руке
rus_verbs:подавлять{}, // подавлять в зародыше
rus_verbs:смешиваться{}, // смешиваться в чане
инфинитив:вычитать{ вид:соверш }, глагол:вычитать{ вид:соверш }, // вычитать в книжечке
rus_verbs:сократиться{}, // сократиться в обхвате
rus_verbs:занервничать{}, // занервничать в кабинете
rus_verbs:соприкоснуться{}, // соприкоснуться в полете
rus_verbs:обозначить{}, // обозначить в объявлении
rus_verbs:обучаться{}, // обучаться в училище
rus_verbs:снизиться{}, // снизиться в нижних слоях атмосферы
rus_verbs:лелеять{}, // лелеять в сердце
rus_verbs:поддерживаться{}, // поддерживаться в суде
rus_verbs:уплыть{}, // уплыть в лодочке
rus_verbs:резвиться{}, // резвиться в саду
rus_verbs:поерзать{}, // поерзать в гамаке
rus_verbs:оплатить{}, // оплатить в ресторане
rus_verbs:похвастаться{}, // похвастаться в компании
rus_verbs:знакомиться{}, // знакомиться в классе
rus_verbs:приплыть{}, // приплыть в подводной лодке
rus_verbs:зажигать{}, // зажигать в классе
rus_verbs:смыслить{}, // смыслить в математике
rus_verbs:закопать{}, // закопать в огороде
rus_verbs:порхать{}, // порхать в зарослях
rus_verbs:потонуть{}, // потонуть в бумажках
rus_verbs:стирать{}, // стирать в холодной воде
rus_verbs:подстерегать{}, // подстерегать в придорожных кустах
rus_verbs:погулять{}, // погулять в парке
rus_verbs:предвкушать{}, // предвкушать в воображении
rus_verbs:ошеломить{}, // ошеломить в бою
rus_verbs:удостовериться{}, // удостовериться в безопасности
rus_verbs:огласить{}, // огласить в заключительной части
rus_verbs:разбогатеть{}, // разбогатеть в деревне
rus_verbs:грохотать{}, // грохотать в мастерской
rus_verbs:реализоваться{}, // реализоваться в должности
rus_verbs:красть{}, // красть в магазине
rus_verbs:нарваться{}, // нарваться в коридоре
rus_verbs:застывать{}, // застывать в неудобной позе
rus_verbs:толкаться{}, // толкаться в тесной комнате
rus_verbs:извлекать{}, // извлекать в аппарате
rus_verbs:обжигать{}, // обжигать в печи
rus_verbs:запечатлеть{}, // запечатлеть в кинохронике
rus_verbs:тренироваться{}, // тренироваться в зале
rus_verbs:поспорить{}, // поспорить в кабинете
rus_verbs:рыскать{}, // рыскать в лесу
rus_verbs:надрываться{}, // надрываться в шахте
rus_verbs:сняться{}, // сняться в фильме
rus_verbs:закружить{}, // закружить в танце
rus_verbs:затонуть{}, // затонуть в порту
rus_verbs:побыть{}, // побыть в гостях
rus_verbs:почистить{}, // почистить в носу
rus_verbs:сгорбиться{}, // сгорбиться в тесной конуре
rus_verbs:подслушивать{}, // подслушивать в классе
rus_verbs:сгорать{}, // сгорать в танке
rus_verbs:разочароваться{}, // разочароваться в артисте
инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать в кустиках
rus_verbs:мять{}, // мять в руках
rus_verbs:подраться{}, // подраться в классе
rus_verbs:замести{}, // замести в прихожей
rus_verbs:откладываться{}, // откладываться в печени
rus_verbs:обозначаться{}, // обозначаться в перечне
rus_verbs:просиживать{}, // просиживать в интернете
rus_verbs:соприкасаться{}, // соприкасаться в точке
rus_verbs:начертить{}, // начертить в тетрадке
rus_verbs:уменьшать{}, // уменьшать в поперечнике
rus_verbs:тормозить{}, // тормозить в облаке
rus_verbs:затевать{}, // затевать в лаборатории
rus_verbs:затопить{}, // затопить в бухте
rus_verbs:задерживать{}, // задерживать в лифте
rus_verbs:прогуляться{}, // прогуляться в лесу
rus_verbs:прорубить{}, // прорубить во льду
rus_verbs:очищать{}, // очищать в кислоте
rus_verbs:полулежать{}, // полулежать в гамаке
rus_verbs:исправить{}, // исправить в задании
rus_verbs:предусматриваться{}, // предусматриваться в постановке задачи
rus_verbs:замучить{}, // замучить в плену
rus_verbs:разрушаться{}, // разрушаться в верхней части
rus_verbs:ерзать{}, // ерзать в кресле
rus_verbs:покопаться{}, // покопаться в залежах
rus_verbs:раскаяться{}, // раскаяться в содеянном
rus_verbs:пробежаться{}, // пробежаться в парке
rus_verbs:полежать{}, // полежать в гамаке
rus_verbs:позаимствовать{}, // позаимствовать в книге
rus_verbs:снижать{}, // снижать в несколько раз
rus_verbs:черпать{}, // черпать в поэзии
rus_verbs:заверять{}, // заверять в своей искренности
rus_verbs:проглядеть{}, // проглядеть в сумерках
rus_verbs:припарковать{}, // припарковать во дворе
rus_verbs:сверлить{}, // сверлить в стене
rus_verbs:здороваться{}, // здороваться в аудитории
rus_verbs:рожать{}, // рожать в воде
rus_verbs:нацарапать{}, // нацарапать в тетрадке
rus_verbs:затопать{}, // затопать в коридоре
rus_verbs:прописать{}, // прописать в правилах
rus_verbs:сориентироваться{}, // сориентироваться в обстоятельствах
rus_verbs:снизить{}, // снизить в несколько раз
rus_verbs:заблуждаться{}, // заблуждаться в своей теории
rus_verbs:откопать{}, // откопать в отвалах
rus_verbs:смастерить{}, // смастерить в лаборатории
rus_verbs:замедлиться{}, // замедлиться в парафине
rus_verbs:избивать{}, // избивать в участке
rus_verbs:мыться{}, // мыться в бане
rus_verbs:сварить{}, // сварить в кастрюльке
rus_verbs:раскопать{}, // раскопать в снегу
rus_verbs:крепиться{}, // крепиться в держателе
rus_verbs:дробить{}, // дробить в мельнице
rus_verbs:попить{}, // попить в ресторанчике
rus_verbs:затронуть{}, // затронуть в душе
rus_verbs:лязгнуть{}, // лязгнуть в тишине
rus_verbs:заправлять{}, // заправлять в полете
rus_verbs:размножаться{}, // размножаться в неволе
rus_verbs:потопить{}, // потопить в Тихом Океане
rus_verbs:кушать{}, // кушать в столовой
rus_verbs:замолкать{}, // замолкать в замешательстве
rus_verbs:измеряться{}, // измеряться в дюймах
rus_verbs:сбываться{}, // сбываться в мечтах
rus_verbs:задернуть{}, // задернуть в комнате
rus_verbs:затихать{}, // затихать в темноте
rus_verbs:прослеживаться{}, // прослеживается в журнале
rus_verbs:прерываться{}, // прерывается в начале
rus_verbs:изображаться{}, // изображается в любых фильмах
rus_verbs:фиксировать{}, // фиксировать в данной точке
rus_verbs:ослаблять{}, // ослаблять в поясе
rus_verbs:зреть{}, // зреть в теплице
rus_verbs:зеленеть{}, // зеленеть в огороде
rus_verbs:критиковать{}, // критиковать в статье
rus_verbs:облететь{}, // облететь в частном вертолете
rus_verbs:разбросать{}, // разбросать в комнате
rus_verbs:заразиться{}, // заразиться в людном месте
rus_verbs:рассеять{}, // рассеять в бою
rus_verbs:печься{}, // печься в духовке
rus_verbs:поспать{}, // поспать в палатке
rus_verbs:заступиться{}, // заступиться в драке
rus_verbs:сплетаться{}, // сплетаться в середине
rus_verbs:поместиться{}, // поместиться в мешке
rus_verbs:спереть{}, // спереть в лавке
// инфинитив:ликвидировать{ вид:несоверш }, глагол:ликвидировать{ вид:несоверш }, // ликвидировать в пригороде
// инфинитив:ликвидировать{ вид:соверш }, глагол:ликвидировать{ вид:соверш },
rus_verbs:проваляться{}, // проваляться в постели
rus_verbs:лечиться{}, // лечиться в стационаре
rus_verbs:определиться{}, // определиться в честном бою
rus_verbs:обработать{}, // обработать в растворе
rus_verbs:пробивать{}, // пробивать в стене
rus_verbs:перемешаться{}, // перемешаться в чане
rus_verbs:чесать{}, // чесать в паху
rus_verbs:пролечь{}, // пролечь в пустынной местности
rus_verbs:скитаться{}, // скитаться в дальних странах
rus_verbs:затрудняться{}, // затрудняться в выборе
rus_verbs:отряхнуться{}, // отряхнуться в коридоре
rus_verbs:разыгрываться{}, // разыгрываться в лотерее
rus_verbs:помолиться{}, // помолиться в церкви
rus_verbs:предписывать{}, // предписывать в рецепте
rus_verbs:порваться{}, // порваться в слабом месте
rus_verbs:греться{}, // греться в здании
rus_verbs:опровергать{}, // опровергать в своем выступлении
rus_verbs:помянуть{}, // помянуть в своем выступлении
rus_verbs:допросить{}, // допросить в прокуратуре
rus_verbs:материализоваться{}, // материализоваться в соседнем здании
rus_verbs:рассеиваться{}, // рассеиваться в воздухе
rus_verbs:перевозить{}, // перевозить в вагоне
rus_verbs:отбывать{}, // отбывать в тюрьме
rus_verbs:попахивать{}, // попахивать в отхожем месте
rus_verbs:перечислять{}, // перечислять в заключении
rus_verbs:зарождаться{}, // зарождаться в дебрях
rus_verbs:предъявлять{}, // предъявлять в своем письме
rus_verbs:распространять{}, // распространять в сети
rus_verbs:пировать{}, // пировать в соседнем селе
rus_verbs:начертать{}, // начертать в летописи
rus_verbs:расцветать{}, // расцветать в подходящих условиях
rus_verbs:царствовать{}, // царствовать в южной части материка
rus_verbs:накопить{}, // накопить в буфере
rus_verbs:закрутиться{}, // закрутиться в рутине
rus_verbs:отработать{}, // отработать в забое
rus_verbs:обокрасть{}, // обокрасть в автобусе
rus_verbs:прокладывать{}, // прокладывать в снегу
rus_verbs:ковырять{}, // ковырять в носу
rus_verbs:копить{}, // копить в очереди
rus_verbs:полечь{}, // полечь в степях
rus_verbs:щебетать{}, // щебетать в кустиках
rus_verbs:подчеркиваться{}, // подчеркиваться в сообщении
rus_verbs:посеять{}, // посеять в огороде
rus_verbs:разъезжать{}, // разъезжать в кабриолете
rus_verbs:замечаться{}, // замечаться в лесу
rus_verbs:просчитать{}, // просчитать в уме
rus_verbs:маяться{}, // маяться в командировке
rus_verbs:выхватывать{}, // выхватывать в тексте
rus_verbs:креститься{}, // креститься в деревенской часовне
rus_verbs:обрабатывать{}, // обрабатывать в растворе кислоты
rus_verbs:настигать{}, // настигать в огороде
rus_verbs:разгуливать{}, // разгуливать в роще
rus_verbs:насиловать{}, // насиловать в квартире
rus_verbs:побороть{}, // побороть в себе
rus_verbs:учитывать{}, // учитывать в расчетах
rus_verbs:искажать{}, // искажать в заметке
rus_verbs:пропить{}, // пропить в кабаке
rus_verbs:катать{}, // катать в лодочке
rus_verbs:припрятать{}, // припрятать в кармашке
rus_verbs:запаниковать{}, // запаниковать в бою
rus_verbs:рассыпать{}, // рассыпать в траве
rus_verbs:застревать{}, // застревать в ограде
rus_verbs:зажигаться{}, // зажигаться в сумерках
rus_verbs:жарить{}, // жарить в масле
rus_verbs:накапливаться{}, // накапливаться в костях
rus_verbs:распуститься{}, // распуститься в горшке
rus_verbs:проголосовать{}, // проголосовать в передвижном пункте
rus_verbs:странствовать{}, // странствовать в автомобиле
rus_verbs:осматриваться{}, // осматриваться в хоромах
rus_verbs:разворачивать{}, // разворачивать в спортзале
rus_verbs:заскучать{}, // заскучать в самолете
rus_verbs:напутать{}, // напутать в расчете
rus_verbs:перекусить{}, // перекусить в столовой
rus_verbs:спасаться{}, // спасаться в автономной капсуле
rus_verbs:посовещаться{}, // посовещаться в комнате
rus_verbs:доказываться{}, // доказываться в статье
rus_verbs:познаваться{}, // познаваться в беде
rus_verbs:загрустить{}, // загрустить в одиночестве
rus_verbs:оживить{}, // оживить в памяти
rus_verbs:переворачиваться{}, // переворачиваться в гробу
rus_verbs:заприметить{}, // заприметить в лесу
rus_verbs:отравиться{}, // отравиться в забегаловке
rus_verbs:продержать{}, // продержать в клетке
rus_verbs:выявить{}, // выявить в костях
rus_verbs:заседать{}, // заседать в совете
rus_verbs:расплачиваться{}, // расплачиваться в первой кассе
rus_verbs:проломить{}, // проломить в двери
rus_verbs:подражать{}, // подражать в мелочах
rus_verbs:подсчитывать{}, // подсчитывать в уме
rus_verbs:опережать{}, // опережать во всем
rus_verbs:сформироваться{}, // сформироваться в облаке
rus_verbs:укрепиться{}, // укрепиться в мнении
rus_verbs:отстоять{}, // отстоять в очереди
rus_verbs:развертываться{}, // развертываться в месте испытания
rus_verbs:замерзать{}, // замерзать во льду
rus_verbs:утопать{}, // утопать в снегу
rus_verbs:раскаиваться{}, // раскаиваться в содеянном
rus_verbs:организовывать{}, // организовывать в пионерлагере
rus_verbs:перевестись{}, // перевестись в наших краях
rus_verbs:смешивать{}, // смешивать в блендере
rus_verbs:ютиться{}, // ютиться в тесной каморке
rus_verbs:прождать{}, // прождать в аудитории
rus_verbs:подыскивать{}, // подыскивать в женском общежитии
rus_verbs:замочить{}, // замочить в сортире
rus_verbs:мерзнуть{}, // мерзнуть в тонкой курточке
rus_verbs:растирать{}, // растирать в ступке
rus_verbs:замедлять{}, // замедлять в парафине
rus_verbs:переспать{}, // переспать в палатке
rus_verbs:рассекать{}, // рассекать в кабриолете
rus_verbs:отыскивать{}, // отыскивать в залежах
rus_verbs:опровергнуть{}, // опровергнуть в своем выступлении
rus_verbs:дрыхнуть{}, // дрыхнуть в гамаке
rus_verbs:укрываться{}, // укрываться в землянке
rus_verbs:запечься{}, // запечься в золе
rus_verbs:догорать{}, // догорать в темноте
rus_verbs:застилать{}, // застилать в коридоре
rus_verbs:сыскаться{}, // сыскаться в деревне
rus_verbs:переделать{}, // переделать в мастерской
rus_verbs:разъяснять{}, // разъяснять в своей лекции
rus_verbs:селиться{}, // селиться в центре
rus_verbs:оплачивать{}, // оплачивать в магазине
rus_verbs:переворачивать{}, // переворачивать в закрытой банке
rus_verbs:упражняться{}, // упражняться в остроумии
rus_verbs:пометить{}, // пометить в списке
rus_verbs:припомниться{}, // припомниться в завещании
rus_verbs:приютить{}, // приютить в амбаре
rus_verbs:натерпеться{}, // натерпеться в темнице
rus_verbs:затеваться{}, // затеваться в клубе
rus_verbs:уплывать{}, // уплывать в лодке
rus_verbs:скиснуть{}, // скиснуть в бидоне
rus_verbs:заколоть{}, // заколоть в боку
rus_verbs:замерцать{}, // замерцать в темноте
rus_verbs:фиксироваться{}, // фиксироваться в протоколе
rus_verbs:запираться{}, // запираться в комнате
rus_verbs:съезжаться{}, // съезжаться в каретах
rus_verbs:толочься{}, // толочься в ступе
rus_verbs:потанцевать{}, // потанцевать в клубе
rus_verbs:побродить{}, // побродить в парке
rus_verbs:назревать{}, // назревать в коллективе
rus_verbs:дохнуть{}, // дохнуть в питомнике
rus_verbs:крестить{}, // крестить в деревенской церквушке
rus_verbs:рассчитаться{}, // рассчитаться в банке
rus_verbs:припарковаться{}, // припарковаться во дворе
rus_verbs:отхватить{}, // отхватить в магазинчике
rus_verbs:остывать{}, // остывать в холодильнике
rus_verbs:составляться{}, // составляться в атмосфере тайны
rus_verbs:переваривать{}, // переваривать в тишине
rus_verbs:хвастать{}, // хвастать в казино
rus_verbs:отрабатывать{}, // отрабатывать в теплице
rus_verbs:разлечься{}, // разлечься в кровати
rus_verbs:прокручивать{}, // прокручивать в голове
rus_verbs:очертить{}, // очертить в воздухе
rus_verbs:сконфузиться{}, // сконфузиться в окружении незнакомых людей
rus_verbs:выявлять{}, // выявлять в боевых условиях
rus_verbs:караулить{}, // караулить в лифте
rus_verbs:расставлять{}, // расставлять в бойницах
rus_verbs:прокрутить{}, // прокрутить в голове
rus_verbs:пересказывать{}, // пересказывать в первой главе
rus_verbs:задавить{}, // задавить в зародыше
rus_verbs:хозяйничать{}, // хозяйничать в холодильнике
rus_verbs:хвалиться{}, // хвалиться в детском садике
rus_verbs:оперировать{}, // оперировать в полевом госпитале
rus_verbs:формулировать{}, // формулировать в следующей главе
rus_verbs:застигнуть{}, // застигнуть в неприглядном виде
rus_verbs:замурлыкать{}, // замурлыкать в тепле
rus_verbs:поддакивать{}, // поддакивать в споре
rus_verbs:прочертить{}, // прочертить в воздухе
rus_verbs:отменять{}, // отменять в городе коменданский час
rus_verbs:колдовать{}, // колдовать в лаборатории
rus_verbs:отвозить{}, // отвозить в машине
rus_verbs:трахать{}, // трахать в гамаке
rus_verbs:повозиться{}, // повозиться в мешке
rus_verbs:ремонтировать{}, // ремонтировать в центре
rus_verbs:робеть{}, // робеть в гостях
rus_verbs:перепробовать{}, // перепробовать в деле
инфинитив:реализовать{ вид:соверш }, инфинитив:реализовать{ вид:несоверш }, // реализовать в новой версии
глагол:реализовать{ вид:соверш }, глагол:реализовать{ вид:несоверш },
rus_verbs:покаяться{}, // покаяться в церкви
rus_verbs:попрыгать{}, // попрыгать в бассейне
rus_verbs:умалчивать{}, // умалчивать в своем докладе
rus_verbs:ковыряться{}, // ковыряться в старой технике
rus_verbs:расписывать{}, // расписывать в деталях
rus_verbs:вязнуть{}, // вязнуть в песке
rus_verbs:погрязнуть{}, // погрязнуть в скандалах
rus_verbs:корениться{}, // корениться в неспособности выполнить поставленную задачу
rus_verbs:зажимать{}, // зажимать в углу
rus_verbs:стискивать{}, // стискивать в ладонях
rus_verbs:практиковаться{}, // практиковаться в приготовлении соуса
rus_verbs:израсходовать{}, // израсходовать в полете
rus_verbs:клокотать{}, // клокотать в жерле
rus_verbs:обвиняться{}, // обвиняться в растрате
rus_verbs:уединиться{}, // уединиться в кладовке
rus_verbs:подохнуть{}, // подохнуть в болоте
rus_verbs:кипятиться{}, // кипятиться в чайнике
rus_verbs:уродиться{}, // уродиться в лесу
rus_verbs:продолжиться{}, // продолжиться в баре
rus_verbs:расшифровать{}, // расшифровать в специальном устройстве
rus_verbs:посапывать{}, // посапывать в кровати
rus_verbs:скрючиться{}, // скрючиться в мешке
rus_verbs:лютовать{}, // лютовать в отдаленных селах
rus_verbs:расписать{}, // расписать в статье
rus_verbs:публиковаться{}, // публиковаться в научном журнале
rus_verbs:зарегистрировать{}, // зарегистрировать в комитете
rus_verbs:прожечь{}, // прожечь в листе
rus_verbs:переждать{}, // переждать в окопе
rus_verbs:публиковать{}, // публиковать в журнале
rus_verbs:морщить{}, // морщить в уголках глаз
rus_verbs:спиться{}, // спиться в одиночестве
rus_verbs:изведать{}, // изведать в гареме
rus_verbs:обмануться{}, // обмануться в ожиданиях
rus_verbs:сочетать{}, // сочетать в себе
rus_verbs:подрабатывать{}, // подрабатывать в магазине
rus_verbs:репетировать{}, // репетировать в студии
rus_verbs:рябить{}, // рябить в глазах
rus_verbs:намочить{}, // намочить в луже
rus_verbs:скатать{}, // скатать в руке
rus_verbs:одевать{}, // одевать в магазине
rus_verbs:испечь{}, // испечь в духовке
rus_verbs:сбрить{}, // сбрить в подмышках
rus_verbs:зажужжать{}, // зажужжать в ухе
rus_verbs:сберечь{}, // сберечь в тайном месте
rus_verbs:согреться{}, // согреться в хижине
инфинитив:дебютировать{ вид:несоверш }, инфинитив:дебютировать{ вид:соверш }, // дебютировать в спектакле
глагол:дебютировать{ вид:несоверш }, глагол:дебютировать{ вид:соверш },
rus_verbs:переплыть{}, // переплыть в лодочке
rus_verbs:передохнуть{}, // передохнуть в тени
rus_verbs:отсвечивать{}, // отсвечивать в зеркалах
rus_verbs:переправляться{}, // переправляться в лодках
rus_verbs:накупить{}, // накупить в магазине
rus_verbs:проторчать{}, // проторчать в очереди
rus_verbs:проскальзывать{}, // проскальзывать в сообщениях
rus_verbs:застукать{}, // застукать в солярии
rus_verbs:наесть{}, // наесть в отпуске
rus_verbs:подвизаться{}, // подвизаться в новом деле
rus_verbs:вычистить{}, // вычистить в саду
rus_verbs:кормиться{}, // кормиться в лесу
rus_verbs:покурить{}, // покурить в саду
rus_verbs:понизиться{}, // понизиться в ранге
rus_verbs:зимовать{}, // зимовать в избушке
rus_verbs:проверяться{}, // проверяться в службе безопасности
rus_verbs:подпирать{}, // подпирать в первом забое
rus_verbs:кувыркаться{}, // кувыркаться в постели
rus_verbs:похрапывать{}, // похрапывать в постели
rus_verbs:завязнуть{}, // завязнуть в песке
rus_verbs:трактовать{}, // трактовать в исследовательской статье
rus_verbs:замедляться{}, // замедляться в тяжелой воде
rus_verbs:шастать{}, // шастать в здании
rus_verbs:заночевать{}, // заночевать в пути
rus_verbs:наметиться{}, // наметиться в исследованиях рака
rus_verbs:освежить{}, // освежить в памяти
rus_verbs:оспаривать{}, // оспаривать в суде
rus_verbs:умещаться{}, // умещаться в ячейке
rus_verbs:искупить{}, // искупить в бою
rus_verbs:отсиживаться{}, // отсиживаться в тылу
rus_verbs:мчать{}, // мчать в кабриолете
rus_verbs:обличать{}, // обличать в своем выступлении
rus_verbs:сгнить{}, // сгнить в тюряге
rus_verbs:опробовать{}, // опробовать в деле
rus_verbs:тренировать{}, // тренировать в зале
rus_verbs:прославить{}, // прославить в академии
rus_verbs:учитываться{}, // учитываться в дипломной работе
rus_verbs:повеселиться{}, // повеселиться в лагере
rus_verbs:поумнеть{}, // поумнеть в карцере
rus_verbs:перестрелять{}, // перестрелять в воздухе
rus_verbs:проведать{}, // проведать в больнице
rus_verbs:измучиться{}, // измучиться в деревне
rus_verbs:прощупать{}, // прощупать в глубине
rus_verbs:изготовлять{}, // изготовлять в сарае
rus_verbs:свирепствовать{}, // свирепствовать в популяции
rus_verbs:иссякать{}, // иссякать в источнике
rus_verbs:гнездиться{}, // гнездиться в дупле
rus_verbs:разогнаться{}, // разогнаться в спортивной машине
rus_verbs:опознавать{}, // опознавать в неизвестном
rus_verbs:засвидетельствовать{}, // засвидетельствовать в суде
rus_verbs:сконцентрировать{}, // сконцентрировать в своих руках
rus_verbs:редактировать{}, // редактировать в редакторе
rus_verbs:покупаться{}, // покупаться в магазине
rus_verbs:промышлять{}, // промышлять в роще
rus_verbs:растягиваться{}, // растягиваться в коридоре
rus_verbs:приобретаться{}, // приобретаться в антикварных лавках
инфинитив:подрезать{ вид:несоверш }, инфинитив:подрезать{ вид:соверш }, // подрезать в воде
глагол:подрезать{ вид:несоверш }, глагол:подрезать{ вид:соверш },
rus_verbs:запечатлеться{}, // запечатлеться в мозгу
rus_verbs:укрывать{}, // укрывать в подвале
rus_verbs:закрепиться{}, // закрепиться в первой башне
rus_verbs:освежать{}, // освежать в памяти
rus_verbs:громыхать{}, // громыхать в ванной
инфинитив:подвигаться{ вид:соверш }, инфинитив:подвигаться{ вид:несоверш }, // подвигаться в кровати
глагол:подвигаться{ вид:соверш }, глагол:подвигаться{ вид:несоверш },
rus_verbs:добываться{}, // добываться в шахтах
rus_verbs:растворить{}, // растворить в кислоте
rus_verbs:приплясывать{}, // приплясывать в гримерке
rus_verbs:доживать{}, // доживать в доме престарелых
rus_verbs:отпраздновать{}, // отпраздновать в ресторане
rus_verbs:сотрясаться{}, // сотрясаться в конвульсиях
rus_verbs:помыть{}, // помыть в проточной воде
инфинитив:увязать{ вид:несоверш }, инфинитив:увязать{ вид:соверш }, // увязать в песке
глагол:увязать{ вид:несоверш }, глагол:увязать{ вид:соверш },
прилагательное:увязавший{ вид:несоверш },
rus_verbs:наличествовать{}, // наличествовать в запаснике
rus_verbs:нащупывать{}, // нащупывать в кармане
rus_verbs:повествоваться{}, // повествоваться в рассказе
rus_verbs:отремонтировать{}, // отремонтировать в техцентре
rus_verbs:покалывать{}, // покалывать в правом боку
rus_verbs:сиживать{}, // сиживать в саду
rus_verbs:разрабатываться{}, // разрабатываться в секретных лабораториях
rus_verbs:укрепляться{}, // укрепляться в мнении
rus_verbs:разниться{}, // разниться во взглядах
rus_verbs:сполоснуть{}, // сполоснуть в водичке
rus_verbs:скупать{}, // скупать в магазине
rus_verbs:почесывать{}, // почесывать в паху
rus_verbs:оформлять{}, // оформлять в конторе
rus_verbs:распускаться{}, // распускаться в садах
rus_verbs:зарябить{}, // зарябить в глазах
rus_verbs:загореть{}, // загореть в Испании
rus_verbs:очищаться{}, // очищаться в баке
rus_verbs:остудить{}, // остудить в холодной воде
rus_verbs:разбомбить{}, // разбомбить в горах
rus_verbs:издохнуть{}, // издохнуть в бедности
rus_verbs:проехаться{}, // проехаться в новой машине
rus_verbs:задействовать{}, // задействовать в анализе
rus_verbs:произрастать{}, // произрастать в степи
rus_verbs:разуться{}, // разуться в прихожей
rus_verbs:сооружать{}, // сооружать в огороде
rus_verbs:зачитывать{}, // зачитывать в суде
rus_verbs:состязаться{}, // состязаться в остроумии
rus_verbs:ополоснуть{}, // ополоснуть в молоке
rus_verbs:уместиться{}, // уместиться в кармане
rus_verbs:совершенствоваться{}, // совершенствоваться в управлении мотоциклом
rus_verbs:стираться{}, // стираться в стиральной машине
rus_verbs:искупаться{}, // искупаться в прохладной реке
rus_verbs:курировать{}, // курировать в правительстве
rus_verbs:закупить{}, // закупить в магазине
rus_verbs:плодиться{}, // плодиться в подходящих условиях
rus_verbs:горланить{}, // горланить в парке
rus_verbs:першить{}, // першить в горле
rus_verbs:пригрезиться{}, // пригрезиться во сне
rus_verbs:исправлять{}, // исправлять в тетрадке
rus_verbs:расслабляться{}, // расслабляться в гамаке
rus_verbs:скапливаться{}, // скапливаться в нижней части
rus_verbs:сплетничать{}, // сплетничают в комнате
rus_verbs:раздевать{}, // раздевать в кабинке
rus_verbs:окопаться{}, // окопаться в лесу
rus_verbs:загорать{}, // загорать в Испании
rus_verbs:подпевать{}, // подпевать в церковном хоре
rus_verbs:прожужжать{}, // прожужжать в динамике
rus_verbs:изучаться{}, // изучаться в дикой природе
rus_verbs:заклубиться{}, // заклубиться в воздухе
rus_verbs:подметать{}, // подметать в зале
rus_verbs:подозреваться{}, // подозреваться в совершении кражи
rus_verbs:обогащать{}, // обогащать в специальном аппарате
rus_verbs:издаться{}, // издаться в другом издательстве
rus_verbs:справить{}, // справить в кустах нужду
rus_verbs:помыться{}, // помыться в бане
rus_verbs:проскакивать{}, // проскакивать в словах
rus_verbs:попивать{}, // попивать в кафе чай
rus_verbs:оформляться{}, // оформляться в регистратуре
rus_verbs:чирикать{}, // чирикать в кустах
rus_verbs:скупить{}, // скупить в магазинах
rus_verbs:переночевать{}, // переночевать в гостинице
rus_verbs:концентрироваться{}, // концентрироваться в пробирке
rus_verbs:одичать{}, // одичать в лесу
rus_verbs:ковырнуть{}, // ковырнуть в ухе
rus_verbs:затеплиться{}, // затеплиться в глубине души
rus_verbs:разгрести{}, // разгрести в задачах залежи
rus_verbs:застопориться{}, // застопориться в начале списка
rus_verbs:перечисляться{}, // перечисляться во введении
rus_verbs:покататься{}, // покататься в парке аттракционов
rus_verbs:изловить{}, // изловить в поле
rus_verbs:прославлять{}, // прославлять в стихах
rus_verbs:промочить{}, // промочить в луже
rus_verbs:поделывать{}, // поделывать в отпуске
rus_verbs:просуществовать{}, // просуществовать в первобытном состоянии
rus_verbs:подстеречь{}, // подстеречь в подъезде
rus_verbs:прикупить{}, // прикупить в магазине
rus_verbs:перемешивать{}, // перемешивать в кастрюле
rus_verbs:тискать{}, // тискать в углу
rus_verbs:купать{}, // купать в теплой водичке
rus_verbs:завариться{}, // завариться в стакане
rus_verbs:притулиться{}, // притулиться в углу
rus_verbs:пострелять{}, // пострелять в тире
rus_verbs:навесить{}, // навесить в больнице
инфинитив:изолировать{ вид:соверш }, инфинитив:изолировать{ вид:несоверш }, // изолировать в камере
глагол:изолировать{ вид:соверш }, глагол:изолировать{ вид:несоверш },
rus_verbs:нежиться{}, // нежится в постельке
rus_verbs:притомиться{}, // притомиться в школе
rus_verbs:раздвоиться{}, // раздвоиться в глазах
rus_verbs:навалить{}, // навалить в углу
rus_verbs:замуровать{}, // замуровать в склепе
rus_verbs:поселяться{}, // поселяться в кроне дуба
rus_verbs:потягиваться{}, // потягиваться в кровати
rus_verbs:укачать{}, // укачать в поезде
rus_verbs:отлеживаться{}, // отлеживаться в гамаке
rus_verbs:разменять{}, // разменять в кассе
rus_verbs:прополоскать{}, // прополоскать в чистой теплой воде
rus_verbs:ржаветь{}, // ржаветь в воде
rus_verbs:уличить{}, // уличить в плагиате
rus_verbs:мутиться{}, // мутиться в голове
rus_verbs:растворять{}, // растворять в бензоле
rus_verbs:двоиться{}, // двоиться в глазах
rus_verbs:оговорить{}, // оговорить в договоре
rus_verbs:подделать{}, // подделать в документе
rus_verbs:зарегистрироваться{}, // зарегистрироваться в социальной сети
rus_verbs:растолстеть{}, // растолстеть в талии
rus_verbs:повоевать{}, // повоевать в городских условиях
rus_verbs:прибраться{}, // гнушаться прибраться в хлеву
rus_verbs:поглощаться{}, // поглощаться в металлической фольге
rus_verbs:ухать{}, // ухать в лесу
rus_verbs:подписываться{}, // подписываться в петиции
rus_verbs:покатать{}, // покатать в машинке
rus_verbs:излечиться{}, // излечиться в клинике
rus_verbs:трепыхаться{}, // трепыхаться в мешке
rus_verbs:кипятить{}, // кипятить в кастрюле
rus_verbs:понастроить{}, // понастроить в прибрежной зоне
rus_verbs:перебывать{}, // перебывать во всех европейских столицах
rus_verbs:оглашать{}, // оглашать в итоговой части
rus_verbs:преуспевать{}, // преуспевать в новом бизнесе
rus_verbs:консультироваться{}, // консультироваться в техподдержке
rus_verbs:накапливать{}, // накапливать в печени
rus_verbs:перемешать{}, // перемешать в контейнере
rus_verbs:наследить{}, // наследить в коридоре
rus_verbs:выявиться{}, // выявиться в результе
rus_verbs:забулькать{}, // забулькать в болоте
rus_verbs:отваривать{}, // отваривать в молоке
rus_verbs:запутываться{}, // запутываться в веревках
rus_verbs:нагреться{}, // нагреться в микроволновой печке
rus_verbs:рыбачить{}, // рыбачить в открытом море
rus_verbs:укорениться{}, // укорениться в сознании широких народных масс
rus_verbs:умывать{}, // умывать в тазике
rus_verbs:защекотать{}, // защекотать в носу
rus_verbs:заходиться{}, // заходиться в плаче
инфинитив:искупать{ вид:соверш }, инфинитив:искупать{ вид:несоверш }, // искупать в прохладной водичке
глагол:искупать{ вид:соверш }, глагол:искупать{ вид:несоверш },
деепричастие:искупав{}, деепричастие:искупая{},
rus_verbs:заморозить{}, // заморозить в холодильнике
rus_verbs:закреплять{}, // закреплять в металлическом держателе
rus_verbs:расхватать{}, // расхватать в магазине
rus_verbs:истязать{}, // истязать в тюремном подвале
rus_verbs:заржаветь{}, // заржаветь во влажной атмосфере
rus_verbs:обжаривать{}, // обжаривать в подсолнечном масле
rus_verbs:умереть{}, // Ты, подлый предатель, умрешь в нищете
rus_verbs:подогреть{}, // подогрей в микроволновке
rus_verbs:подогревать{},
rus_verbs:затянуть{}, // Кузнечики, сверчки, скрипачи и медведки затянули в траве свою трескучую музыку
rus_verbs:проделать{}, // проделать в стене дыру
инфинитив:жениться{ вид:соверш }, // жениться в Техасе
инфинитив:жениться{ вид:несоверш },
глагол:жениться{ вид:соверш },
глагол:жениться{ вид:несоверш },
деепричастие:женившись{},
деепричастие:женясь{},
прилагательное:женатый{},
прилагательное:женившийся{вид:соверш},
прилагательное:женящийся{},
rus_verbs:всхрапнуть{}, // всхрапнуть во сне
rus_verbs:всхрапывать{}, // всхрапывать во сне
rus_verbs:ворочаться{}, // Собака ворочается во сне
rus_verbs:воссоздаваться{}, // воссоздаваться в памяти
rus_verbs:акклиматизироваться{}, // альпинисты готовятся акклиматизироваться в горах
инфинитив:атаковать{ вид:несоверш }, // взвод был атакован в лесу
инфинитив:атаковать{ вид:соверш },
глагол:атаковать{ вид:несоверш },
глагол:атаковать{ вид:соверш },
прилагательное:атакованный{},
прилагательное:атаковавший{},
прилагательное:атакующий{},
инфинитив:аккумулировать{вид:несоверш}, // энергия была аккумулирована в печени
инфинитив:аккумулировать{вид:соверш},
глагол:аккумулировать{вид:несоверш},
глагол:аккумулировать{вид:соверш},
прилагательное:аккумулированный{},
прилагательное:аккумулирующий{},
//прилагательное:аккумулировавший{ вид:несоверш },
прилагательное:аккумулировавший{ вид:соверш },
rus_verbs:врисовывать{}, // врисовывать нового персонажа в анимацию
rus_verbs:вырасти{}, // Он вырос в глазах коллег.
rus_verbs:иметь{}, // Он всегда имел в резерве острое словцо.
rus_verbs:убить{}, // убить в себе зверя
инфинитив:абсорбироваться{ вид:соверш }, // жидкость абсорбируется в поглощающей ткани
инфинитив:абсорбироваться{ вид:несоверш },
глагол:абсорбироваться{ вид:соверш },
глагол:абсорбироваться{ вид:несоверш },
rus_verbs:поставить{}, // поставить в углу
rus_verbs:сжимать{}, // сжимать в кулаке
rus_verbs:готовиться{}, // альпинисты готовятся акклиматизироваться в горах
rus_verbs:аккумулироваться{}, // энергия аккумулируется в жировых отложениях
инфинитив:активизироваться{ вид:несоверш }, // в горах активизировались повстанцы
инфинитив:активизироваться{ вид:соверш },
глагол:активизироваться{ вид:несоверш },
глагол:активизироваться{ вид:соверш },
rus_verbs:апробировать{}, // пилот апробировал в ходе испытаний новый режим планера
rus_verbs:арестовать{}, // наркодилер был арестован в помещении кафе
rus_verbs:базировать{}, // установка будет базирована в лесу
rus_verbs:барахтаться{}, // дети барахтались в воде
rus_verbs:баррикадироваться{}, // преступники баррикадируются в помещении банка
rus_verbs:барствовать{}, // Семен Семенович барствовал в своей деревне
rus_verbs:бесчинствовать{}, // Боевики бесчинствовали в захваченном селе
rus_verbs:блаженствовать{}, // Воробьи блаженствовали в кроне рябины
rus_verbs:блуждать{}, // Туристы блуждали в лесу
rus_verbs:брать{}, // Жена берет деньги в тумбочке
rus_verbs:бродить{}, // парочки бродили в парке
rus_verbs:обойти{}, // Бразилия обошла Россию в рейтинге
rus_verbs:задержать{}, // Знаменитый советский фигурист задержан в США
rus_verbs:бултыхаться{}, // Ноги бултыхаются в воде
rus_verbs:вариться{}, // Курица варится в кастрюле
rus_verbs:закончиться{}, // Эта рецессия закончилась в 2003 году
rus_verbs:прокручиваться{}, // Ключ прокручивается в замке
rus_verbs:прокрутиться{}, // Ключ трижды прокрутился в замке
rus_verbs:храниться{}, // Настройки хранятся в текстовом файле
rus_verbs:сохраняться{}, // Настройки сохраняются в текстовом файле
rus_verbs:витать{}, // Мальчик витает в облаках
rus_verbs:владычествовать{}, // Король владычествует в стране
rus_verbs:властвовать{}, // Олигархи властвовали в стране
rus_verbs:возбудить{}, // возбудить в сердце тоску
rus_verbs:возбуждать{}, // возбуждать в сердце тоску
rus_verbs:возвыситься{}, // возвыситься в глазах современников
rus_verbs:возжечь{}, // возжечь в храме огонь
rus_verbs:возжечься{}, // Огонь возжёгся в храме
rus_verbs:возжигать{}, // возжигать в храме огонь
rus_verbs:возжигаться{}, // Огонь возжигается в храме
rus_verbs:вознамериваться{}, // вознамериваться уйти в монастырь
rus_verbs:вознамериться{}, // вознамериться уйти в монастырь
rus_verbs:возникать{}, // Новые идеи неожиданно возникают в колиной голове
rus_verbs:возникнуть{}, // Новые идейки возникли в голове
rus_verbs:возродиться{}, // возродиться в новом качестве
rus_verbs:возрождать{}, // возрождать в новом качестве
rus_verbs:возрождаться{}, // возрождаться в новом амплуа
rus_verbs:ворошить{}, // ворошить в камине кочергой золу
rus_verbs:воспевать{}, // Поэты воспевают героев в одах
rus_verbs:воспеваться{}, // Герои воспеваются в одах поэтами
rus_verbs:воспеть{}, // Поэты воспели в этой оде героев
rus_verbs:воспретить{}, // воспретить в помещении азартные игры
rus_verbs:восславить{}, // Поэты восславили в одах
rus_verbs:восславлять{}, // Поэты восславляют в одах
rus_verbs:восславляться{}, // Героя восславляются в одах
rus_verbs:воссоздать{}, // воссоздает в памяти образ человека
rus_verbs:воссоздавать{}, // воссоздать в памяти образ человека
rus_verbs:воссоздаться{}, // воссоздаться в памяти
rus_verbs:вскипятить{}, // вскипятить в чайнике воду
rus_verbs:вскипятиться{}, // вскипятиться в чайнике
rus_verbs:встретить{}, // встретить в классе старого приятеля
rus_verbs:встретиться{}, // встретиться в классе
rus_verbs:встречать{}, // встречать в лесу голодного медведя
rus_verbs:встречаться{}, // встречаться в кафе
rus_verbs:выбривать{}, // выбривать что-то в подмышках
rus_verbs:выбрить{}, // выбрить что-то в паху
rus_verbs:вывалять{}, // вывалять кого-то в грязи
rus_verbs:вываляться{}, // вываляться в грязи
rus_verbs:вываривать{}, // вываривать в молоке
rus_verbs:вывариваться{}, // вывариваться в молоке
rus_verbs:выварить{}, // выварить в молоке
rus_verbs:вывариться{}, // вывариться в молоке
rus_verbs:выгрызать{}, // выгрызать в сыре отверствие
rus_verbs:выгрызть{}, // выгрызть в сыре отверстие
rus_verbs:выгуливать{}, // выгуливать в парке собаку
rus_verbs:выгулять{}, // выгулять в парке собаку
rus_verbs:выдолбить{}, // выдолбить в стволе углубление
rus_verbs:выжить{}, // выжить в пустыне
rus_verbs:Выискать{}, // Выискать в программе ошибку
rus_verbs:выискаться{}, // Ошибка выискалась в программе
rus_verbs:выискивать{}, // выискивать в программе ошибку
rus_verbs:выискиваться{}, // выискиваться в программе
rus_verbs:выкраивать{}, // выкраивать в расписании время
rus_verbs:выкраиваться{}, // выкраиваться в расписании
инфинитив:выкупаться{aux stress="в^ыкупаться"}, // выкупаться в озере
глагол:выкупаться{вид:соверш},
rus_verbs:выловить{}, // выловить в пруду
rus_verbs:вымачивать{}, // вымачивать в молоке
rus_verbs:вымачиваться{}, // вымачиваться в молоке
rus_verbs:вынюхивать{}, // вынюхивать в траве следы
rus_verbs:выпачкать{}, // выпачкать в смоле свою одежду
rus_verbs:выпачкаться{}, // выпачкаться в грязи
rus_verbs:вырастить{}, // вырастить в теплице ведро огурчиков
rus_verbs:выращивать{}, // выращивать в теплице помидоры
rus_verbs:выращиваться{}, // выращиваться в теплице
rus_verbs:вырыть{}, // вырыть в земле глубокую яму
rus_verbs:высадить{}, // высадить в пустынной местности
rus_verbs:высадиться{}, // высадиться в пустынной местности
rus_verbs:высаживать{}, // высаживать в пустыне
rus_verbs:высверливать{}, // высверливать в доске отверствие
rus_verbs:высверливаться{}, // высверливаться в стене
rus_verbs:высверлить{}, // высверлить в стене отверствие
rus_verbs:высверлиться{}, // высверлиться в стене
rus_verbs:выскоблить{}, // выскоблить в столешнице канавку
rus_verbs:высматривать{}, // высматривать в темноте
rus_verbs:заметить{}, // заметить в помещении
rus_verbs:оказаться{}, // оказаться в первых рядах
rus_verbs:душить{}, // душить в объятиях
rus_verbs:оставаться{}, // оставаться в классе
rus_verbs:появиться{}, // впервые появиться в фильме
rus_verbs:лежать{}, // лежать в футляре
rus_verbs:раздаться{}, // раздаться в плечах
rus_verbs:ждать{}, // ждать в здании вокзала
rus_verbs:жить{}, // жить в трущобах
rus_verbs:постелить{}, // постелить в прихожей
rus_verbs:оказываться{}, // оказываться в неприятной ситуации
rus_verbs:держать{}, // держать в голове
rus_verbs:обнаружить{}, // обнаружить в себе способность
rus_verbs:начинать{}, // начинать в лаборатории
rus_verbs:рассказывать{}, // рассказывать в лицах
rus_verbs:ожидать{}, // ожидать в помещении
rus_verbs:продолжить{}, // продолжить в помещении
rus_verbs:состоять{}, // состоять в группе
rus_verbs:родиться{}, // родиться в рубашке
rus_verbs:искать{}, // искать в кармане
rus_verbs:иметься{}, // иметься в наличии
rus_verbs:говориться{}, // говориться в среде панков
rus_verbs:клясться{}, // клясться в верности
rus_verbs:узнавать{}, // узнавать в нем своего сына
rus_verbs:признаться{}, // признаться в ошибке
rus_verbs:сомневаться{}, // сомневаться в искренности
rus_verbs:толочь{}, // толочь в ступе
rus_verbs:понадобиться{}, // понадобиться в суде
rus_verbs:служить{}, // служить в пехоте
rus_verbs:потолочь{}, // потолочь в ступе
rus_verbs:появляться{}, // появляться в театре
rus_verbs:сжать{}, // сжать в объятиях
rus_verbs:действовать{}, // действовать в постановке
rus_verbs:селить{}, // селить в гостинице
rus_verbs:поймать{}, // поймать в лесу
rus_verbs:увидать{}, // увидать в толпе
rus_verbs:подождать{}, // подождать в кабинете
rus_verbs:прочесть{}, // прочесть в глазах
rus_verbs:тонуть{}, // тонуть в реке
rus_verbs:ощущать{}, // ощущать в животе
rus_verbs:ошибиться{}, // ошибиться в расчетах
rus_verbs:отметить{}, // отметить в списке
rus_verbs:показывать{}, // показывать в динамике
rus_verbs:скрыться{}, // скрыться в траве
rus_verbs:убедиться{}, // убедиться в корректности
rus_verbs:прозвучать{}, // прозвучать в наушниках
rus_verbs:разговаривать{}, // разговаривать в фойе
rus_verbs:издать{}, // издать в России
rus_verbs:прочитать{}, // прочитать в газете
rus_verbs:попробовать{}, // попробовать в деле
rus_verbs:замечать{}, // замечать в программе ошибку
rus_verbs:нести{}, // нести в руках
rus_verbs:пропасть{}, // пропасть в плену
rus_verbs:носить{}, // носить в кармане
rus_verbs:гореть{}, // гореть в аду
rus_verbs:поправить{}, // поправить в программе
rus_verbs:застыть{}, // застыть в неудобной позе
rus_verbs:получать{}, // получать в кассе
rus_verbs:потребоваться{}, // потребоваться в работе
rus_verbs:спрятать{}, // спрятать в шкафу
rus_verbs:учиться{}, // учиться в институте
rus_verbs:развернуться{}, // развернуться в коридоре
rus_verbs:подозревать{}, // подозревать в мошенничестве
rus_verbs:играть{}, // играть в команде
rus_verbs:сыграть{}, // сыграть в команде
rus_verbs:строить{}, // строить в деревне
rus_verbs:устроить{}, // устроить в доме вечеринку
rus_verbs:находить{}, // находить в лесу
rus_verbs:нуждаться{}, // нуждаться в деньгах
rus_verbs:испытать{}, // испытать в рабочей обстановке
rus_verbs:мелькнуть{}, // мелькнуть в прицеле
rus_verbs:очутиться{}, // очутиться в закрытом помещении
инфинитив:использовать{вид:соверш}, // использовать в работе
инфинитив:использовать{вид:несоверш},
глагол:использовать{вид:несоверш},
глагол:использовать{вид:соверш},
rus_verbs:лететь{}, // лететь в самолете
rus_verbs:смеяться{}, // смеяться в цирке
rus_verbs:ездить{}, // ездить в лимузине
rus_verbs:заснуть{}, // заснуть в неудобной позе
rus_verbs:застать{}, // застать в неформальной обстановке
rus_verbs:очнуться{}, // очнуться в незнакомой обстановке
rus_verbs:твориться{}, // Что творится в закрытой зоне
rus_verbs:разглядеть{}, // разглядеть в темноте
rus_verbs:изучать{}, // изучать в естественных условиях
rus_verbs:удержаться{}, // удержаться в седле
rus_verbs:побывать{}, // побывать в зоопарке
rus_verbs:уловить{}, // уловить в словах нотку отчаяния
rus_verbs:приобрести{}, // приобрести в лавке
rus_verbs:исчезать{}, // исчезать в тумане
rus_verbs:уверять{}, // уверять в своей невиновности
rus_verbs:продолжаться{}, // продолжаться в воздухе
rus_verbs:открывать{}, // открывать в городе новый стадион
rus_verbs:поддержать{}, // поддержать в парке порядок
rus_verbs:солить{}, // солить в бочке
rus_verbs:прожить{}, // прожить в деревне
rus_verbs:создавать{}, // создавать в театре
rus_verbs:обсуждать{}, // обсуждать в коллективе
rus_verbs:заказать{}, // заказать в магазине
rus_verbs:отыскать{}, // отыскать в гараже
rus_verbs:уснуть{}, // уснуть в кресле
rus_verbs:задержаться{}, // задержаться в театре
rus_verbs:подобрать{}, // подобрать в коллекции
rus_verbs:пробовать{}, // пробовать в работе
rus_verbs:курить{}, // курить в закрытом помещении
rus_verbs:устраивать{}, // устраивать в лесу засаду
rus_verbs:установить{}, // установить в багажнике
rus_verbs:запереть{}, // запереть в сарае
rus_verbs:содержать{}, // содержать в достатке
rus_verbs:синеть{}, // синеть в кислородной атмосфере
rus_verbs:слышаться{}, // слышаться в голосе
rus_verbs:закрыться{}, // закрыться в здании
rus_verbs:скрываться{}, // скрываться в квартире
rus_verbs:родить{}, // родить в больнице
rus_verbs:описать{}, // описать в заметках
rus_verbs:перехватить{}, // перехватить в коридоре
rus_verbs:менять{}, // менять в магазине
rus_verbs:скрывать{}, // скрывать в чужой квартире
rus_verbs:стиснуть{}, // стиснуть в стальных объятиях
rus_verbs:останавливаться{}, // останавливаться в гостинице
rus_verbs:мелькать{}, // мелькать в телевизоре
rus_verbs:присутствовать{}, // присутствовать в аудитории
rus_verbs:украсть{}, // украсть в магазине
rus_verbs:победить{}, // победить в войне
rus_verbs:расположиться{}, // расположиться в гостинице
rus_verbs:упомянуть{}, // упомянуть в своей книге
rus_verbs:плыть{}, // плыть в старой бочке
rus_verbs:нащупать{}, // нащупать в глубине
rus_verbs:проявляться{}, // проявляться в работе
rus_verbs:затихнуть{}, // затихнуть в норе
rus_verbs:построить{}, // построить в гараже
rus_verbs:поддерживать{}, // поддерживать в исправном состоянии
rus_verbs:заработать{}, // заработать в стартапе
rus_verbs:сломать{}, // сломать в суставе
rus_verbs:снимать{}, // снимать в гардеробе
rus_verbs:сохранить{}, // сохранить в коллекции
rus_verbs:располагаться{}, // располагаться в отдельном кабинете
rus_verbs:сражаться{}, // сражаться в честном бою
rus_verbs:спускаться{}, // спускаться в батискафе
rus_verbs:уничтожить{}, // уничтожить в схроне
rus_verbs:изучить{}, // изучить в естественных условиях
rus_verbs:рождаться{}, // рождаться в муках
rus_verbs:пребывать{}, // пребывать в прострации
rus_verbs:прилететь{}, // прилететь в аэробусе
rus_verbs:догнать{}, // догнать в переулке
rus_verbs:изобразить{}, // изобразить в танце
rus_verbs:проехать{}, // проехать в легковушке
rus_verbs:убедить{}, // убедить в разумности
rus_verbs:приготовить{}, // приготовить в духовке
rus_verbs:собирать{}, // собирать в лесу
rus_verbs:поплыть{}, // поплыть в катере
rus_verbs:доверять{}, // доверять в управлении
rus_verbs:разобраться{}, // разобраться в законах
rus_verbs:ловить{}, // ловить в озере
rus_verbs:проесть{}, // проесть в куске металла отверстие
rus_verbs:спрятаться{}, // спрятаться в подвале
rus_verbs:провозгласить{}, // провозгласить в речи
rus_verbs:изложить{}, // изложить в своём выступлении
rus_verbs:замяться{}, // замяться в коридоре
rus_verbs:раздаваться{}, // Крик ягуара раздается в джунглях
rus_verbs:доказать{}, // Автор доказал в своей работе, что теорема верна
rus_verbs:хранить{}, // хранить в шкатулке
rus_verbs:шутить{}, // шутить в классе
глагол:рассыпаться{ aux stress="рассып^аться" }, // рассыпаться в извинениях
инфинитив:рассыпаться{ aux stress="рассып^аться" },
rus_verbs:чертить{}, // чертить в тетрадке
rus_verbs:отразиться{}, // отразиться в аттестате
rus_verbs:греть{}, // греть в микроволновке
rus_verbs:зарычать{}, // Кто-то зарычал в глубине леса
rus_verbs:рассуждать{}, // Автор рассуждает в своей статье
rus_verbs:освободить{}, // Обвиняемые были освобождены в зале суда
rus_verbs:окружать{}, // окружать в лесу
rus_verbs:сопровождать{}, // сопровождать в операции
rus_verbs:заканчиваться{}, // заканчиваться в дороге
rus_verbs:поселиться{}, // поселиться в загородном доме
rus_verbs:охватывать{}, // охватывать в хронологии
rus_verbs:запеть{}, // запеть в кино
инфинитив:провозить{вид:несоверш}, // провозить в багаже
глагол:провозить{вид:несоверш},
rus_verbs:мочить{}, // мочить в сортире
rus_verbs:перевернуться{}, // перевернуться в полёте
rus_verbs:улететь{}, // улететь в теплые края
rus_verbs:сдержать{}, // сдержать в руках
rus_verbs:преследовать{}, // преследовать в любой другой стране
rus_verbs:драться{}, // драться в баре
rus_verbs:просидеть{}, // просидеть в классе
rus_verbs:убираться{}, // убираться в квартире
rus_verbs:содрогнуться{}, // содрогнуться в приступе отвращения
rus_verbs:пугать{}, // пугать в прессе
rus_verbs:отреагировать{}, // отреагировать в прессе
rus_verbs:проверять{}, // проверять в аппарате
rus_verbs:убеждать{}, // убеждать в отсутствии альтернатив
rus_verbs:летать{}, // летать в комфортабельном частном самолёте
rus_verbs:толпиться{}, // толпиться в фойе
rus_verbs:плавать{}, // плавать в специальном костюме
rus_verbs:пробыть{}, // пробыть в воде слишком долго
rus_verbs:прикинуть{}, // прикинуть в уме
rus_verbs:застрять{}, // застрять в лифте
rus_verbs:метаться{}, // метаться в кровате
rus_verbs:сжечь{}, // сжечь в печке
rus_verbs:расслабиться{}, // расслабиться в ванной
rus_verbs:услыхать{}, // услыхать в автобусе
rus_verbs:удержать{}, // удержать в вертикальном положении
rus_verbs:образоваться{}, // образоваться в верхних слоях атмосферы
rus_verbs:рассмотреть{}, // рассмотреть в капле воды
rus_verbs:просмотреть{}, // просмотреть в браузере
rus_verbs:учесть{}, // учесть в планах
rus_verbs:уезжать{}, // уезжать в чьей-то машине
rus_verbs:похоронить{}, // похоронить в мерзлой земле
rus_verbs:растянуться{}, // растянуться в расслабленной позе
rus_verbs:обнаружиться{}, // обнаружиться в чужой сумке
rus_verbs:гулять{}, // гулять в парке
rus_verbs:утонуть{}, // утонуть в реке
rus_verbs:зажать{}, // зажать в медвежьих объятиях
rus_verbs:усомниться{}, // усомниться в объективности
rus_verbs:танцевать{}, // танцевать в спортзале
rus_verbs:проноситься{}, // проноситься в голове
rus_verbs:трудиться{}, // трудиться в кооперативе
глагол:засыпать{ aux stress="засып^ать" переходность:непереходный }, // засыпать в спальном мешке
инфинитив:засыпать{ aux stress="засып^ать" переходность:непереходный },
rus_verbs:сушить{}, // сушить в сушильном шкафу
rus_verbs:зашевелиться{}, // зашевелиться в траве
rus_verbs:обдумывать{}, // обдумывать в спокойной обстановке
rus_verbs:промелькнуть{}, // промелькнуть в окне
rus_verbs:поучаствовать{}, // поучаствовать в обсуждении
rus_verbs:закрыть{}, // закрыть в комнате
rus_verbs:запирать{}, // запирать в комнате
rus_verbs:закрывать{}, // закрывать в доме
rus_verbs:заблокировать{}, // заблокировать в доме
rus_verbs:зацвести{}, // В садах зацвела сирень
rus_verbs:кричать{}, // Какое-то животное кричало в ночном лесу.
rus_verbs:поглотить{}, // фотон, поглощенный в рецепторе
rus_verbs:стоять{}, // войска, стоявшие в Риме
rus_verbs:закалить{}, // ветераны, закаленные в боях
rus_verbs:выступать{}, // пришлось выступать в тюрьме.
rus_verbs:выступить{}, // пришлось выступить в тюрьме.
rus_verbs:закопошиться{}, // Мыши закопошились в траве
rus_verbs:воспламениться{}, // смесь, воспламенившаяся в цилиндре
rus_verbs:воспламеняться{}, // смесь, воспламеняющаяся в цилиндре
rus_verbs:закрываться{}, // закрываться в комнате
rus_verbs:провалиться{}, // провалиться в прокате
деепричастие:авторизируясь{ вид:несоверш },
глагол:авторизироваться{ вид:несоверш },
инфинитив:авторизироваться{ вид:несоверш }, // авторизироваться в системе
rus_verbs:существовать{}, // существовать в вакууме
деепричастие:находясь{},
прилагательное:находившийся{},
прилагательное:находящийся{},
глагол:находиться{ вид:несоверш },
инфинитив:находиться{ вид:несоверш }, // находиться в вакууме
rus_verbs:регистрировать{}, // регистрировать в инспекции
глагол:перерегистрировать{ вид:несоверш }, глагол:перерегистрировать{ вид:соверш },
инфинитив:перерегистрировать{ вид:несоверш }, инфинитив:перерегистрировать{ вид:соверш }, // перерегистрировать в инспекции
rus_verbs:поковыряться{}, // поковыряться в носу
rus_verbs:оттаять{}, // оттаять в кипятке
rus_verbs:распинаться{}, // распинаться в проклятиях
rus_verbs:отменить{}, // Министерство связи предлагает отменить внутренний роуминг в России
rus_verbs:столкнуться{}, // Американский эсминец и японский танкер столкнулись в Персидском заливе
rus_verbs:ценить{}, // Он очень ценил в статьях краткость изложения.
прилагательное:несчастный{}, // Он очень несчастен в семейной жизни.
rus_verbs:объясниться{}, // Он объяснился в любви.
прилагательное:нетвердый{}, // Он нетвёрд в истории.
rus_verbs:заниматься{}, // Он занимается в читальном зале.
rus_verbs:вращаться{}, // Он вращается в учёных кругах.
прилагательное:спокойный{}, // Он был спокоен и уверен в завтрашнем дне.
rus_verbs:бегать{}, // Он бегал по городу в поисках квартиры.
rus_verbs:заключать{}, // Письмо заключало в себе очень важные сведения.
rus_verbs:срабатывать{}, // Алгоритм срабатывает в половине случаев.
rus_verbs:специализироваться{}, // мы специализируемся в создании ядерного оружия
rus_verbs:сравниться{}, // Никто не может сравниться с ним в знаниях.
rus_verbs:продолжать{}, // Продолжайте в том же духе.
rus_verbs:говорить{}, // Не говорите об этом в присутствии третьих лиц.
rus_verbs:болтать{}, // Не болтай в присутствии начальника!
rus_verbs:проболтаться{}, // Не проболтайся в присутствии начальника!
rus_verbs:повторить{}, // Он должен повторить свои показания в присутствии свидетелей
rus_verbs:получить{}, // ректор поздравил студентов, получивших в этом семестре повышенную стипендию
rus_verbs:приобретать{}, // Эту еду мы приобретаем в соседнем магазине.
rus_verbs:расходиться{}, // Маша и Петя расходятся во взглядах
rus_verbs:сходиться{}, // Все дороги сходятся в Москве
rus_verbs:убирать{}, // убирать в комнате
rus_verbs:удостоверяться{}, // он удостоверяется в личности специалиста
rus_verbs:уединяться{}, // уединяться в пустыне
rus_verbs:уживаться{}, // уживаться в одном коллективе
rus_verbs:укорять{}, // укорять друга в забывчивости
rus_verbs:читать{}, // он читал об этом в журнале
rus_verbs:состояться{}, // В Израиле состоятся досрочные парламентские выборы
rus_verbs:погибнуть{}, // Список погибших в авиакатастрофе под Ярославлем
rus_verbs:работать{}, // Я работаю в театре.
rus_verbs:признать{}, // Я признал в нём старого друга.
rus_verbs:преподавать{}, // Я преподаю в университете.
rus_verbs:понимать{}, // Я плохо понимаю в живописи.
rus_verbs:водиться{}, // неизвестный науке зверь, который водится в жарких тропических лесах
rus_verbs:разразиться{}, // В Москве разразилась эпидемия гриппа
rus_verbs:замереть{}, // вся толпа замерла в восхищении
rus_verbs:сидеть{}, // Я люблю сидеть в этом удобном кресле.
rus_verbs:идти{}, // Я иду в неопределённом направлении.
rus_verbs:заболеть{}, // Я заболел в дороге.
rus_verbs:ехать{}, // Я еду в автобусе
rus_verbs:взять{}, // Я взял книгу в библиотеке на неделю.
rus_verbs:провести{}, // Юные годы он провёл в Италии.
rus_verbs:вставать{}, // Этот случай живо встаёт в моей памяти.
rus_verbs:возвысить{}, // Это событие возвысило его в общественном мнении.
rus_verbs:произойти{}, // Это произошло в одном городе в Японии.
rus_verbs:привидеться{}, // Это мне привиделось во сне.
rus_verbs:держаться{}, // Это дело держится в большом секрете.
rus_verbs:привиться{}, // Это выражение не привилось в русском языке.
rus_verbs:восстановиться{}, // Эти писатели восстановились в правах.
rus_verbs:быть{}, // Эта книга есть в любом книжном магазине.
прилагательное:популярный{}, // Эта идея очень популярна в массах.
rus_verbs:шуметь{}, // Шумит в голове.
rus_verbs:остаться{}, // Шляпа осталась в поезде.
rus_verbs:выражаться{}, // Характер писателя лучше всего выражается в его произведениях.
rus_verbs:воспитать{}, // Учительница воспитала в детях любовь к природе.
rus_verbs:пересохнуть{}, // У меня в горле пересохло.
rus_verbs:щекотать{}, // У меня в горле щекочет.
rus_verbs:колоть{}, // У меня в боку колет.
прилагательное:свежий{}, // Событие ещё свежо в памяти.
rus_verbs:собрать{}, // Соберите всех учеников во дворе.
rus_verbs:белеть{}, // Снег белеет в горах.
rus_verbs:сделать{}, // Сколько орфографических ошибок ты сделал в диктанте?
rus_verbs:таять{}, // Сахар тает в кипятке.
rus_verbs:жать{}, // Сапог жмёт в подъёме.
rus_verbs:возиться{}, // Ребята возятся в углу.
rus_verbs:распоряжаться{}, // Прошу не распоряжаться в чужом доме.
rus_verbs:кружиться{}, // Они кружились в вальсе.
rus_verbs:выставлять{}, // Они выставляют его в смешном виде.
rus_verbs:бывать{}, // Она часто бывает в обществе.
rus_verbs:петь{}, // Она поёт в опере.
rus_verbs:сойтись{}, // Все свидетели сошлись в своих показаниях.
rus_verbs:валяться{}, // Вещи валялись в беспорядке.
rus_verbs:пройти{}, // Весь день прошёл в беготне.
rus_verbs:продавать{}, // В этом магазине продают обувь.
rus_verbs:заключаться{}, // В этом заключается вся сущность.
rus_verbs:звенеть{}, // В ушах звенит.
rus_verbs:проступить{}, // В тумане проступили очертания корабля.
rus_verbs:бить{}, // В саду бьёт фонтан.
rus_verbs:проскользнуть{}, // В речи проскользнул упрёк.
rus_verbs:оставить{}, // Не оставь товарища в опасности.
rus_verbs:прогулять{}, // Мы прогуляли час в парке.
rus_verbs:перебить{}, // Мы перебили врагов в бою.
rus_verbs:остановиться{}, // Мы остановились в первой попавшейся гостинице.
rus_verbs:видеть{}, // Он многое видел в жизни.
// глагол:проходить{ вид:несоверш }, // Беседа проходила в дружественной атмосфере.
rus_verbs:подать{}, // Автор подал своих героев в реалистических тонах.
rus_verbs:кинуть{}, // Он кинул меня в беде.
rus_verbs:приходить{}, // Приходи в сентябре
rus_verbs:воскрешать{}, // воскрешать в памяти
rus_verbs:соединять{}, // соединять в себе
rus_verbs:разбираться{}, // умение разбираться в вещах
rus_verbs:делать{}, // В её комнате делали обыск.
rus_verbs:воцариться{}, // В зале воцарилась глубокая тишина.
rus_verbs:начаться{}, // В деревне начались полевые работы.
rus_verbs:блеснуть{}, // В голове блеснула хорошая мысль.
rus_verbs:вертеться{}, // В голове вертится вчерашний разговор.
rus_verbs:веять{}, // В воздухе веет прохладой.
rus_verbs:висеть{}, // В воздухе висит зной.
rus_verbs:носиться{}, // В воздухе носятся комары.
rus_verbs:грести{}, // Грести в спокойной воде будет немного легче, но скучнее
rus_verbs:воскресить{}, // воскресить в памяти
rus_verbs:поплавать{}, // поплавать в 100-метровом бассейне
rus_verbs:пострадать{}, // В массовой драке пострадал 23-летний мужчина
прилагательное:уверенный{ причастие }, // Она уверена в своих силах.
прилагательное:постоянный{}, // Она постоянна во вкусах.
прилагательное:сильный{}, // Он не силён в математике.
прилагательное:повинный{}, // Он не повинен в этом.
прилагательное:возможный{}, // Ураганы, сильные грозы и даже смерчи возможны в конце периода сильной жары
rus_verbs:вывести{}, // способный летать над землей крокодил был выведен в секретной лаборатории
прилагательное:нужный{}, // сковородка тоже нужна в хозяйстве.
rus_verbs:сесть{}, // Она села в тени
rus_verbs:заливаться{}, // в нашем парке заливаются соловьи
rus_verbs:разнести{}, // В лесу огонь пожара мгновенно разнесло
rus_verbs:чувствоваться{}, // В тёплом, но сыром воздухе остро чувствовалось дыхание осени
// rus_verbs:расти{}, // дерево, растущее в лесу
rus_verbs:происходить{}, // что происходит в поликлиннике
rus_verbs:спать{}, // кто спит в моей кровати
rus_verbs:мыть{}, // мыть машину в саду
ГЛ_ИНФ(царить), // В воздухе царило безмолвие
ГЛ_ИНФ(мести), // мести в прихожей пол
ГЛ_ИНФ(прятать), // прятать в яме
ГЛ_ИНФ(увидеть), прилагательное:увидевший{}, деепричастие:увидев{}, // увидел периодическую таблицу элементов во сне.
// ГЛ_ИНФ(собраться), // собраться в порту
ГЛ_ИНФ(случиться), // что-то случилось в больнице
ГЛ_ИНФ(зажечься), // в небе зажглись звёзды
ГЛ_ИНФ(купить), // купи молока в магазине
прилагательное:пропагандировавшийся{} // группа студентов университета дружбы народов, активно пропагандировавшейся в СССР
}
// Чтобы разрешить связывание в паттернах типа: пообедать в macdonalds
fact гл_предл
{
if context { Гл_В_Предл предлог:в{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_В_Предл предлог:в{} *:*{ падеж:предл } }
then return true
}
// С локативом:
// собраться в порту
fact гл_предл
{
if context { Гл_В_Предл предлог:в{} существительное:*{ падеж:мест } }
then return true
}
#endregion Предложный
#region Винительный
// Для глаголов движения с выраженным направлением действия может присоединяться
// предложный паттерн с винительным падежом.
wordentry_set Гл_В_Вин =
{
rus_verbs:вдавиться{}, // Дуло больно вдавилось в позвонок.
глагол:ввергнуть{}, // Двух прелестнейших дам он ввергнул в горе.
глагол:ввергать{},
инфинитив:ввергнуть{},
инфинитив:ввергать{},
rus_verbs:двинуться{}, // Двинулись в путь и мы.
rus_verbs:сплавать{}, // Сплавать в Россию!
rus_verbs:уложиться{}, // Уложиться в воскресенье.
rus_verbs:спешить{}, // Спешите в Лондон
rus_verbs:кинуть{}, // Киньте в море.
rus_verbs:проситься{}, // Просилась в Никарагуа.
rus_verbs:притопать{}, // Притопал в Будапешт.
rus_verbs:скататься{}, // Скатался в Красноярск.
rus_verbs:соскользнуть{}, // Соскользнул в пике.
rus_verbs:соскальзывать{},
rus_verbs:играть{}, // Играл в дутье.
глагол:айда{}, // Айда в каморы.
rus_verbs:отзывать{}, // Отзывали в Москву...
rus_verbs:сообщаться{}, // Сообщается в Лондон.
rus_verbs:вдуматься{}, // Вдумайтесь в них.
rus_verbs:проехать{}, // Проехать в Лунево...
rus_verbs:спрыгивать{}, // Спрыгиваем в него.
rus_verbs:верить{}, // Верю в вас!
rus_verbs:прибыть{}, // Прибыл в Подмосковье.
rus_verbs:переходить{}, // Переходите в школу.
rus_verbs:доложить{}, // Доложили в Москву.
rus_verbs:подаваться{}, // Подаваться в Россию?
rus_verbs:спрыгнуть{}, // Спрыгнул в него.
rus_verbs:вывезти{}, // Вывезли в Китай.
rus_verbs:пропихивать{}, // Я очень аккуратно пропихивал дуло в ноздрю.
rus_verbs:пропихнуть{},
rus_verbs:транспортироваться{},
rus_verbs:закрадываться{}, // в голову начали закрадываться кое-какие сомнения и подозрения
rus_verbs:дуть{},
rus_verbs:БОГАТЕТЬ{}, //
rus_verbs:РАЗБОГАТЕТЬ{}, //
rus_verbs:ВОЗРАСТАТЬ{}, //
rus_verbs:ВОЗРАСТИ{}, //
rus_verbs:ПОДНЯТЬ{}, // Он поднял половинку самолета в воздух и на всей скорости повел ее к горам. (ПОДНЯТЬ)
rus_verbs:ОТКАТИТЬСЯ{}, // Услышав за спиной дыхание, он прыгнул вперед и откатился в сторону, рассчитывая ускользнуть от врага, нападавшего сзади (ОТКАТИТЬСЯ)
rus_verbs:ВПЛЕТАТЬСЯ{}, // В общий смрад вплеталось зловонье пены, летевшей из пастей, и крови из легких (ВПЛЕТАТЬСЯ)
rus_verbs:ЗАМАНИТЬ{}, // Они подумали, что Павел пытается заманить их в зону обстрела. (ЗАМАНИТЬ,ЗАМАНИВАТЬ)
rus_verbs:ЗАМАНИВАТЬ{},
rus_verbs:ПРОТРУБИТЬ{}, // Эти врата откроются, когда он протрубит в рог, и пропустят его в другую вселенную. (ПРОТРУБИТЬ)
rus_verbs:ВРУБИТЬСЯ{}, // Клинок сломался, не врубившись в металл. (ВРУБИТЬСЯ/ВРУБАТЬСЯ)
rus_verbs:ВРУБАТЬСЯ{},
rus_verbs:ОТПРАВИТЬ{}, // Мы ищем благородного вельможу, который нанял бы нас или отправил в рыцарский поиск. (ОТПРАВИТЬ)
rus_verbs:ОБЛАЧИТЬ{}, // Этот был облачен в сверкавшие красные доспехи с опущенным забралом и держал огромное копье, дожидаясь своей очереди. (ОБЛАЧИТЬ/ОБЛАЧАТЬ/ОБЛАЧИТЬСЯ/ОБЛАЧАТЬСЯ/НАРЯДИТЬСЯ/НАРЯЖАТЬСЯ)
rus_verbs:ОБЛАЧАТЬ{},
rus_verbs:ОБЛАЧИТЬСЯ{},
rus_verbs:ОБЛАЧАТЬСЯ{},
rus_verbs:НАРЯДИТЬСЯ{},
rus_verbs:НАРЯЖАТЬСЯ{},
rus_verbs:ЗАХВАТИТЬ{}, // Кроме набранного рабского материала обычного типа, он захватил в плен группу очень странных созданий, а также женщину исключительной красоты (ЗАХВАТИТЬ/ЗАХВАТЫВАТЬ/ЗАХВАТ)
rus_verbs:ЗАХВАТЫВАТЬ{},
rus_verbs:ПРОВЕСТИ{}, // Он провел их в маленькое святилище позади штурвала. (ПРОВЕСТИ)
rus_verbs:ПОЙМАТЬ{}, // Их можно поймать в ловушку (ПОЙМАТЬ)
rus_verbs:СТРОИТЬСЯ{}, // На вершине они остановились, строясь в круг. (СТРОИТЬСЯ,ПОСТРОИТЬСЯ,ВЫСТРОИТЬСЯ)
rus_verbs:ПОСТРОИТЬСЯ{},
rus_verbs:ВЫСТРОИТЬСЯ{},
rus_verbs:ВЫПУСТИТЬ{}, // Несколько стрел, выпущенных в преследуемых, вонзились в траву (ВЫПУСТИТЬ/ВЫПУСКАТЬ)
rus_verbs:ВЫПУСКАТЬ{},
rus_verbs:ВЦЕПЛЯТЬСЯ{}, // Они вцепляются тебе в горло. (ВЦЕПЛЯТЬСЯ/ВЦЕПИТЬСЯ)
rus_verbs:ВЦЕПИТЬСЯ{},
rus_verbs:ПАЛЬНУТЬ{}, // Вольф вставил в тетиву новую стрелу и пальнул в белое брюхо (ПАЛЬНУТЬ)
rus_verbs:ОТСТУПИТЬ{}, // Вольф отступил в щель. (ОТСТУПИТЬ/ОТСТУПАТЬ)
rus_verbs:ОТСТУПАТЬ{},
rus_verbs:КРИКНУТЬ{}, // Вольф крикнул в ответ и медленно отступил от птицы. (КРИКНУТЬ)
rus_verbs:ДЫХНУТЬ{}, // В лицо ему дыхнули винным перегаром. (ДЫХНУТЬ)
rus_verbs:ПОТРУБИТЬ{}, // Я видел рог во время своих скитаний по дворцу и даже потрубил в него (ПОТРУБИТЬ)
rus_verbs:ОТКРЫВАТЬСЯ{}, // Некоторые врата открывались в другие вселенные (ОТКРЫВАТЬСЯ)
rus_verbs:ТРУБИТЬ{}, // А я трубил в рог (ТРУБИТЬ)
rus_verbs:ПЫРНУТЬ{}, // Вольф пырнул его в бок. (ПЫРНУТЬ)
rus_verbs:ПРОСКРЕЖЕТАТЬ{}, // Тот что-то проскрежетал в ответ, а затем наорал на него. (ПРОСКРЕЖЕТАТЬ В вин, НАОРАТЬ НА вин)
rus_verbs:ИМПОРТИРОВАТЬ{}, // импортировать товары двойного применения только в Российскую Федерацию (ИМПОРТИРОВАТЬ)
rus_verbs:ОТЪЕХАТЬ{}, // Легкий грохот катков заглушил рог, когда дверь отъехала в сторону. (ОТЪЕХАТЬ)
rus_verbs:ПОПЛЕСТИСЬ{}, // Подобрав нижнее белье, носки и ботинки, он поплелся по песку обратно в джунгли. (ПОПЛЕЛСЯ)
rus_verbs:СЖАТЬСЯ{}, // Желудок у него сжался в кулак. (СЖАТЬСЯ, СЖИМАТЬСЯ)
rus_verbs:СЖИМАТЬСЯ{},
rus_verbs:проверять{}, // Школьников будут принудительно проверять на курение
rus_verbs:ПОТЯНУТЬ{}, // Я потянул его в кино (ПОТЯНУТЬ)
rus_verbs:ПЕРЕВЕСТИ{}, // Премьер-министр Казахстана поручил до конца года перевести все социально-значимые услуги в электронный вид (ПЕРЕВЕСТИ)
rus_verbs:КРАСИТЬ{}, // Почему китайские партийные боссы красят волосы в черный цвет? (КРАСИТЬ/ПОКРАСИТЬ/ПЕРЕКРАСИТЬ/ОКРАСИТЬ/ЗАКРАСИТЬ)
rus_verbs:ПОКРАСИТЬ{}, //
rus_verbs:ПЕРЕКРАСИТЬ{}, //
rus_verbs:ОКРАСИТЬ{}, //
rus_verbs:ЗАКРАСИТЬ{}, //
rus_verbs:СООБЩИТЬ{}, // Мужчина ранил человека в щеку и сам сообщил об этом в полицию (СООБЩИТЬ)
rus_verbs:СТЯГИВАТЬ{}, // Но толщина пузыря постоянно меняется из-за гравитации, которая стягивает жидкость в нижнюю часть (СТЯГИВАТЬ/СТЯНУТЬ/ЗАТЯНУТЬ/ВТЯНУТЬ)
rus_verbs:СТЯНУТЬ{}, //
rus_verbs:ЗАТЯНУТЬ{}, //
rus_verbs:ВТЯНУТЬ{}, //
rus_verbs:СОХРАНИТЬ{}, // сохранить данные в файл (СОХРАНИТЬ)
деепричастие:придя{}, // Немного придя в себя
rus_verbs:наблюдать{}, // Судья , долго наблюдавший в трубу , вдруг вскричал
rus_verbs:УЛЫБАТЬСЯ{}, // она улыбалась во весь рот (УЛЫБАТЬСЯ)
rus_verbs:МЕТНУТЬСЯ{}, // она метнулась обратно во тьму (МЕТНУТЬСЯ)
rus_verbs:ПОСЛЕДОВАТЬ{}, // большинство жителей города последовало за ним во дворец (ПОСЛЕДОВАТЬ)
rus_verbs:ПЕРЕМЕЩАТЬСЯ{}, // экстремисты перемещаются из лесов в Сеть (ПЕРЕМЕЩАТЬСЯ)
rus_verbs:ВЫТАЩИТЬ{}, // Алексей позволил вытащить себя через дверь во тьму (ВЫТАЩИТЬ)
rus_verbs:СЫПАТЬСЯ{}, // внизу под ними камни градом сыпались во двор (СЫПАТЬСЯ)
rus_verbs:выезжать{}, // заключенные сами шьют куклы и иногда выезжают с представлениями в детский дом неподалеку
rus_verbs:КРИЧАТЬ{}, // ей хотелось кричать во весь голос (КРИЧАТЬ В вин)
rus_verbs:ВЫПРЯМИТЬСЯ{}, // волк выпрямился во весь огромный рост (ВЫПРЯМИТЬСЯ В вин)
rus_verbs:спрятать{}, // Джон спрятал очки во внутренний карман (спрятать в вин)
rus_verbs:ЭКСТРАДИРОВАТЬ{}, // Украина экстрадирует в Таджикистан задержанного бывшего премьер-министра (ЭКСТРАДИРОВАТЬ В вин)
rus_verbs:ВВОЗИТЬ{}, // лабораторный мониторинг ввозимой в Россию мясной продукции из США (ВВОЗИТЬ В вин)
rus_verbs:УПАКОВАТЬ{}, // упакованных в несколько слоев полиэтилена (УПАКОВАТЬ В вин)
rus_verbs:ОТТЯГИВАТЬ{}, // использовать естественную силу гравитации, оттягивая объекты в сторону и изменяя их орбиту (ОТТЯГИВАТЬ В вин)
rus_verbs:ПОЗВОНИТЬ{}, // они позвонили в отдел экологии городской администрации (ПОЗВОНИТЬ В)
rus_verbs:ПРИВЛЕЧЬ{}, // Открытость данных о лесе поможет привлечь инвестиции в отрасль (ПРИВЛЕЧЬ В)
rus_verbs:ЗАПРОСИТЬСЯ{}, // набегавшись и наплясавшись, Стасик утомился и запросился в кроватку (ЗАПРОСИТЬСЯ В)
rus_verbs:ОТСТАВИТЬ{}, // бутыль с ацетоном Витька отставил в сторонку (ОТСТАВИТЬ В)
rus_verbs:ИСПОЛЬЗОВАТЬ{}, // ты использовал свою магию во зло. (ИСПОЛЬЗОВАТЬ В вин)
rus_verbs:ВЫСЕВАТЬ{}, // В апреле редис возможно уже высевать в грунт (ВЫСЕВАТЬ В)
rus_verbs:ЗАГНАТЬ{}, // Американский психолог загнал любовь в три угла (ЗАГНАТЬ В)
rus_verbs:ЭВОЛЮЦИОНИРОВАТЬ{}, // Почему не все обезьяны эволюционировали в человека? (ЭВОЛЮЦИОНИРОВАТЬ В вин)
rus_verbs:СФОТОГРАФИРОВАТЬСЯ{}, // Он сфотографировался во весь рост. (СФОТОГРАФИРОВАТЬСЯ В)
rus_verbs:СТАВИТЬ{}, // Он ставит мне в упрёк свою ошибку. (СТАВИТЬ В)
rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА)
rus_verbs:ПЕРЕСЕЛЯТЬСЯ{}, // Греки переселяются в Германию (ПЕРЕСЕЛЯТЬСЯ В)
rus_verbs:ФОРМИРОВАТЬСЯ{}, // Сахарная свекла относится к двулетним растениям, мясистый корнеплод формируется в первый год. (ФОРМИРОВАТЬСЯ В)
rus_verbs:ПРОВОРЧАТЬ{}, // дедуля что-то проворчал в ответ (ПРОВОРЧАТЬ В)
rus_verbs:БУРКНУТЬ{}, // нелюдимый парень что-то буркнул в ответ (БУРКНУТЬ В)
rus_verbs:ВЕСТИ{}, // дверь вела во тьму. (ВЕСТИ В)
rus_verbs:ВЫСКОЧИТЬ{}, // беглецы выскочили во двор. (ВЫСКОЧИТЬ В)
rus_verbs:ДОСЫЛАТЬ{}, // Одним движением стрелок досылает патрон в ствол (ДОСЫЛАТЬ В)
rus_verbs:СЪЕХАТЬСЯ{}, // Финалисты съехались на свои игры в Лос-Анжелес. (СЪЕХАТЬСЯ НА, В)
rus_verbs:ВЫТЯНУТЬ{}, // Дым вытянуло в трубу. (ВЫТЯНУТЬ В)
rus_verbs:торчать{}, // острые обломки бревен торчали во все стороны.
rus_verbs:ОГЛЯДЫВАТЬ{}, // Она оглядывает себя в зеркало. (ОГЛЯДЫВАТЬ В)
rus_verbs:ДЕЙСТВОВАТЬ{}, // Этот пакет законов действует в ущерб частным предпринимателям.
rus_verbs:РАЗЛЕТЕТЬСЯ{}, // люди разлетелись во все стороны. (РАЗЛЕТЕТЬСЯ В)
rus_verbs:брызнуть{}, // во все стороны брызнула кровь. (брызнуть в)
rus_verbs:ТЯНУТЬСЯ{}, // провода тянулись во все углы. (ТЯНУТЬСЯ В)
rus_verbs:валить{}, // валить все в одну кучу (валить в)
rus_verbs:выдвинуть{}, // его выдвинули в палату представителей (выдвинуть в)
rus_verbs:карабкаться{}, // карабкаться в гору (карабкаться в)
rus_verbs:клониться{}, // он клонился в сторону (клониться в)
rus_verbs:командировать{}, // мы командировали нашего представителя в Рим (командировать в)
rus_verbs:запасть{}, // Эти слова запали мне в душу.
rus_verbs:давать{}, // В этой лавке дают в долг?
rus_verbs:ездить{}, // Каждый день грузовик ездит в город.
rus_verbs:претвориться{}, // Замысел претворился в жизнь.
rus_verbs:разойтись{}, // Они разошлись в разные стороны.
rus_verbs:выйти{}, // Охотник вышел в поле с ружьём.
rus_verbs:отозвать{}, // Отзовите его в сторону и скажите ему об этом.
rus_verbs:расходиться{}, // Маша и Петя расходятся в разные стороны
rus_verbs:переодеваться{}, // переодеваться в женское платье
rus_verbs:перерастать{}, // перерастать в массовые беспорядки
rus_verbs:завязываться{}, // завязываться в узел
rus_verbs:похватать{}, // похватать в руки
rus_verbs:увлечь{}, // увлечь в прогулку по парку
rus_verbs:помещать{}, // помещать в изолятор
rus_verbs:зыркнуть{}, // зыркнуть в окошко
rus_verbs:закатать{}, // закатать в асфальт
rus_verbs:усаживаться{}, // усаживаться в кресло
rus_verbs:загонять{}, // загонять в сарай
rus_verbs:подбрасывать{}, // подбрасывать в воздух
rus_verbs:телеграфировать{}, // телеграфировать в центр
rus_verbs:вязать{}, // вязать в стопы
rus_verbs:подлить{}, // подлить в огонь
rus_verbs:заполучить{}, // заполучить в распоряжение
rus_verbs:подогнать{}, // подогнать в док
rus_verbs:ломиться{}, // ломиться в открытую дверь
rus_verbs:переправить{}, // переправить в деревню
rus_verbs:затягиваться{}, // затягиваться в трубу
rus_verbs:разлетаться{}, // разлетаться в стороны
rus_verbs:кланяться{}, // кланяться в ножки
rus_verbs:устремляться{}, // устремляться в открытое море
rus_verbs:переместиться{}, // переместиться в другую аудиторию
rus_verbs:ложить{}, // ложить в ящик
rus_verbs:отвозить{}, // отвозить в аэропорт
rus_verbs:напрашиваться{}, // напрашиваться в гости
rus_verbs:напроситься{}, // напроситься в гости
rus_verbs:нагрянуть{}, // нагрянуть в гости
rus_verbs:заворачивать{}, // заворачивать в фольгу
rus_verbs:заковать{}, // заковать в кандалы
rus_verbs:свезти{}, // свезти в сарай
rus_verbs:притащиться{}, // притащиться в дом
rus_verbs:завербовать{}, // завербовать в разведку
rus_verbs:рубиться{}, // рубиться в компьютерные игры
rus_verbs:тыкаться{}, // тыкаться в материнскую грудь
инфинитив:ссыпать{ вид:несоверш }, инфинитив:ссыпать{ вид:соверш }, // ссыпать в контейнер
глагол:ссыпать{ вид:несоверш }, глагол:ссыпать{ вид:соверш },
деепричастие:ссыпав{}, деепричастие:ссыпая{},
rus_verbs:засасывать{}, // засасывать в себя
rus_verbs:скакнуть{}, // скакнуть в будущее
rus_verbs:подвозить{}, // подвозить в театр
rus_verbs:переиграть{}, // переиграть в покер
rus_verbs:мобилизовать{}, // мобилизовать в действующую армию
rus_verbs:залетать{}, // залетать в закрытое воздушное пространство
rus_verbs:подышать{}, // подышать в трубочку
rus_verbs:смотаться{}, // смотаться в институт
rus_verbs:рассовать{}, // рассовать в кармашки
rus_verbs:захаживать{}, // захаживать в дом
инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять в ломбард
деепричастие:сгоняя{},
rus_verbs:посылаться{}, // посылаться в порт
rus_verbs:отлить{}, // отлить в кастрюлю
rus_verbs:преобразоваться{}, // преобразоваться в линейное уравнение
rus_verbs:поплакать{}, // поплакать в платочек
rus_verbs:обуться{}, // обуться в сапоги
rus_verbs:закапать{}, // закапать в глаза
инфинитив:свозить{ вид:несоверш }, инфинитив:свозить{ вид:соверш }, // свозить в центр утилизации
глагол:свозить{ вид:несоверш }, глагол:свозить{ вид:соверш },
деепричастие:свозив{}, деепричастие:свозя{},
rus_verbs:преобразовать{}, // преобразовать в линейное уравнение
rus_verbs:кутаться{}, // кутаться в плед
rus_verbs:смещаться{}, // смещаться в сторону
rus_verbs:зазывать{}, // зазывать в свой магазин
инфинитив:трансформироваться{ вид:несоверш }, инфинитив:трансформироваться{ вид:соверш }, // трансформироваться в комбинезон
глагол:трансформироваться{ вид:несоверш }, глагол:трансформироваться{ вид:соверш },
деепричастие:трансформируясь{}, деепричастие:трансформировавшись{},
rus_verbs:погружать{}, // погружать в кипящее масло
rus_verbs:обыграть{}, // обыграть в теннис
rus_verbs:закутать{}, // закутать в одеяло
rus_verbs:изливаться{}, // изливаться в воду
rus_verbs:закатывать{}, // закатывать в асфальт
rus_verbs:мотнуться{}, // мотнуться в банк
rus_verbs:избираться{}, // избираться в сенат
rus_verbs:наниматься{}, // наниматься в услужение
rus_verbs:настучать{}, // настучать в органы
rus_verbs:запихивать{}, // запихивать в печку
rus_verbs:закапывать{}, // закапывать в нос
rus_verbs:засобираться{}, // засобираться в поход
rus_verbs:копировать{}, // копировать в другую папку
rus_verbs:замуровать{}, // замуровать в стену
rus_verbs:упечь{}, // упечь в тюрьму
rus_verbs:зрить{}, // зрить в корень
rus_verbs:стягиваться{}, // стягиваться в одну точку
rus_verbs:усаживать{}, // усаживать в тренажер
rus_verbs:протолкнуть{}, // протолкнуть в отверстие
rus_verbs:расшибиться{}, // расшибиться в лепешку
rus_verbs:приглашаться{}, // приглашаться в кабинет
rus_verbs:садить{}, // садить в телегу
rus_verbs:уткнуть{}, // уткнуть в подушку
rus_verbs:протечь{}, // протечь в подвал
rus_verbs:перегнать{}, // перегнать в другую страну
rus_verbs:переползти{}, // переползти в тень
rus_verbs:зарываться{}, // зарываться в грунт
rus_verbs:переодеть{}, // переодеть в сухую одежду
rus_verbs:припуститься{}, // припуститься в пляс
rus_verbs:лопотать{}, // лопотать в микрофон
rus_verbs:прогнусавить{}, // прогнусавить в микрофон
rus_verbs:мочиться{}, // мочиться в штаны
rus_verbs:загружать{}, // загружать в патронник
rus_verbs:радировать{}, // радировать в центр
rus_verbs:промотать{}, // промотать в конец
rus_verbs:помчать{}, // помчать в школу
rus_verbs:съезжать{}, // съезжать в кювет
rus_verbs:завозить{}, // завозить в магазин
rus_verbs:заявляться{}, // заявляться в школу
rus_verbs:наглядеться{}, // наглядеться в зеркало
rus_verbs:сворачиваться{}, // сворачиваться в клубочек
rus_verbs:устремлять{}, // устремлять взор в будущее
rus_verbs:забредать{}, // забредать в глухие уголки
rus_verbs:перемотать{}, // перемотать в самое начало диалога
rus_verbs:сморкаться{}, // сморкаться в носовой платочек
rus_verbs:перетекать{}, // перетекать в другой сосуд
rus_verbs:закачать{}, // закачать в шарик
rus_verbs:запрятать{}, // запрятать в сейф
rus_verbs:пинать{}, // пинать в живот
rus_verbs:затрубить{}, // затрубить в горн
rus_verbs:подглядывать{}, // подглядывать в замочную скважину
инфинитив:подсыпать{ вид:соверш }, инфинитив:подсыпать{ вид:несоверш }, // подсыпать в питье
глагол:подсыпать{ вид:соверш }, глагол:подсыпать{ вид:несоверш },
деепричастие:подсыпав{}, деепричастие:подсыпая{},
rus_verbs:засовывать{}, // засовывать в пенал
rus_verbs:отрядить{}, // отрядить в командировку
rus_verbs:справлять{}, // справлять в кусты
rus_verbs:поторапливаться{}, // поторапливаться в самолет
rus_verbs:скопировать{}, // скопировать в кэш
rus_verbs:подливать{}, // подливать в огонь
rus_verbs:запрячь{}, // запрячь в повозку
rus_verbs:окраситься{}, // окраситься в пурпур
rus_verbs:уколоть{}, // уколоть в шею
rus_verbs:слететься{}, // слететься в гнездо
rus_verbs:резаться{}, // резаться в карты
rus_verbs:затесаться{}, // затесаться в ряды оппозиционеров
инфинитив:задвигать{ вид:несоверш }, глагол:задвигать{ вид:несоверш }, // задвигать в ячейку (несоверш)
деепричастие:задвигая{},
rus_verbs:доставляться{}, // доставляться в ресторан
rus_verbs:поплевать{}, // поплевать в чашку
rus_verbs:попереться{}, // попереться в магазин
rus_verbs:хаживать{}, // хаживать в церковь
rus_verbs:преображаться{}, // преображаться в королеву
rus_verbs:организоваться{}, // организоваться в группу
rus_verbs:ужалить{}, // ужалить в руку
rus_verbs:протискиваться{}, // протискиваться в аудиторию
rus_verbs:препроводить{}, // препроводить в закуток
rus_verbs:разъезжаться{}, // разъезжаться в разные стороны
rus_verbs:пропыхтеть{}, // пропыхтеть в трубку
rus_verbs:уволочь{}, // уволочь в нору
rus_verbs:отодвигаться{}, // отодвигаться в сторону
rus_verbs:разливать{}, // разливать в стаканы
rus_verbs:сбегаться{}, // сбегаться в актовый зал
rus_verbs:наведаться{}, // наведаться в кладовку
rus_verbs:перекочевать{}, // перекочевать в горы
rus_verbs:прощебетать{}, // прощебетать в трубку
rus_verbs:перекладывать{}, // перекладывать в другой карман
rus_verbs:углубляться{}, // углубляться в теорию
rus_verbs:переименовать{}, // переименовать в город
rus_verbs:переметнуться{}, // переметнуться в лагерь противника
rus_verbs:разносить{}, // разносить в щепки
rus_verbs:осыпаться{}, // осыпаться в холода
rus_verbs:попроситься{}, // попроситься в туалет
rus_verbs:уязвить{}, // уязвить в сердце
rus_verbs:перетащить{}, // перетащить в дом
rus_verbs:закутаться{}, // закутаться в плед
// rus_verbs:упаковать{}, // упаковать в бумагу
инфинитив:тикать{ aux stress="тик^ать" }, глагол:тикать{ aux stress="тик^ать" }, // тикать в крепость
rus_verbs:хихикать{}, // хихикать в кулачок
rus_verbs:объединить{}, // объединить в сеть
инфинитив:слетать{ вид:соверш }, глагол:слетать{ вид:соверш }, // слетать в Калифорнию
деепричастие:слетав{},
rus_verbs:заползти{}, // заползти в норку
rus_verbs:перерасти{}, // перерасти в крупную аферу
rus_verbs:списать{}, // списать в утиль
rus_verbs:просачиваться{}, // просачиваться в бункер
rus_verbs:пускаться{}, // пускаться в погоню
rus_verbs:согревать{}, // согревать в мороз
rus_verbs:наливаться{}, // наливаться в емкость
rus_verbs:унестись{}, // унестись в небо
rus_verbs:зашвырнуть{}, // зашвырнуть в шкаф
rus_verbs:сигануть{}, // сигануть в воду
rus_verbs:окунуть{}, // окунуть в ледяную воду
rus_verbs:просочиться{}, // просочиться в сапог
rus_verbs:соваться{}, // соваться в толпу
rus_verbs:протолкаться{}, // протолкаться в гардероб
rus_verbs:заложить{}, // заложить в ломбард
rus_verbs:перекатить{}, // перекатить в сарай
rus_verbs:поставлять{}, // поставлять в Китай
rus_verbs:залезать{}, // залезать в долги
rus_verbs:отлучаться{}, // отлучаться в туалет
rus_verbs:сбиваться{}, // сбиваться в кучу
rus_verbs:зарыть{}, // зарыть в землю
rus_verbs:засадить{}, // засадить в тело
rus_verbs:прошмыгнуть{}, // прошмыгнуть в дверь
rus_verbs:переставить{}, // переставить в шкаф
rus_verbs:отчалить{}, // отчалить в плавание
rus_verbs:набираться{}, // набираться в команду
rus_verbs:лягнуть{}, // лягнуть в живот
rus_verbs:притворить{}, // притворить в жизнь
rus_verbs:проковылять{}, // проковылять в гардероб
rus_verbs:прикатить{}, // прикатить в гараж
rus_verbs:залететь{}, // залететь в окно
rus_verbs:переделать{}, // переделать в мопед
rus_verbs:протащить{}, // протащить в совет
rus_verbs:обмакнуть{}, // обмакнуть в воду
rus_verbs:отклоняться{}, // отклоняться в сторону
rus_verbs:запихать{}, // запихать в пакет
rus_verbs:избирать{}, // избирать в совет
rus_verbs:загрузить{}, // загрузить в буфер
rus_verbs:уплывать{}, // уплывать в Париж
rus_verbs:забивать{}, // забивать в мерзлоту
rus_verbs:потыкать{}, // потыкать в безжизненную тушу
rus_verbs:съезжаться{}, // съезжаться в санаторий
rus_verbs:залепить{}, // залепить в рыло
rus_verbs:набиться{}, // набиться в карманы
rus_verbs:уползти{}, // уползти в нору
rus_verbs:упрятать{}, // упрятать в камеру
rus_verbs:переместить{}, // переместить в камеру анабиоза
rus_verbs:закрасться{}, // закрасться в душу
rus_verbs:сместиться{}, // сместиться в инфракрасную область
rus_verbs:запускать{}, // запускать в серию
rus_verbs:потрусить{}, // потрусить в чащобу
rus_verbs:забрасывать{}, // забрасывать в чистую воду
rus_verbs:переселить{}, // переселить в отдаленную деревню
rus_verbs:переезжать{}, // переезжать в новую квартиру
rus_verbs:приподнимать{}, // приподнимать в воздух
rus_verbs:добавиться{}, // добавиться в конец очереди
rus_verbs:убыть{}, // убыть в часть
rus_verbs:передвигать{}, // передвигать в соседнюю клетку
rus_verbs:добавляться{}, // добавляться в очередь
rus_verbs:дописать{}, // дописать в перечень
rus_verbs:записываться{}, // записываться в кружок
rus_verbs:продаться{}, // продаться в кредитное рабство
rus_verbs:переписывать{}, // переписывать в тетрадку
rus_verbs:заплыть{}, // заплыть в территориальные воды
инфинитив:пописать{ aux stress="поп^исать" }, инфинитив:пописать{ aux stress="попис^ать" }, // пописать в горшок
глагол:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="попис^ать" },
rus_verbs:отбирать{}, // отбирать в гвардию
rus_verbs:нашептывать{}, // нашептывать в микрофон
rus_verbs:ковылять{}, // ковылять в стойло
rus_verbs:прилетать{}, // прилетать в Париж
rus_verbs:пролиться{}, // пролиться в канализацию
rus_verbs:запищать{}, // запищать в микрофон
rus_verbs:подвезти{}, // подвезти в больницу
rus_verbs:припереться{}, // припереться в театр
rus_verbs:утечь{}, // утечь в сеть
rus_verbs:прорываться{}, // прорываться в буфет
rus_verbs:увозить{}, // увозить в ремонт
rus_verbs:съедать{}, // съедать в обед
rus_verbs:просунуться{}, // просунуться в дверь
rus_verbs:перенестись{}, // перенестись в прошлое
rus_verbs:завезти{}, // завезти в магазин
rus_verbs:проложить{}, // проложить в деревню
rus_verbs:объединяться{}, // объединяться в профсоюз
rus_verbs:развиться{}, // развиться в бабочку
rus_verbs:засеменить{}, // засеменить в кабинку
rus_verbs:скатываться{}, // скатываться в яму
rus_verbs:завозиться{}, // завозиться в магазин
rus_verbs:нанимать{}, // нанимать в рейс
rus_verbs:поспеть{}, // поспеть в класс
rus_verbs:кидаться{}, // кинаться в крайности
rus_verbs:поспевать{}, // поспевать в оперу
rus_verbs:обернуть{}, // обернуть в фольгу
rus_verbs:обратиться{}, // обратиться в прокуратуру
rus_verbs:истолковать{}, // истолковать в свою пользу
rus_verbs:таращиться{}, // таращиться в дисплей
rus_verbs:прыснуть{}, // прыснуть в кулачок
rus_verbs:загнуть{}, // загнуть в другую сторону
rus_verbs:раздать{}, // раздать в разные руки
rus_verbs:назначить{}, // назначить в приемную комиссию
rus_verbs:кидать{}, // кидать в кусты
rus_verbs:увлекать{}, // увлекать в лес
rus_verbs:переселиться{}, // переселиться в чужое тело
rus_verbs:присылать{}, // присылать в город
rus_verbs:уплыть{}, // уплыть в Европу
rus_verbs:запричитать{}, // запричитать в полный голос
rus_verbs:утащить{}, // утащить в логово
rus_verbs:завернуться{}, // завернуться в плед
rus_verbs:заносить{}, // заносить в блокнот
rus_verbs:пятиться{}, // пятиться в дом
rus_verbs:наведываться{}, // наведываться в больницу
rus_verbs:нырять{}, // нырять в прорубь
rus_verbs:зачастить{}, // зачастить в бар
rus_verbs:назначаться{}, // назначается в комиссию
rus_verbs:мотаться{}, // мотаться в областной центр
rus_verbs:разыграть{}, // разыграть в карты
rus_verbs:пропищать{}, // пропищать в микрофон
rus_verbs:пихнуть{}, // пихнуть в бок
rus_verbs:эмигрировать{}, // эмигрировать в Канаду
rus_verbs:подключить{}, // подключить в сеть
rus_verbs:упереть{}, // упереть в фундамент
rus_verbs:уплатить{}, // уплатить в кассу
rus_verbs:потащиться{}, // потащиться в медпункт
rus_verbs:пригнать{}, // пригнать в стойло
rus_verbs:оттеснить{}, // оттеснить в фойе
rus_verbs:стучаться{}, // стучаться в ворота
rus_verbs:перечислить{}, // перечислить в фонд
rus_verbs:сомкнуть{}, // сомкнуть в круг
rus_verbs:закачаться{}, // закачаться в резервуар
rus_verbs:кольнуть{}, // кольнуть в бок
rus_verbs:накрениться{}, // накрениться в сторону берега
rus_verbs:подвинуться{}, // подвинуться в другую сторону
rus_verbs:разнести{}, // разнести в клочья
rus_verbs:отливать{}, // отливать в форму
rus_verbs:подкинуть{}, // подкинуть в карман
rus_verbs:уводить{}, // уводить в кабинет
rus_verbs:ускакать{}, // ускакать в школу
rus_verbs:ударять{}, // ударять в барабаны
rus_verbs:даться{}, // даться в руки
rus_verbs:поцеловаться{}, // поцеловаться в губы
rus_verbs:посветить{}, // посветить в подвал
rus_verbs:тыкать{}, // тыкать в арбуз
rus_verbs:соединяться{}, // соединяться в кольцо
rus_verbs:растянуть{}, // растянуть в тонкую ниточку
rus_verbs:побросать{}, // побросать в пыль
rus_verbs:стукнуться{}, // стукнуться в закрытую дверь
rus_verbs:проигрывать{}, // проигрывать в теннис
rus_verbs:дунуть{}, // дунуть в трубочку
rus_verbs:улетать{}, // улетать в Париж
rus_verbs:переводиться{}, // переводиться в филиал
rus_verbs:окунуться{}, // окунуться в водоворот событий
rus_verbs:попрятаться{}, // попрятаться в норы
rus_verbs:перевезти{}, // перевезти в соседнюю палату
rus_verbs:топать{}, // топать в школу
rus_verbs:относить{}, // относить в помещение
rus_verbs:укладывать{}, // укладывать в стопку
rus_verbs:укатить{}, // укатил в турне
rus_verbs:убирать{}, // убирать в сумку
rus_verbs:помалкивать{}, // помалкивать в тряпочку
rus_verbs:ронять{}, // ронять в грязь
rus_verbs:глазеть{}, // глазеть в бинокль
rus_verbs:преобразиться{}, // преобразиться в другого человека
rus_verbs:запрыгнуть{}, // запрыгнуть в поезд
rus_verbs:сгодиться{}, // сгодиться в суп
rus_verbs:проползти{}, // проползти в нору
rus_verbs:забираться{}, // забираться в коляску
rus_verbs:сбежаться{}, // сбежались в класс
rus_verbs:закатиться{}, // закатиться в угол
rus_verbs:плевать{}, // плевать в душу
rus_verbs:поиграть{}, // поиграть в демократию
rus_verbs:кануть{}, // кануть в небытие
rus_verbs:опаздывать{}, // опаздывать в школу
rus_verbs:отползти{}, // отползти в сторону
rus_verbs:стекаться{}, // стекаться в отстойник
rus_verbs:запихнуть{}, // запихнуть в пакет
rus_verbs:вышвырнуть{}, // вышвырнуть в коридор
rus_verbs:связываться{}, // связываться в плотный узел
rus_verbs:затолкать{}, // затолкать в ухо
rus_verbs:скрутить{}, // скрутить в трубочку
rus_verbs:сворачивать{}, // сворачивать в трубочку
rus_verbs:сплестись{}, // сплестись в узел
rus_verbs:заскочить{}, // заскочить в кабинет
rus_verbs:проваливаться{}, // проваливаться в сон
rus_verbs:уверовать{}, // уверовать в свою безнаказанность
rus_verbs:переписать{}, // переписать в тетрадку
rus_verbs:переноситься{}, // переноситься в мир фантазий
rus_verbs:заводить{}, // заводить в помещение
rus_verbs:сунуться{}, // сунуться в аудиторию
rus_verbs:устраиваться{}, // устраиваться в автомастерскую
rus_verbs:пропускать{}, // пропускать в зал
инфинитив:сбегать{ вид:несоверш }, инфинитив:сбегать{ вид:соверш }, // сбегать в кино
глагол:сбегать{ вид:несоверш }, глагол:сбегать{ вид:соверш },
деепричастие:сбегая{}, деепричастие:сбегав{},
rus_verbs:прибегать{}, // прибегать в школу
rus_verbs:съездить{}, // съездить в лес
rus_verbs:захлопать{}, // захлопать в ладошки
rus_verbs:опрокинуться{}, // опрокинуться в грязь
инфинитив:насыпать{ вид:несоверш }, инфинитив:насыпать{ вид:соверш }, // насыпать в стакан
глагол:насыпать{ вид:несоверш }, глагол:насыпать{ вид:соверш },
деепричастие:насыпая{}, деепричастие:насыпав{},
rus_verbs:употреблять{}, // употреблять в пищу
rus_verbs:приводиться{}, // приводиться в действие
rus_verbs:пристроить{}, // пристроить в надежные руки
rus_verbs:юркнуть{}, // юркнуть в нору
rus_verbs:объединиться{}, // объединиться в банду
rus_verbs:сажать{}, // сажать в одиночку
rus_verbs:соединить{}, // соединить в кольцо
rus_verbs:забрести{}, // забрести в кафешку
rus_verbs:свернуться{}, // свернуться в клубочек
rus_verbs:пересесть{}, // пересесть в другой автобус
rus_verbs:постучаться{}, // постучаться в дверцу
rus_verbs:соединять{}, // соединять в кольцо
rus_verbs:приволочь{}, // приволочь в коморку
rus_verbs:смахивать{}, // смахивать в ящик стола
rus_verbs:забежать{}, // забежать в помещение
rus_verbs:целиться{}, // целиться в беглеца
rus_verbs:прокрасться{}, // прокрасться в хранилище
rus_verbs:заковылять{}, // заковылять в травтамологию
rus_verbs:прискакать{}, // прискакать в стойло
rus_verbs:колотить{}, // колотить в дверь
rus_verbs:смотреться{}, // смотреться в зеркало
rus_verbs:подложить{}, // подложить в салон
rus_verbs:пущать{}, // пущать в королевские покои
rus_verbs:согнуть{}, // согнуть в дугу
rus_verbs:забарабанить{}, // забарабанить в дверь
rus_verbs:отклонить{}, // отклонить в сторону посадочной полосы
rus_verbs:убраться{}, // убраться в специальную нишу
rus_verbs:насмотреться{}, // насмотреться в зеркало
rus_verbs:чмокнуть{}, // чмокнуть в щечку
rus_verbs:усмехаться{}, // усмехаться в бороду
rus_verbs:передвинуть{}, // передвинуть в конец очереди
rus_verbs:допускаться{}, // допускаться в опочивальню
rus_verbs:задвинуть{}, // задвинуть в дальний угол
rus_verbs:отправлять{}, // отправлять в центр
rus_verbs:сбрасывать{}, // сбрасывать в жерло
rus_verbs:расстреливать{}, // расстреливать в момент обнаружения
rus_verbs:заволочь{}, // заволочь в закуток
rus_verbs:пролить{}, // пролить в воду
rus_verbs:зарыться{}, // зарыться в сено
rus_verbs:переливаться{}, // переливаться в емкость
rus_verbs:затащить{}, // затащить в клуб
rus_verbs:перебежать{}, // перебежать в лагерь врагов
rus_verbs:одеть{}, // одеть в новое платье
инфинитив:задвигаться{ вид:несоверш }, глагол:задвигаться{ вид:несоверш }, // задвигаться в нишу
деепричастие:задвигаясь{},
rus_verbs:клюнуть{}, // клюнуть в темечко
rus_verbs:наливать{}, // наливать в кружку
rus_verbs:пролезть{}, // пролезть в ушко
rus_verbs:откладывать{}, // откладывать в ящик
rus_verbs:протянуться{}, // протянуться в соседний дом
rus_verbs:шлепнуться{}, // шлепнуться лицом в грязь
rus_verbs:устанавливать{}, // устанавливать в машину
rus_verbs:употребляться{}, // употребляться в пищу
rus_verbs:переключиться{}, // переключиться в реверсный режим
rus_verbs:пискнуть{}, // пискнуть в микрофон
rus_verbs:заявиться{}, // заявиться в класс
rus_verbs:налиться{}, // налиться в стакан
rus_verbs:заливать{}, // заливать в бак
rus_verbs:ставиться{}, // ставиться в очередь
инфинитив:писаться{ aux stress="п^исаться" }, глагол:писаться{ aux stress="п^исаться" }, // писаться в штаны
деепричастие:писаясь{},
rus_verbs:целоваться{}, // целоваться в губы
rus_verbs:наносить{}, // наносить в область сердца
rus_verbs:посмеяться{}, // посмеяться в кулачок
rus_verbs:употребить{}, // употребить в пищу
rus_verbs:прорваться{}, // прорваться в столовую
rus_verbs:укладываться{}, // укладываться в ровные стопки
rus_verbs:пробиться{}, // пробиться в финал
rus_verbs:забить{}, // забить в землю
rus_verbs:переложить{}, // переложить в другой карман
rus_verbs:опускать{}, // опускать в свежевырытую могилу
rus_verbs:поторопиться{}, // поторопиться в школу
rus_verbs:сдвинуться{}, // сдвинуться в сторону
rus_verbs:капать{}, // капать в смесь
rus_verbs:погружаться{}, // погружаться во тьму
rus_verbs:направлять{}, // направлять в кабинку
rus_verbs:погрузить{}, // погрузить во тьму
rus_verbs:примчаться{}, // примчаться в школу
rus_verbs:упираться{}, // упираться в дверь
rus_verbs:удаляться{}, // удаляться в комнату совещаний
rus_verbs:ткнуться{}, // ткнуться в окошко
rus_verbs:убегать{}, // убегать в чащу
rus_verbs:соединиться{}, // соединиться в необычную пространственную фигуру
rus_verbs:наговорить{}, // наговорить в микрофон
rus_verbs:переносить{}, // переносить в дом
rus_verbs:прилечь{}, // прилечь в кроватку
rus_verbs:поворачивать{}, // поворачивать в обратную сторону
rus_verbs:проскочить{}, // проскочить в щель
rus_verbs:совать{}, // совать в духовку
rus_verbs:переодеться{}, // переодеться в чистую одежду
rus_verbs:порвать{}, // порвать в лоскуты
rus_verbs:завязать{}, // завязать в бараний рог
rus_verbs:съехать{}, // съехать в кювет
rus_verbs:литься{}, // литься в канистру
rus_verbs:уклониться{}, // уклониться в левую сторону
rus_verbs:смахнуть{}, // смахнуть в мусорное ведро
rus_verbs:спускать{}, // спускать в шахту
rus_verbs:плеснуть{}, // плеснуть в воду
rus_verbs:подуть{}, // подуть в угольки
rus_verbs:набирать{}, // набирать в команду
rus_verbs:хлопать{}, // хлопать в ладошки
rus_verbs:ранить{}, // ранить в самое сердце
rus_verbs:посматривать{}, // посматривать в иллюминатор
rus_verbs:превращать{}, // превращать воду в вино
rus_verbs:толкать{}, // толкать в пучину
rus_verbs:отбыть{}, // отбыть в расположение части
rus_verbs:сгрести{}, // сгрести в карман
rus_verbs:удрать{}, // удрать в тайгу
rus_verbs:пристроиться{}, // пристроиться в хорошую фирму
rus_verbs:сбиться{}, // сбиться в плотную группу
rus_verbs:заключать{}, // заключать в объятия
rus_verbs:отпускать{}, // отпускать в поход
rus_verbs:устремить{}, // устремить взгляд в будущее
rus_verbs:обронить{}, // обронить в траву
rus_verbs:сливаться{}, // сливаться в речку
rus_verbs:стекать{}, // стекать в канаву
rus_verbs:свалить{}, // свалить в кучу
rus_verbs:подтянуть{}, // подтянуть в кабину
rus_verbs:скатиться{}, // скатиться в канаву
rus_verbs:проскользнуть{}, // проскользнуть в приоткрытую дверь
rus_verbs:заторопиться{}, // заторопиться в буфет
rus_verbs:протиснуться{}, // протиснуться в центр толпы
rus_verbs:прятать{}, // прятать в укромненькое местечко
rus_verbs:пропеть{}, // пропеть в микрофон
rus_verbs:углубиться{}, // углубиться в джунгли
rus_verbs:сползти{}, // сползти в яму
rus_verbs:записывать{}, // записывать в память
rus_verbs:расстрелять{}, // расстрелять в упор (наречный оборот В УПОР)
rus_verbs:колотиться{}, // колотиться в дверь
rus_verbs:просунуть{}, // просунуть в отверстие
rus_verbs:провожать{}, // провожать в армию
rus_verbs:катить{}, // катить в гараж
rus_verbs:поражать{}, // поражать в самое сердце
rus_verbs:отлететь{}, // отлететь в дальний угол
rus_verbs:закинуть{}, // закинуть в речку
rus_verbs:катиться{}, // катиться в пропасть
rus_verbs:забросить{}, // забросить в дальний угол
rus_verbs:отвезти{}, // отвезти в лагерь
rus_verbs:втопить{}, // втопить педаль в пол
rus_verbs:втапливать{}, // втапливать педать в пол
rus_verbs:утопить{}, // утопить кнопку в панель
rus_verbs:напасть{}, // В Пекине участники антияпонских протестов напали на машину посла США
rus_verbs:нанять{}, // Босс нанял в службу поддержки еще несколько девушек
rus_verbs:переводить{}, // переводить в устойчивую к перегреву форму
rus_verbs:баллотировать{}, // претендент был баллотирован в жюри (баллотирован?)
rus_verbs:вбухать{}, // Власти вбухали в этой проект много денег
rus_verbs:вбухивать{}, // Власти вбухивают в этот проект очень много денег
rus_verbs:поскакать{}, // поскакать в атаку
rus_verbs:прицелиться{}, // прицелиться в бегущего зайца
rus_verbs:прыгать{}, // прыгать в кровать
rus_verbs:приглашать{}, // приглашать в дом
rus_verbs:понестись{}, // понестись в ворота
rus_verbs:заехать{}, // заехать в гаражный бокс
rus_verbs:опускаться{}, // опускаться в бездну
rus_verbs:переехать{}, // переехать в коттедж
rus_verbs:поместить{}, // поместить в карантин
rus_verbs:ползти{}, // ползти в нору
rus_verbs:добавлять{}, // добавлять в корзину
rus_verbs:уткнуться{}, // уткнуться в подушку
rus_verbs:продавать{}, // продавать в рабство
rus_verbs:спрятаться{}, // Белка спрячется в дупло.
rus_verbs:врисовывать{}, // врисовывать новый персонаж в анимацию
rus_verbs:воткнуть{}, // воткни вилку в розетку
rus_verbs:нести{}, // нести в больницу
rus_verbs:воткнуться{}, // вилка воткнулась в сочную котлетку
rus_verbs:впаивать{}, // впаивать деталь в плату
rus_verbs:впаиваться{}, // деталь впаивается в плату
rus_verbs:впархивать{}, // впархивать в помещение
rus_verbs:впаять{}, // впаять деталь в плату
rus_verbs:впендюривать{}, // впендюривать штукенцию в агрегат
rus_verbs:впендюрить{}, // впендюрить штукенцию в агрегат
rus_verbs:вперивать{}, // вперивать взгляд в экран
rus_verbs:впериваться{}, // впериваться в экран
rus_verbs:вперить{}, // вперить взгляд в экран
rus_verbs:впериться{}, // впериться в экран
rus_verbs:вперять{}, // вперять взгляд в экран
rus_verbs:вперяться{}, // вперяться в экран
rus_verbs:впечатать{}, // впечатать текст в первую главу
rus_verbs:впечататься{}, // впечататься в стену
rus_verbs:впечатывать{}, // впечатывать текст в первую главу
rus_verbs:впечатываться{}, // впечатываться в стену
rus_verbs:впиваться{}, // Хищник впивается в жертву мощными зубами
rus_verbs:впитаться{}, // Жидкость впиталась в ткань
rus_verbs:впитываться{}, // Жидкость впитывается в ткань
rus_verbs:впихивать{}, // Мама впихивает в сумку кусок колбасы
rus_verbs:впихиваться{}, // Кусок колбасы впихивается в сумку
rus_verbs:впихнуть{}, // Мама впихнула кастрюлю в холодильник
rus_verbs:впихнуться{}, // Кастрюля впихнулась в холодильник
rus_verbs:вплавиться{}, // Провод вплавился в плату
rus_verbs:вплеснуть{}, // вплеснуть краситель в бак
rus_verbs:вплести{}, // вплести ленту в волосы
rus_verbs:вплестись{}, // вплестись в волосы
rus_verbs:вплетать{}, // вплетать ленты в волосы
rus_verbs:вплывать{}, // корабль вплывает в порт
rus_verbs:вплыть{}, // яхта вплыла в бухту
rus_verbs:вползать{}, // дракон вползает в пещеру
rus_verbs:вползти{}, // дракон вполз в свою пещеру
rus_verbs:впорхнуть{}, // бабочка впорхнула в окно
rus_verbs:впрессовать{}, // впрессовать деталь в плиту
rus_verbs:впрессоваться{}, // впрессоваться в плиту
rus_verbs:впрессовывать{}, // впрессовывать деталь в плиту
rus_verbs:впрессовываться{}, // впрессовываться в плиту
rus_verbs:впрыгивать{}, // Пассажир впрыгивает в вагон
rus_verbs:впрыгнуть{}, // Пассажир впрыгнул в вагон
rus_verbs:впрыскивать{}, // Форсунка впрыскивает топливо в цилиндр
rus_verbs:впрыскиваться{}, // Топливо впрыскивается форсункой в цилиндр
rus_verbs:впрыснуть{}, // Форсунка впрыснула топливную смесь в камеру сгорания
rus_verbs:впрягать{}, // впрягать лошадь в телегу
rus_verbs:впрягаться{}, // впрягаться в работу
rus_verbs:впрячь{}, // впрячь лошадь в телегу
rus_verbs:впрячься{}, // впрячься в работу
rus_verbs:впускать{}, // впускать посетителей в музей
rus_verbs:впускаться{}, // впускаться в помещение
rus_verbs:впустить{}, // впустить посетителей в музей
rus_verbs:впутать{}, // впутать кого-то во что-то
rus_verbs:впутаться{}, // впутаться во что-то
rus_verbs:впутывать{}, // впутывать кого-то во что-то
rus_verbs:впутываться{}, // впутываться во что-то
rus_verbs:врабатываться{}, // врабатываться в режим
rus_verbs:вработаться{}, // вработаться в режим
rus_verbs:врастать{}, // врастать в кожу
rus_verbs:врасти{}, // врасти в кожу
инфинитив:врезать{ вид:несоверш }, // врезать замок в дверь
инфинитив:врезать{ вид:соверш },
глагол:врезать{ вид:несоверш },
глагол:врезать{ вид:соверш },
деепричастие:врезая{},
деепричастие:врезав{},
прилагательное:врезанный{},
инфинитив:врезаться{ вид:несоверш }, // врезаться в стену
инфинитив:врезаться{ вид:соверш },
глагол:врезаться{ вид:несоверш },
деепричастие:врезаясь{},
деепричастие:врезавшись{},
rus_verbs:врубить{}, // врубить в нагрузку
rus_verbs:врываться{}, // врываться в здание
rus_verbs:закачивать{}, // Насос закачивает топливо в бак
rus_verbs:ввезти{}, // Предприятие ввезло товар в страну
rus_verbs:вверстать{}, // Дизайнер вверстал блок в страницу
rus_verbs:вверстывать{}, // Дизайнер с трудом вверстывает блоки в страницу
rus_verbs:вверстываться{}, // Блок тяжело вверстывается в эту страницу
rus_verbs:ввивать{}, // Женщина ввивает полоску в косу
rus_verbs:вволакиваться{}, // Пойманная мышь вволакивается котиком в дом
rus_verbs:вволочь{}, // Кот вволок в дом пойманную крысу
rus_verbs:вдергивать{}, // приспособление вдергивает нитку в игольное ушко
rus_verbs:вдернуть{}, // приспособление вдернуло нитку в игольное ушко
rus_verbs:вдувать{}, // Челоек вдувает воздух в легкие второго человека
rus_verbs:вдуваться{}, // Воздух вдувается в легкие человека
rus_verbs:вламываться{}, // Полиция вламывается в квартиру
rus_verbs:вовлекаться{}, // трудные подростки вовлекаются в занятие спортом
rus_verbs:вовлечь{}, // вовлечь трудных подростков в занятие спортом
rus_verbs:вовлечься{}, // вовлечься в занятие спортом
rus_verbs:спуститься{}, // спуститься в подвал
rus_verbs:спускаться{}, // спускаться в подвал
rus_verbs:отправляться{}, // отправляться в дальнее плавание
инфинитив:эмитировать{ вид:соверш }, // Поверхность эмитирует электроны в пространство
инфинитив:эмитировать{ вид:несоверш },
глагол:эмитировать{ вид:соверш },
глагол:эмитировать{ вид:несоверш },
деепричастие:эмитируя{},
деепричастие:эмитировав{},
прилагательное:эмитировавший{ вид:несоверш },
// прилагательное:эмитировавший{ вид:соверш },
прилагательное:эмитирующий{},
прилагательное:эмитируемый{},
прилагательное:эмитированный{},
инфинитив:этапировать{вид:несоверш}, // Преступника этапировали в колонию
инфинитив:этапировать{вид:соверш},
глагол:этапировать{вид:несоверш},
глагол:этапировать{вид:соверш},
деепричастие:этапируя{},
прилагательное:этапируемый{},
прилагательное:этапированный{},
rus_verbs:этапироваться{}, // Преступники этапируются в колонию
rus_verbs:баллотироваться{}, // они баллотировались в жюри
rus_verbs:бежать{}, // Олигарх с семьей любовницы бежал в другую страну
rus_verbs:бросать{}, // Они бросали в фонтан медные монетки
rus_verbs:бросаться{}, // Дети бросались в воду с моста
rus_verbs:бросить{}, // Он бросил в фонтан медную монетку
rus_verbs:броситься{}, // самоубийца бросился с моста в воду
rus_verbs:превратить{}, // Найден белок, который превратит человека в супергероя
rus_verbs:буксировать{}, // Буксир буксирует танкер в порт
rus_verbs:буксироваться{}, // Сухогруз буксируется в порт
rus_verbs:вбегать{}, // Курьер вбегает в дверь
rus_verbs:вбежать{}, // Курьер вбежал в дверь
rus_verbs:вбетонировать{}, // Опора была вбетонирована в пол
rus_verbs:вбивать{}, // Мастер вбивает штырь в плиту
rus_verbs:вбиваться{}, // Штырь вбивается в плиту
rus_verbs:вбирать{}, // Вата вбирает в себя влагу
rus_verbs:вбить{}, // Ученик вбил в доску маленький гвоздь
rus_verbs:вбрасывать{}, // Арбитр вбрасывает мяч в игру
rus_verbs:вбрасываться{}, // Мяч вбрасывается в игру
rus_verbs:вбросить{}, // Судья вбросил мяч в игру
rus_verbs:вбуравиться{}, // Сверло вбуравилось в бетон
rus_verbs:вбуравливаться{}, // Сверло вбуравливается в бетон
rus_verbs:вбухиваться{}, // Много денег вбухиваются в этот проект
rus_verbs:вваливаться{}, // Человек вваливается в кабинет врача
rus_verbs:ввалить{}, // Грузчики ввалили мешок в квартиру
rus_verbs:ввалиться{}, // Человек ввалился в кабинет терапевта
rus_verbs:вваривать{}, // Робот вваривает арматурину в плиту
rus_verbs:ввариваться{}, // Арматура вваривается в плиту
rus_verbs:вварить{}, // Робот вварил арматурину в плиту
rus_verbs:влезть{}, // Предприятие ввезло товар в страну
rus_verbs:ввернуть{}, // Вверни новую лампочку в люстру
rus_verbs:ввернуться{}, // Лампочка легко ввернулась в патрон
rus_verbs:ввертывать{}, // Электрик ввертывает лампочку в патрон
rus_verbs:ввертываться{}, // Лампочка легко ввертывается в патрон
rus_verbs:вверять{}, // Пациент вверяет свою жизнь в руки врача
rus_verbs:вверяться{}, // Пациент вверяется в руки врача
rus_verbs:ввести{}, // Агенство ввело своего представителя в совет директоров
rus_verbs:ввиваться{}, // полоска ввивается в косу
rus_verbs:ввинтить{}, // Отвертка ввинтила шуруп в дерево
rus_verbs:ввинтиться{}, // Шуруп ввинтился в дерево
rus_verbs:ввинчивать{}, // Рука ввинчивает саморез в стену
rus_verbs:ввинчиваться{}, // Саморез ввинчивается в стену
rus_verbs:вводить{}, // Агенство вводит своего представителя в совет директоров
rus_verbs:вводиться{}, // Представитель агенства вводится в совет директоров
// rus_verbs:ввозить{}, // Фирма ввозит в страну станки и сырье
rus_verbs:ввозиться{}, // Станки и сырье ввозятся в страну
rus_verbs:вволакивать{}, // Пойманная мышь вволакивается котиком в дом
rus_verbs:вворачивать{}, // Электрик вворачивает новую лампочку в патрон
rus_verbs:вворачиваться{}, // Новая лампочка легко вворачивается в патрон
rus_verbs:ввязаться{}, // Разведрота ввязалась в бой
rus_verbs:ввязываться{}, // Передовые части ввязываются в бой
rus_verbs:вглядеться{}, // Охранник вгляделся в темный коридор
rus_verbs:вглядываться{}, // Охранник внимательно вглядывается в монитор
rus_verbs:вгонять{}, // Эта музыка вгоняет меня в депрессию
rus_verbs:вгрызаться{}, // Зонд вгрызается в поверхность астероида
rus_verbs:вгрызться{}, // Зонд вгрызся в поверхность астероида
rus_verbs:вдаваться{}, // Вы не должны вдаваться в юридические детали
rus_verbs:вдвигать{}, // Робот вдвигает контейнер в ячейку
rus_verbs:вдвигаться{}, // Контейнер вдвигается в ячейку
rus_verbs:вдвинуть{}, // манипулятор вдвинул деталь в печь
rus_verbs:вдвинуться{}, // деталь вдвинулась в печь
rus_verbs:вдевать{}, // портниха быстро вдевает нитку в иголку
rus_verbs:вдеваться{}, // нитка быстро вдевается в игольное ушко
rus_verbs:вдеть{}, // портниха быстро вдела нитку в игольное ушко
rus_verbs:вдеться{}, // нитка быстро вделась в игольное ушко
rus_verbs:вделать{}, // мастер вделал розетку в стену
rus_verbs:вделывать{}, // мастер вделывает выключатель в стену
rus_verbs:вделываться{}, // кронштейн вделывается в стену
rus_verbs:вдергиваться{}, // нитка легко вдергивается в игольное ушко
rus_verbs:вдернуться{}, // нитка легко вдернулась в игольное ушко
rus_verbs:вдолбить{}, // Американцы обещали вдолбить страну в каменный век
rus_verbs:вдумываться{}, // Мальчик обычно не вдумывался в сюжет фильмов
rus_verbs:вдыхать{}, // мы вдыхаем в себя весь этот смог
rus_verbs:вдыхаться{}, // Весь этот смог вдыхается в легкие
rus_verbs:вернуть{}, // Книгу надо вернуть в библиотеку
rus_verbs:вернуться{}, // Дети вернулись в библиотеку
rus_verbs:вжаться{}, // Водитель вжался в кресло
rus_verbs:вживаться{}, // Актер вживается в новую роль
rus_verbs:вживить{}, // Врачи вживили стимулятор в тело пациента
rus_verbs:вживиться{}, // Стимулятор вживился в тело пациента
rus_verbs:вживлять{}, // Врачи вживляют стимулятор в тело пациента
rus_verbs:вживляться{}, // Стимулятор вживляется в тело
rus_verbs:вжиматься{}, // Видитель инстинктивно вжимается в кресло
rus_verbs:вжиться{}, // Актер вжился в свою новую роль
rus_verbs:взвиваться{}, // Воздушный шарик взвивается в небо
rus_verbs:взвинтить{}, // Кризис взвинтил цены в небо
rus_verbs:взвинтиться{}, // Цены взвинтились в небо
rus_verbs:взвинчивать{}, // Кризис взвинчивает цены в небо
rus_verbs:взвинчиваться{}, // Цены взвинчиваются в небо
rus_verbs:взвиться{}, // Шарики взвились в небо
rus_verbs:взлетать{}, // Экспериментальный аппарат взлетает в воздух
rus_verbs:взлететь{}, // Экспериментальный аппарат взлетел в небо
rus_verbs:взмывать{}, // шарики взмывают в небо
rus_verbs:взмыть{}, // Шарики взмыли в небо
rus_verbs:вильнуть{}, // Машина вильнула в левую сторону
rus_verbs:вкалывать{}, // Медсестра вкалывает иглу в вену
rus_verbs:вкалываться{}, // Игла вкалываться прямо в вену
rus_verbs:вкапывать{}, // рабочий вкапывает сваю в землю
rus_verbs:вкапываться{}, // Свая вкапывается в землю
rus_verbs:вкатить{}, // рабочие вкатили бочку в гараж
rus_verbs:вкатиться{}, // машина вкатилась в гараж
rus_verbs:вкатывать{}, // рабочик вкатывают бочку в гараж
rus_verbs:вкатываться{}, // машина вкатывается в гараж
rus_verbs:вкачать{}, // Механики вкачали в бак много топлива
rus_verbs:вкачивать{}, // Насос вкачивает топливо в бак
rus_verbs:вкачиваться{}, // Топливо вкачивается в бак
rus_verbs:вкидать{}, // Манипулятор вкидал груз в контейнер
rus_verbs:вкидывать{}, // Манипулятор вкидывает груз в контейнер
rus_verbs:вкидываться{}, // Груз вкидывается в контейнер
rus_verbs:вкладывать{}, // Инвестор вкладывает деньги в акции
rus_verbs:вкладываться{}, // Инвестор вкладывается в акции
rus_verbs:вклеивать{}, // Мальчик вклеивает картинку в тетрадь
rus_verbs:вклеиваться{}, // Картинка вклеивается в тетрадь
rus_verbs:вклеить{}, // Мальчик вклеил картинку в тетрадь
rus_verbs:вклеиться{}, // Картинка вклеилась в тетрадь
rus_verbs:вклепать{}, // Молоток вклепал заклепку в лист
rus_verbs:вклепывать{}, // Молоток вклепывает заклепку в лист
rus_verbs:вклиниваться{}, // Машина вклинивается в поток
rus_verbs:вклиниться{}, // машина вклинилась в поток
rus_verbs:включать{}, // Команда включает компьютер в сеть
rus_verbs:включаться{}, // Машина включается в глобальную сеть
rus_verbs:включить{}, // Команда включила компьютер в сеть
rus_verbs:включиться{}, // Компьютер включился в сеть
rus_verbs:вколачивать{}, // Столяр вколачивает гвоздь в доску
rus_verbs:вколачиваться{}, // Гвоздь вколачивается в доску
rus_verbs:вколотить{}, // Столяр вколотил гвоздь в доску
rus_verbs:вколоть{}, // Медсестра вколола в мышцу лекарство
rus_verbs:вкопать{}, // Рабочие вкопали сваю в землю
rus_verbs:вкрадываться{}, // Ошибка вкрадывается в расчеты
rus_verbs:вкраивать{}, // Портниха вкраивает вставку в юбку
rus_verbs:вкраиваться{}, // Вставка вкраивается в юбку
rus_verbs:вкрасться{}, // Ошибка вкралась в расчеты
rus_verbs:вкрутить{}, // Электрик вкрутил лампочку в патрон
rus_verbs:вкрутиться{}, // лампочка легко вкрутилась в патрон
rus_verbs:вкручивать{}, // Электрик вкручивает лампочку в патрон
rus_verbs:вкручиваться{}, // Лампочка легко вкручивается в патрон
rus_verbs:влазить{}, // Разъем влазит в отверствие
rus_verbs:вламывать{}, // Полиция вламывается в квартиру
rus_verbs:влетать{}, // Самолет влетает в грозовой фронт
rus_verbs:влететь{}, // Самолет влетел в грозовой фронт
rus_verbs:вливать{}, // Механик вливает масло в картер
rus_verbs:вливаться{}, // Масло вливается в картер
rus_verbs:влипать{}, // Эти неудачники постоянно влипают в разные происшествия
rus_verbs:влипнуть{}, // Эти неудачники опять влипли в неприятности
rus_verbs:влить{}, // Механик влил свежее масло в картер
rus_verbs:влиться{}, // Свежее масло влилось в бак
rus_verbs:вложить{}, // Инвесторы вложили в эти акции большие средства
rus_verbs:вложиться{}, // Инвесторы вложились в эти акции
rus_verbs:влюбиться{}, // Коля влюбился в Олю
rus_verbs:влюблять{}, // Оля постоянно влюбляла в себя мальчиков
rus_verbs:влюбляться{}, // Оля влюбляется в спортсменов
rus_verbs:вляпаться{}, // Коля вляпался в неприятность
rus_verbs:вляпываться{}, // Коля постоянно вляпывается в неприятности
rus_verbs:вменить{}, // вменить в вину
rus_verbs:вменять{}, // вменять в обязанность
rus_verbs:вмерзать{}, // Колеса вмерзают в лед
rus_verbs:вмерзнуть{}, // Колеса вмерзли в лед
rus_verbs:вмести{}, // вмести в дом
rus_verbs:вместить{}, // вместить в ёмкость
rus_verbs:вместиться{}, // Прибор не вместился в зонд
rus_verbs:вмешаться{}, // Начальник вмешался в конфликт
rus_verbs:вмешивать{}, // Не вмешивай меня в это дело
rus_verbs:вмешиваться{}, // Начальник вмешивается в переговоры
rus_verbs:вмещаться{}, // Приборы не вмещаются в корпус
rus_verbs:вминать{}, // вминать в корпус
rus_verbs:вминаться{}, // кронштейн вминается в корпус
rus_verbs:вмонтировать{}, // Конструкторы вмонтировали в корпус зонда новые приборы
rus_verbs:вмонтироваться{}, // Новые приборы легко вмонтировались в корпус зонда
rus_verbs:вмораживать{}, // Установка вмораживает сваи в грунт
rus_verbs:вмораживаться{}, // Сваи вмораживаются в грунт
rus_verbs:вморозить{}, // Установка вморозила сваи в грунт
rus_verbs:вмуровать{}, // Сейф был вмурован в стену
rus_verbs:вмуровывать{}, // вмуровывать сейф в стену
rus_verbs:вмуровываться{}, // сейф вмуровывается в бетонную стену
rus_verbs:внедрить{}, // внедрить инновацию в производство
rus_verbs:внедриться{}, // Шпион внедрился в руководство
rus_verbs:внедрять{}, // внедрять инновации в производство
rus_verbs:внедряться{}, // Шпионы внедряются в руководство
rus_verbs:внести{}, // внести коробку в дом
rus_verbs:внестись{}, // внестись в список приглашенных гостей
rus_verbs:вникать{}, // Разработчик вникает в детали задачи
rus_verbs:вникнуть{}, // Дизайнер вник в детали задачи
rus_verbs:вносить{}, // вносить новое действующее лицо в список главных героев
rus_verbs:вноситься{}, // вноситься в список главных персонажей
rus_verbs:внюхаться{}, // Пёс внюхался в ароматы леса
rus_verbs:внюхиваться{}, // Пёс внюхивается в ароматы леса
rus_verbs:вобрать{}, // вобрать в себя лучшие методы борьбы с вредителями
rus_verbs:вовлекать{}, // вовлекать трудных подростков в занятие спортом
rus_verbs:вогнать{}, // вогнал человека в тоску
rus_verbs:водворить{}, // водворить преступника в тюрьму
rus_verbs:возвернуть{}, // возвернуть в родную стихию
rus_verbs:возвернуться{}, // возвернуться в родную стихию
rus_verbs:возвести{}, // возвести число в четную степень
rus_verbs:возводить{}, // возводить число в четную степень
rus_verbs:возводиться{}, // число возводится в четную степень
rus_verbs:возвратить{}, // возвратить коров в стойло
rus_verbs:возвратиться{}, // возвратиться в родной дом
rus_verbs:возвращать{}, // возвращать коров в стойло
rus_verbs:возвращаться{}, // возвращаться в родной дом
rus_verbs:войти{}, // войти в галерею славы
rus_verbs:вонзать{}, // Коля вонзает вилку в котлету
rus_verbs:вонзаться{}, // Вилка вонзается в котлету
rus_verbs:вонзить{}, // Коля вонзил вилку в котлету
rus_verbs:вонзиться{}, // Вилка вонзилась в сочную котлету
rus_verbs:воплотить{}, // Коля воплотил свои мечты в реальность
rus_verbs:воплотиться{}, // Мечты воплотились в реальность
rus_verbs:воплощать{}, // Коля воплощает мечты в реальность
rus_verbs:воплощаться{}, // Мечты иногда воплощаются в реальность
rus_verbs:ворваться{}, // Перемены неожиданно ворвались в размеренную жизнь
rus_verbs:воспарить{}, // Душа воспарила в небо
rus_verbs:воспарять{}, // Душа воспаряет в небо
rus_verbs:врыть{}, // врыть опору в землю
rus_verbs:врыться{}, // врыться в землю
rus_verbs:всадить{}, // всадить пулю в сердце
rus_verbs:всаживать{}, // всаживать нож в бок
rus_verbs:всасывать{}, // всасывать воду в себя
rus_verbs:всасываться{}, // всасываться в ёмкость
rus_verbs:вселить{}, // вселить надежду в кого-либо
rus_verbs:вселиться{}, // вселиться в пустующее здание
rus_verbs:вселять{}, // вселять надежду в кого-то
rus_verbs:вселяться{}, // вселяться в пустующее здание
rus_verbs:вскидывать{}, // вскидывать руку в небо
rus_verbs:вскинуть{}, // вскинуть руку в небо
rus_verbs:вслушаться{}, // вслушаться в звуки
rus_verbs:вслушиваться{}, // вслушиваться в шорох
rus_verbs:всматриваться{}, // всматриваться в темноту
rus_verbs:всмотреться{}, // всмотреться в темень
rus_verbs:всовывать{}, // всовывать палец в отверстие
rus_verbs:всовываться{}, // всовываться в форточку
rus_verbs:всосать{}, // всосать жидкость в себя
rus_verbs:всосаться{}, // всосаться в кожу
rus_verbs:вставить{}, // вставить ключ в замок
rus_verbs:вставлять{}, // вставлять ключ в замок
rus_verbs:встраивать{}, // встраивать черный ход в систему защиты
rus_verbs:встраиваться{}, // встраиваться в систему безопасности
rus_verbs:встревать{}, // встревать в разговор
rus_verbs:встроить{}, // встроить секретный модуль в систему безопасности
rus_verbs:встроиться{}, // встроиться в систему безопасности
rus_verbs:встрять{}, // встрять в разговор
rus_verbs:вступать{}, // вступать в действующую армию
rus_verbs:вступить{}, // вступить в действующую армию
rus_verbs:всунуть{}, // всунуть палец в отверстие
rus_verbs:всунуться{}, // всунуться в форточку
инфинитив:всыпать{вид:соверш}, // всыпать порошок в контейнер
инфинитив:всыпать{вид:несоверш},
глагол:всыпать{вид:соверш},
глагол:всыпать{вид:несоверш},
деепричастие:всыпав{},
деепричастие:всыпая{},
прилагательное:всыпавший{ вид:соверш },
// прилагательное:всыпавший{ вид:несоверш },
прилагательное:всыпанный{},
// прилагательное:всыпающий{},
инфинитив:всыпаться{ вид:несоверш}, // всыпаться в контейнер
// инфинитив:всыпаться{ вид:соверш},
// глагол:всыпаться{ вид:соверш},
глагол:всыпаться{ вид:несоверш},
// деепричастие:всыпавшись{},
деепричастие:всыпаясь{},
// прилагательное:всыпавшийся{ вид:соверш },
// прилагательное:всыпавшийся{ вид:несоверш },
// прилагательное:всыпающийся{},
rus_verbs:вталкивать{}, // вталкивать деталь в ячейку
rus_verbs:вталкиваться{}, // вталкиваться в ячейку
rus_verbs:втаптывать{}, // втаптывать в грязь
rus_verbs:втаптываться{}, // втаптываться в грязь
rus_verbs:втаскивать{}, // втаскивать мешок в комнату
rus_verbs:втаскиваться{}, // втаскиваться в комнату
rus_verbs:втащить{}, // втащить мешок в комнату
rus_verbs:втащиться{}, // втащиться в комнату
rus_verbs:втекать{}, // втекать в бутылку
rus_verbs:втемяшивать{}, // втемяшивать в голову
rus_verbs:втемяшиваться{}, // втемяшиваться в голову
rus_verbs:втемяшить{}, // втемяшить в голову
rus_verbs:втемяшиться{}, // втемяшиться в голову
rus_verbs:втереть{}, // втереть крем в кожу
rus_verbs:втереться{}, // втереться в кожу
rus_verbs:втесаться{}, // втесаться в группу
rus_verbs:втесывать{}, // втесывать в группу
rus_verbs:втесываться{}, // втесываться в группу
rus_verbs:втечь{}, // втечь в бак
rus_verbs:втирать{}, // втирать крем в кожу
rus_verbs:втираться{}, // втираться в кожу
rus_verbs:втискивать{}, // втискивать сумку в вагон
rus_verbs:втискиваться{}, // втискиваться в переполненный вагон
rus_verbs:втиснуть{}, // втиснуть сумку в вагон
rus_verbs:втиснуться{}, // втиснуться в переполненный вагон метро
rus_verbs:втолкать{}, // втолкать коляску в лифт
rus_verbs:втолкаться{}, // втолкаться в вагон метро
rus_verbs:втолкнуть{}, // втолкнуть коляску в лифт
rus_verbs:втолкнуться{}, // втолкнуться в вагон метро
rus_verbs:втолочь{}, // втолочь в смесь
rus_verbs:втоптать{}, // втоптать цветы в землю
rus_verbs:вторгаться{}, // вторгаться в чужую зону
rus_verbs:вторгнуться{}, // вторгнуться в частную жизнь
rus_verbs:втравить{}, // втравить кого-то в неприятности
rus_verbs:втравливать{}, // втравливать кого-то в неприятности
rus_verbs:втрамбовать{}, // втрамбовать камни в землю
rus_verbs:втрамбовывать{}, // втрамбовывать камни в землю
rus_verbs:втрамбовываться{}, // втрамбовываться в землю
rus_verbs:втрескаться{}, // втрескаться в кого-то
rus_verbs:втрескиваться{}, // втрескиваться в кого-либо
rus_verbs:втыкать{}, // втыкать вилку в котлетку
rus_verbs:втыкаться{}, // втыкаться в розетку
rus_verbs:втюриваться{}, // втюриваться в кого-либо
rus_verbs:втюриться{}, // втюриться в кого-либо
rus_verbs:втягивать{}, // втягивать что-то в себя
rus_verbs:втягиваться{}, // втягиваться в себя
rus_verbs:втянуться{}, // втянуться в себя
rus_verbs:вцементировать{}, // вцементировать сваю в фундамент
rus_verbs:вчеканить{}, // вчеканить надпись в лист
rus_verbs:вчитаться{}, // вчитаться внимательнее в текст
rus_verbs:вчитываться{}, // вчитываться внимательнее в текст
rus_verbs:вчувствоваться{}, // вчувствоваться в роль
rus_verbs:вшагивать{}, // вшагивать в новую жизнь
rus_verbs:вшагнуть{}, // вшагнуть в новую жизнь
rus_verbs:вшивать{}, // вшивать заплату в рубашку
rus_verbs:вшиваться{}, // вшиваться в ткань
rus_verbs:вшить{}, // вшить заплату в ткань
rus_verbs:въедаться{}, // въедаться в мякоть
rus_verbs:въезжать{}, // въезжать в гараж
rus_verbs:въехать{}, // въехать в гараж
rus_verbs:выиграть{}, // Коля выиграл в шахматы
rus_verbs:выигрывать{}, // Коля часто выигрывает у меня в шахматы
rus_verbs:выкладывать{}, // выкладывать в общий доступ
rus_verbs:выкладываться{}, // выкладываться в общий доступ
rus_verbs:выкрасить{}, // выкрасить машину в розовый цвет
rus_verbs:выкраситься{}, // выкраситься в дерзкий розовый цвет
rus_verbs:выкрашивать{}, // выкрашивать волосы в красный цвет
rus_verbs:выкрашиваться{}, // выкрашиваться в красный цвет
rus_verbs:вылезать{}, // вылезать в открытое пространство
rus_verbs:вылезти{}, // вылезти в открытое пространство
rus_verbs:выливать{}, // выливать в бутылку
rus_verbs:выливаться{}, // выливаться в ёмкость
rus_verbs:вылить{}, // вылить отходы в канализацию
rus_verbs:вылиться{}, // Топливо вылилось в воду
rus_verbs:выложить{}, // выложить в общий доступ
rus_verbs:выпадать{}, // выпадать в осадок
rus_verbs:выпрыгивать{}, // выпрыгивать в окно
rus_verbs:выпрыгнуть{}, // выпрыгнуть в окно
rus_verbs:выродиться{}, // выродиться в жалкое подобие
rus_verbs:вырождаться{}, // вырождаться в жалкое подобие славных предков
rus_verbs:высеваться{}, // высеваться в землю
rus_verbs:высеять{}, // высеять в землю
rus_verbs:выслать{}, // выслать в страну постоянного пребывания
rus_verbs:высморкаться{}, // высморкаться в платок
rus_verbs:высморкнуться{}, // высморкнуться в платок
rus_verbs:выстреливать{}, // выстреливать в цель
rus_verbs:выстреливаться{}, // выстреливаться в цель
rus_verbs:выстрелить{}, // выстрелить в цель
rus_verbs:вытекать{}, // вытекать в озеро
rus_verbs:вытечь{}, // вытечь в воду
rus_verbs:смотреть{}, // смотреть в будущее
rus_verbs:подняться{}, // подняться в лабораторию
rus_verbs:послать{}, // послать в магазин
rus_verbs:слать{}, // слать в неизвестность
rus_verbs:добавить{}, // добавить в суп
rus_verbs:пройти{}, // пройти в лабораторию
rus_verbs:положить{}, // положить в ящик
rus_verbs:прислать{}, // прислать в полицию
rus_verbs:упасть{}, // упасть в пропасть
инфинитив:писать{ aux stress="пис^ать" }, // писать в газету
инфинитив:писать{ aux stress="п^исать" }, // писать в штанишки
глагол:писать{ aux stress="п^исать" },
глагол:писать{ aux stress="пис^ать" },
деепричастие:писая{},
прилагательное:писавший{ aux stress="п^исавший" }, // писавший в штанишки
прилагательное:писавший{ aux stress="пис^авший" }, // писавший в газету
rus_verbs:собираться{}, // собираться в поход
rus_verbs:звать{}, // звать в ресторан
rus_verbs:направиться{}, // направиться в ресторан
rus_verbs:отправиться{}, // отправиться в ресторан
rus_verbs:поставить{}, // поставить в угол
rus_verbs:целить{}, // целить в мишень
rus_verbs:попасть{}, // попасть в переплет
rus_verbs:ударить{}, // ударить в больное место
rus_verbs:закричать{}, // закричать в микрофон
rus_verbs:опустить{}, // опустить в воду
rus_verbs:принести{}, // принести в дом бездомного щенка
rus_verbs:отдать{}, // отдать в хорошие руки
rus_verbs:ходить{}, // ходить в школу
rus_verbs:уставиться{}, // уставиться в экран
rus_verbs:приходить{}, // приходить в бешенство
rus_verbs:махнуть{}, // махнуть в Италию
rus_verbs:сунуть{}, // сунуть в замочную скважину
rus_verbs:явиться{}, // явиться в расположение части
rus_verbs:уехать{}, // уехать в город
rus_verbs:целовать{}, // целовать в лобик
rus_verbs:повести{}, // повести в бой
rus_verbs:опуститься{}, // опуститься в кресло
rus_verbs:передать{}, // передать в архив
rus_verbs:побежать{}, // побежать в школу
rus_verbs:стечь{}, // стечь в воду
rus_verbs:уходить{}, // уходить добровольцем в армию
rus_verbs:привести{}, // привести в дом
rus_verbs:шагнуть{}, // шагнуть в неизвестность
rus_verbs:собраться{}, // собраться в поход
rus_verbs:заглянуть{}, // заглянуть в основу
rus_verbs:поспешить{}, // поспешить в церковь
rus_verbs:поцеловать{}, // поцеловать в лоб
rus_verbs:перейти{}, // перейти в высшую лигу
rus_verbs:поверить{}, // поверить в искренность
rus_verbs:глянуть{}, // глянуть в оглавление
rus_verbs:зайти{}, // зайти в кафетерий
rus_verbs:подобрать{}, // подобрать в лесу
rus_verbs:проходить{}, // проходить в помещение
rus_verbs:глядеть{}, // глядеть в глаза
rus_verbs:пригласить{}, // пригласить в театр
rus_verbs:позвать{}, // позвать в класс
rus_verbs:усесться{}, // усесться в кресло
rus_verbs:поступить{}, // поступить в институт
rus_verbs:лечь{}, // лечь в постель
rus_verbs:поклониться{}, // поклониться в пояс
rus_verbs:потянуться{}, // потянуться в лес
rus_verbs:колоть{}, // колоть в ягодицу
rus_verbs:присесть{}, // присесть в кресло
rus_verbs:оглядеться{}, // оглядеться в зеркало
rus_verbs:поглядеть{}, // поглядеть в зеркало
rus_verbs:превратиться{}, // превратиться в лягушку
rus_verbs:принимать{}, // принимать во внимание
rus_verbs:звонить{}, // звонить в колокола
rus_verbs:привезти{}, // привезти в гостиницу
rus_verbs:рухнуть{}, // рухнуть в пропасть
rus_verbs:пускать{}, // пускать в дело
rus_verbs:отвести{}, // отвести в больницу
rus_verbs:сойти{}, // сойти в ад
rus_verbs:набрать{}, // набрать в команду
rus_verbs:собрать{}, // собрать в кулак
rus_verbs:двигаться{}, // двигаться в каюту
rus_verbs:падать{}, // падать в область нуля
rus_verbs:полезть{}, // полезть в драку
rus_verbs:направить{}, // направить в стационар
rus_verbs:приводить{}, // приводить в чувство
rus_verbs:толкнуть{}, // толкнуть в бок
rus_verbs:кинуться{}, // кинуться в драку
rus_verbs:ткнуть{}, // ткнуть в глаз
rus_verbs:заключить{}, // заключить в объятия
rus_verbs:подниматься{}, // подниматься в небо
rus_verbs:расти{}, // расти в глубину
rus_verbs:налить{}, // налить в кружку
rus_verbs:швырнуть{}, // швырнуть в бездну
rus_verbs:прыгнуть{}, // прыгнуть в дверь
rus_verbs:промолчать{}, // промолчать в тряпочку
rus_verbs:садиться{}, // садиться в кресло
rus_verbs:лить{}, // лить в кувшин
rus_verbs:дослать{}, // дослать деталь в держатель
rus_verbs:переслать{}, // переслать в обработчик
rus_verbs:удалиться{}, // удалиться в совещательную комнату
rus_verbs:разглядывать{}, // разглядывать в бинокль
rus_verbs:повесить{}, // повесить в шкаф
инфинитив:походить{ вид:соверш }, // походить в институт
глагол:походить{ вид:соверш },
деепричастие:походив{},
// прилагательное:походивший{вид:соверш},
rus_verbs:помчаться{}, // помчаться в класс
rus_verbs:свалиться{}, // свалиться в яму
rus_verbs:сбежать{}, // сбежать в Англию
rus_verbs:стрелять{}, // стрелять в цель
rus_verbs:обращать{}, // обращать в свою веру
rus_verbs:завести{}, // завести в дом
rus_verbs:приобрести{}, // приобрести в рассрочку
rus_verbs:сбросить{}, // сбросить в яму
rus_verbs:устроиться{}, // устроиться в крупную корпорацию
rus_verbs:погрузиться{}, // погрузиться в пучину
rus_verbs:течь{}, // течь в канаву
rus_verbs:произвести{}, // произвести в звание майора
rus_verbs:метать{}, // метать в цель
rus_verbs:пустить{}, // пустить в дело
rus_verbs:полететь{}, // полететь в Европу
rus_verbs:пропустить{}, // пропустить в здание
rus_verbs:рвануть{}, // рвануть в отпуск
rus_verbs:заходить{}, // заходить в каморку
rus_verbs:нырнуть{}, // нырнуть в прорубь
rus_verbs:рвануться{}, // рвануться в атаку
rus_verbs:приподняться{}, // приподняться в воздух
rus_verbs:превращаться{}, // превращаться в крупную величину
rus_verbs:прокричать{}, // прокричать в ухо
rus_verbs:записать{}, // записать в блокнот
rus_verbs:забраться{}, // забраться в шкаф
rus_verbs:приезжать{}, // приезжать в деревню
rus_verbs:продать{}, // продать в рабство
rus_verbs:проникнуть{}, // проникнуть в центр
rus_verbs:устремиться{}, // устремиться в открытое море
rus_verbs:посадить{}, // посадить в кресло
rus_verbs:упереться{}, // упереться в пол
rus_verbs:ринуться{}, // ринуться в буфет
rus_verbs:отдавать{}, // отдавать в кадетское училище
rus_verbs:отложить{}, // отложить в долгий ящик
rus_verbs:убежать{}, // убежать в приют
rus_verbs:оценить{}, // оценить в миллион долларов
rus_verbs:поднимать{}, // поднимать в стратосферу
rus_verbs:отослать{}, // отослать в квалификационную комиссию
rus_verbs:отодвинуть{}, // отодвинуть в дальний угол
rus_verbs:торопиться{}, // торопиться в школу
rus_verbs:попадаться{}, // попадаться в руки
rus_verbs:поразить{}, // поразить в самое сердце
rus_verbs:доставить{}, // доставить в квартиру
rus_verbs:заслать{}, // заслать в тыл
rus_verbs:сослать{}, // сослать в изгнание
rus_verbs:запустить{}, // запустить в космос
rus_verbs:удариться{}, // удариться в запой
rus_verbs:ударяться{}, // ударяться в крайность
rus_verbs:шептать{}, // шептать в лицо
rus_verbs:уронить{}, // уронить в унитаз
rus_verbs:прорычать{}, // прорычать в микрофон
rus_verbs:засунуть{}, // засунуть в глотку
rus_verbs:плыть{}, // плыть в открытое море
rus_verbs:перенести{}, // перенести в духовку
rus_verbs:светить{}, // светить в лицо
rus_verbs:мчаться{}, // мчаться в ремонт
rus_verbs:стукнуть{}, // стукнуть в лоб
rus_verbs:обрушиться{}, // обрушиться в котлован
rus_verbs:поглядывать{}, // поглядывать в экран
rus_verbs:уложить{}, // уложить в кроватку
инфинитив:попадать{ вид:несоверш }, // попадать в черный список
глагол:попадать{ вид:несоверш },
прилагательное:попадающий{ вид:несоверш },
прилагательное:попадавший{ вид:несоверш },
деепричастие:попадая{},
rus_verbs:провалиться{}, // провалиться в яму
rus_verbs:жаловаться{}, // жаловаться в комиссию
rus_verbs:опоздать{}, // опоздать в школу
rus_verbs:посылать{}, // посылать в парикмахерскую
rus_verbs:погнать{}, // погнать в хлев
rus_verbs:поступать{}, // поступать в институт
rus_verbs:усадить{}, // усадить в кресло
rus_verbs:проиграть{}, // проиграть в рулетку
rus_verbs:прилететь{}, // прилететь в страну
rus_verbs:повалиться{}, // повалиться в траву
rus_verbs:огрызнуться{}, // Собака огрызнулась в ответ
rus_verbs:лезть{}, // лезть в чужие дела
rus_verbs:потащить{}, // потащить в суд
rus_verbs:направляться{}, // направляться в порт
rus_verbs:поползти{}, // поползти в другую сторону
rus_verbs:пуститься{}, // пуститься в пляс
rus_verbs:забиться{}, // забиться в нору
rus_verbs:залезть{}, // залезть в конуру
rus_verbs:сдать{}, // сдать в утиль
rus_verbs:тронуться{}, // тронуться в путь
rus_verbs:сыграть{}, // сыграть в шахматы
rus_verbs:перевернуть{}, // перевернуть в более удобную позу
rus_verbs:сжимать{}, // сжимать пальцы в кулак
rus_verbs:подтолкнуть{}, // подтолкнуть в бок
rus_verbs:отнести{}, // отнести животное в лечебницу
rus_verbs:одеться{}, // одеться в зимнюю одежду
rus_verbs:плюнуть{}, // плюнуть в колодец
rus_verbs:передавать{}, // передавать в прокуратуру
rus_verbs:отскочить{}, // отскочить в лоб
rus_verbs:призвать{}, // призвать в армию
rus_verbs:увезти{}, // увезти в деревню
rus_verbs:улечься{}, // улечься в кроватку
rus_verbs:отшатнуться{}, // отшатнуться в сторону
rus_verbs:ложиться{}, // ложиться в постель
rus_verbs:пролететь{}, // пролететь в конец
rus_verbs:класть{}, // класть в сейф
rus_verbs:доставлять{}, // доставлять в кабинет
rus_verbs:приобретать{}, // приобретать в кредит
rus_verbs:сводить{}, // сводить в театр
rus_verbs:унести{}, // унести в могилу
rus_verbs:покатиться{}, // покатиться в яму
rus_verbs:сходить{}, // сходить в магазинчик
rus_verbs:спустить{}, // спустить в канализацию
rus_verbs:проникать{}, // проникать в сердцевину
rus_verbs:метнуть{}, // метнуть в болвана гневный взгляд
rus_verbs:пожаловаться{}, // пожаловаться в администрацию
rus_verbs:стучать{}, // стучать в металлическую дверь
rus_verbs:тащить{}, // тащить в ремонт
rus_verbs:заглядывать{}, // заглядывать в ответы
rus_verbs:плюхнуться{}, // плюхнуться в стол ароматного сена
rus_verbs:увести{}, // увести в следующий кабинет
rus_verbs:успевать{}, // успевать в школу
rus_verbs:пробраться{}, // пробраться в собачью конуру
rus_verbs:подавать{}, // подавать в суд
rus_verbs:прибежать{}, // прибежать в конюшню
rus_verbs:рассмотреть{}, // рассмотреть в микроскоп
rus_verbs:пнуть{}, // пнуть в живот
rus_verbs:завернуть{}, // завернуть в декоративную пленку
rus_verbs:уезжать{}, // уезжать в деревню
rus_verbs:привлекать{}, // привлекать в свои ряды
rus_verbs:перебраться{}, // перебраться в прибрежный город
rus_verbs:долить{}, // долить в коктейль
rus_verbs:палить{}, // палить в нападающих
rus_verbs:отобрать{}, // отобрать в коллекцию
rus_verbs:улететь{}, // улететь в неизвестность
rus_verbs:выглянуть{}, // выглянуть в окно
rus_verbs:выглядывать{}, // выглядывать в окно
rus_verbs:пробираться{}, // грабитель, пробирающийся в дом
инфинитив:написать{ aux stress="напис^ать"}, // читатель, написавший в блог
глагол:написать{ aux stress="напис^ать"},
прилагательное:написавший{ aux stress="напис^авший"},
rus_verbs:свернуть{}, // свернуть в колечко
инфинитив:сползать{ вид:несоверш }, // сползать в овраг
глагол:сползать{ вид:несоверш },
прилагательное:сползающий{ вид:несоверш },
прилагательное:сползавший{ вид:несоверш },
rus_verbs:барабанить{}, // барабанить в дверь
rus_verbs:дописывать{}, // дописывать в конец
rus_verbs:меняться{}, // меняться в лучшую сторону
rus_verbs:измениться{}, // измениться в лучшую сторону
rus_verbs:изменяться{}, // изменяться в лучшую сторону
rus_verbs:вписаться{}, // вписаться в поворот
rus_verbs:вписываться{}, // вписываться в повороты
rus_verbs:переработать{}, // переработать в удобрение
rus_verbs:перерабатывать{}, // перерабатывать в удобрение
rus_verbs:уползать{}, // уползать в тень
rus_verbs:заползать{}, // заползать в нору
rus_verbs:перепрятать{}, // перепрятать в укромное место
rus_verbs:заталкивать{}, // заталкивать в вагон
rus_verbs:преобразовывать{}, // преобразовывать в список
инфинитив:конвертировать{ вид:несоверш }, // конвертировать в список
глагол:конвертировать{ вид:несоверш },
инфинитив:конвертировать{ вид:соверш },
глагол:конвертировать{ вид:соверш },
деепричастие:конвертировав{},
деепричастие:конвертируя{},
rus_verbs:изорвать{}, // Он изорвал газету в клочки.
rus_verbs:выходить{}, // Окна выходят в сад.
rus_verbs:говорить{}, // Он говорил в защиту своего отца.
rus_verbs:вырастать{}, // Он вырастает в большого художника.
rus_verbs:вывести{}, // Он вывел детей в сад.
// инфинитив:всыпать{ вид:соверш }, инфинитив:всыпать{ вид:несоверш },
// глагол:всыпать{ вид:соверш }, глагол:всыпать{ вид:несоверш }, // Он всыпал в воду две ложки соли.
// прилагательное:раненый{}, // Он был ранен в левую руку.
// прилагательное:одетый{}, // Он был одет в толстое осеннее пальто.
rus_verbs:бухнуться{}, // Он бухнулся в воду.
rus_verbs:склонять{}, // склонять защиту в свою пользу
rus_verbs:впиться{}, // Пиявка впилась в тело.
rus_verbs:сходиться{}, // Интеллигенты начала века часто сходились в разные союзы
rus_verbs:сохранять{}, // сохранить данные в файл
rus_verbs:собирать{}, // собирать игрушки в ящик
rus_verbs:упаковывать{}, // упаковывать вещи в чемодан
rus_verbs:обращаться{}, // Обращайтесь ко мне в любое время
rus_verbs:стрельнуть{}, // стрельни в толпу!
rus_verbs:пулять{}, // пуляй в толпу
rus_verbs:пульнуть{}, // пульни в толпу
rus_verbs:становиться{}, // Становитесь в очередь.
rus_verbs:вписать{}, // Юля вписала свое имя в список.
rus_verbs:вписывать{}, // Мы вписывали свои имена в список
прилагательное:видный{}, // Планета Марс видна в обычный бинокль
rus_verbs:пойти{}, // Девочка рано пошла в школу
rus_verbs:отойти{}, // Эти обычаи отошли в историю.
rus_verbs:бить{}, // Холодный ветер бил ему в лицо.
rus_verbs:входить{}, // Это входит в его обязанности.
rus_verbs:принять{}, // меня приняли в пионеры
rus_verbs:уйти{}, // Правительство РФ ушло в отставку
rus_verbs:допустить{}, // Япония была допущена в Организацию Объединённых Наций в 1956 году.
rus_verbs:посвятить{}, // Я посвятил друга в свою тайну.
инфинитив:экспортировать{ вид:несоверш }, глагол:экспортировать{ вид:несоверш }, // экспортировать нефть в страны Востока
rus_verbs:взглянуть{}, // Я не смел взглянуть ему в глаза.
rus_verbs:идти{}, // Я иду гулять в парк.
rus_verbs:вскочить{}, // Я вскочил в трамвай и помчался в институт.
rus_verbs:получить{}, // Эту мебель мы получили в наследство от родителей.
rus_verbs:везти{}, // Учитель везёт детей в лагерь.
rus_verbs:качать{}, // Судно качает во все стороны.
rus_verbs:заезжать{}, // Сегодня вечером я заезжал в магазин за книгами.
rus_verbs:связать{}, // Свяжите свои вещи в узелок.
rus_verbs:пронести{}, // Пронесите стол в дверь.
rus_verbs:вынести{}, // Надо вынести примечания в конец.
rus_verbs:устроить{}, // Она устроила сына в школу.
rus_verbs:угодить{}, // Она угодила головой в дверь.
rus_verbs:отвернуться{}, // Она резко отвернулась в сторону.
rus_verbs:рассматривать{}, // Она рассматривала сцену в бинокль.
rus_verbs:обратить{}, // Война обратила город в развалины.
rus_verbs:сойтись{}, // Мы сошлись в школьные годы.
rus_verbs:приехать{}, // Мы приехали в положенный час.
rus_verbs:встать{}, // Дети встали в круг.
rus_verbs:впасть{}, // Из-за болезни он впал в нужду.
rus_verbs:придти{}, // придти в упадок
rus_verbs:заявить{}, // Надо заявить в милицию о краже.
rus_verbs:заявлять{}, // заявлять в полицию
rus_verbs:ехать{}, // Мы будем ехать в Орёл
rus_verbs:окрашиваться{}, // окрашиваться в красный цвет
rus_verbs:решить{}, // Дело решено в пользу истца.
rus_verbs:сесть{}, // Она села в кресло
rus_verbs:посмотреть{}, // Она посмотрела на себя в зеркало.
rus_verbs:влезать{}, // он влезает в мою квартирку
rus_verbs:попасться{}, // в мою ловушку попалась мышь
rus_verbs:лететь{}, // Мы летим в Орёл
ГЛ_ИНФ(брать), // он берет в свою правую руку очень тяжелый шершавый камень
ГЛ_ИНФ(взять), // Коля взял в руку камень
ГЛ_ИНФ(поехать), // поехать в круиз
ГЛ_ИНФ(подать), // подать в отставку
инфинитив:засыпать{ вид:соверш }, глагол:засыпать{ вид:соверш }, // засыпать песок в ящик
инфинитив:засыпать{ вид:несоверш переходность:переходный }, глагол:засыпать{ вид:несоверш переходность:переходный }, // засыпать песок в ящик
ГЛ_ИНФ(впадать), прилагательное:впадающий{}, прилагательное:впадавший{}, деепричастие:впадая{}, // впадать в море
ГЛ_ИНФ(постучать) // постучать в дверь
}
// Чтобы разрешить связывание в паттернах типа: уйти в BEA Systems
fact гл_предл
{
if context { Гл_В_Вин предлог:в{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_В_Вин предлог:в{} *:*{ падеж:вин } }
then return true
}
fact гл_предл
{
if context { глагол:подвывать{} предлог:в{} существительное:такт{ падеж:вин } }
then return true
}
#endregion Винительный
// Все остальные варианты по умолчанию запрещаем.
fact гл_предл
{
if context { * предлог:в{} *:*{ падеж:предл } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:в{} *:*{ падеж:мест } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:в{} *:*{ падеж:вин } }
then return false,-4
}
fact гл_предл
{
if context { * предлог:в{} * }
then return false,-5
}
#endregion Предлог_В
#region Предлог_НА
// ------------------- С ПРЕДЛОГОМ 'НА' ---------------------------
#region ПРЕДЛОЖНЫЙ
// НА+предложный падеж:
// ЛЕЖАТЬ НА СТОЛЕ
#region VerbList
wordentry_set Гл_НА_Предл=
{
rus_verbs:заслушать{}, // Вопрос заслушали на сессии облсовета
rus_verbs:ПРОСТУПАТЬ{}, // На лбу, носу и щеке проступало черное пятно кровоподтека. (ПРОСТУПАТЬ/ПРОСТУПИТЬ)
rus_verbs:ПРОСТУПИТЬ{}, //
rus_verbs:ВИДНЕТЬСЯ{}, // На другой стороне Океана виднелась полоска суши, окружавшая нижний ярус планеты. (ВИДНЕТЬСЯ)
rus_verbs:ЗАВИСАТЬ{}, // Машина умела зависать в воздухе на любой высоте (ЗАВИСАТЬ)
rus_verbs:ЗАМЕРЕТЬ{}, // Скользнув по траве, он замер на боку (ЗАМЕРЕТЬ, локатив)
rus_verbs:ЗАМИРАТЬ{}, //
rus_verbs:ЗАКРЕПИТЬ{}, // Он вручил ей лишний кинжал, который она воткнула в рубаху и закрепила на подоле. (ЗАКРЕПИТЬ)
rus_verbs:УПОЛЗТИ{}, // Зверь завизжал и попытался уползти на двух невредимых передних ногах. (УПОЛЗТИ/УПОЛЗАТЬ)
rus_verbs:УПОЛЗАТЬ{}, //
rus_verbs:БОЛТАТЬСЯ{}, // Тело его будет болтаться на пространственных ветрах, пока не сгниет веревка. (БОЛТАТЬСЯ)
rus_verbs:РАЗВЕРНУТЬ{}, // Филиппины разрешат США развернуть военные базы на своей территории (РАЗВЕРНУТЬ)
rus_verbs:ПОЛУЧИТЬ{}, // Я пытался узнать секреты и получить советы на официальном русскоязычном форуме (ПОЛУЧИТЬ)
rus_verbs:ЗАСИЯТЬ{}, // Он активировал управление, и на экране снова засияло изображение полумесяца. (ЗАСИЯТЬ)
rus_verbs:ВЗОРВАТЬСЯ{}, // Смертник взорвался на предвыборном митинге в Пакистане (ВЗОРВАТЬСЯ)
rus_verbs:искриться{},
rus_verbs:ОДЕРЖИВАТЬ{}, // На выборах в иранский парламент победу одерживают противники действующего президента (ОДЕРЖИВАТЬ)
rus_verbs:ПРЕСЕЧЬ{}, // На Украине пресекли дерзкий побег заключенных на вертолете (ПРЕСЕЧЬ)
rus_verbs:УЛЕТЕТЬ{}, // Голый норвежец улетел на лыжах с трамплина на 60 метров (УЛЕТЕТЬ)
rus_verbs:ПРОХОДИТЬ{}, // укрывающийся в лесу американский подросток проходил инициацию на охоте, выпив кружку крови первого убитого им оленя (ПРОХОДИТЬ)
rus_verbs:СУЩЕСТВОВАТЬ{}, // На Марсе существовали условия для жизни (СУЩЕСТВОВАТЬ)
rus_verbs:УКАЗАТЬ{}, // Победу в Лиге чемпионов укажут на часах (УКАЗАТЬ)
rus_verbs:отвести{}, // отвести душу на людях
rus_verbs:сходиться{}, // Оба профессора сходились на том, что в черепной коробке динозавра
rus_verbs:сойтись{},
rus_verbs:ОБНАРУЖИТЬ{}, // Доказательство наличия подповерхностного океана на Европе обнаружено на её поверхности (ОБНАРУЖИТЬ)
rus_verbs:НАБЛЮДАТЬСЯ{}, // Редкий зодиакальный свет вскоре будет наблюдаться на ночном небе (НАБЛЮДАТЬСЯ)
rus_verbs:ДОСТИГНУТЬ{}, // На всех аварийных реакторах достигнуто состояние так называемой холодной остановки (ДОСТИГНУТЬ/ДОСТИЧЬ)
глагол:ДОСТИЧЬ{},
инфинитив:ДОСТИЧЬ{},
rus_verbs:завершить{}, // Российские биатлонисты завершили чемпионат мира на мажорной ноте
rus_verbs:РАСКЛАДЫВАТЬ{},
rus_verbs:ФОКУСИРОВАТЬСЯ{}, // Инвесторы предпочитают фокусироваться на среднесрочных ожиданиях (ФОКУСИРОВАТЬСЯ)
rus_verbs:ВОСПРИНИМАТЬ{}, // как несерьезно воспринимали его на выборах мэра (ВОСПРИНИМАТЬ)
rus_verbs:БУШЕВАТЬ{}, // на территории Тверской области бушевала гроза , в результате которой произошло отключение электроснабжения в ряде муниципальных образований региона (БУШЕВАТЬ)
rus_verbs:УЧАСТИТЬСЯ{}, // В последние месяцы в зоне ответственности бундесвера на севере Афганистана участились случаи обстрелов полевых лагерей немецких миротворцев (УЧАСТИТЬСЯ)
rus_verbs:ВЫИГРАТЬ{}, // Почему женская сборная России не может выиграть медаль на чемпионате мира (ВЫИГРАТЬ)
rus_verbs:ПРОПАСТЬ{}, // Пропавшим на прогулке актером заинтересовались следователи (ПРОПАСТЬ)
rus_verbs:УБИТЬ{}, // Силовики убили двух боевиков на административной границе Ингушетии и Чечни (УБИТЬ)
rus_verbs:подпрыгнуть{}, // кобель нелепо подпрыгнул на трех ногах , а его хозяин отправил струю пива мимо рта
rus_verbs:подпрыгивать{},
rus_verbs:высветиться{}, // на компьютере высветится твоя подпись
rus_verbs:фигурировать{}, // его портрет фигурирует на страницах печати и телеэкранах
rus_verbs:действовать{}, // выявленный контрабандный канал действовал на постоянной основе
rus_verbs:СОХРАНИТЬСЯ{}, // На рынке международных сделок IPO сохранится высокая активность (СОХРАНИТЬСЯ НА)
rus_verbs:ПРОЙТИ{}, // Необычный конкурс прошёл на севере Швеции (ПРОЙТИ НА предл)
rus_verbs:НАЧАТЬСЯ{}, // На северо-востоке США началась сильная снежная буря. (НАЧАТЬСЯ НА предл)
rus_verbs:ВОЗНИКНУТЬ{}, // Конфликт возник на почве совместной коммерческой деятельности по выращиванию овощей и зелени (ВОЗНИКНУТЬ НА)
rus_verbs:СВЕТИТЬСЯ{}, // она по-прежнему светится на лицах людей (СВЕТИТЬСЯ НА предл)
rus_verbs:ОРГАНИЗОВАТЬ{}, // Власти Москвы намерены организовать масленичные гуляния на 100 площадках (ОРГАНИЗОВАТЬ НА предл)
rus_verbs:ИМЕТЬ{}, // Имея власть на низовом уровне, оказывать самое непосредственное и определяющее влияние на верховную власть (ИМЕТЬ НА предл)
rus_verbs:ОПРОБОВАТЬ{}, // Опробовать и отточить этот инструмент на местных и региональных выборах (ОПРОБОВАТЬ, ОТТОЧИТЬ НА предл)
rus_verbs:ОТТОЧИТЬ{},
rus_verbs:ДОЛОЖИТЬ{}, // Участникам совещания предложено подготовить по этому вопросу свои предложения и доложить на повторной встрече (ДОЛОЖИТЬ НА предл)
rus_verbs:ОБРАЗОВЫВАТЬСЯ{}, // Солевые и пылевые бури , образующиеся на поверхности обнаженной площади моря , уничтожают урожаи и растительность (ОБРАЗОВЫВАТЬСЯ НА)
rus_verbs:СОБРАТЬ{}, // использует собранные на местном рынке депозиты (СОБРАТЬ НА предл)
инфинитив:НАХОДИТЬСЯ{ вид:несоверш}, // находившихся на борту самолета (НАХОДИТЬСЯ НА предл)
глагол:НАХОДИТЬСЯ{ вид:несоверш },
прилагательное:находившийся{ вид:несоверш },
прилагательное:находящийся{ вид:несоверш },
деепричастие:находясь{},
rus_verbs:ГОТОВИТЬ{}, // пищу готовят сами на примусах (ГОТОВИТЬ НА предл)
rus_verbs:РАЗДАТЬСЯ{}, // Они сообщили о сильном хлопке , который раздался на территории нефтебазы (РАЗДАТЬСЯ НА)
rus_verbs:ПОДСКАЛЬЗЫВАТЬСЯ{}, // подскальзываться на той же апельсиновой корке (ПОДСКАЛЬЗЫВАТЬСЯ НА)
rus_verbs:СКРЫТЬСЯ{}, // Германия: латвиец ограбил магазин и попытался скрыться на такси (СКРЫТЬСЯ НА предл)
rus_verbs:ВЫРАСТИТЬ{}, // Пациенту вырастили новый нос на руке (ВЫРАСТИТЬ НА)
rus_verbs:ПРОДЕМОНСТРИРОВАТЬ{}, // Они хотят подчеркнуть эмоциональную тонкость оппозиционера и на этом фоне продемонстрировать бездушность российской власти (ПРОДЕМОНСТРИРОВАТЬ НА предл)
rus_verbs:ОСУЩЕСТВЛЯТЬСЯ{}, // первичный анализ смеси запахов может осуществляться уже на уровне рецепторных нейронов благодаря механизму латерального торможения (ОСУЩЕСТВЛЯТЬСЯ НА)
rus_verbs:ВЫДЕЛЯТЬСЯ{}, // Ягоды брусники, резко выделяющиеся своим красным цветом на фоне зелёной листвы, поедаются животными и птицами (ВЫДЕЛЯТЬСЯ НА)
rus_verbs:РАСКРЫТЬ{}, // На Украине раскрыто крупное мошенничество в сфере туризма (РАСКРЫТЬ НА)
rus_verbs:ОБЖАРИВАТЬСЯ{}, // Омлет обжаривается на сливочном масле с одной стороны, пока он почти полностью не загустеет (ОБЖАРИВАТЬСЯ НА)
rus_verbs:ПРИГОТОВЛЯТЬ{}, // Яичница — блюдо европейской кухни, приготовляемое на сковороде из разбитых яиц (ПРИГОТОВЛЯТЬ НА)
rus_verbs:РАССАДИТЬ{}, // Женька рассадил игрушки на скамеечке (РАССАДИТЬ НА)
rus_verbs:ОБОЖДАТЬ{}, // обожди Анжелу на остановке троллейбуса (ОБОЖДАТЬ НА)
rus_verbs:УЧИТЬСЯ{}, // Марина учится на факультете журналистики (УЧИТЬСЯ НА предл)
rus_verbs:раскладываться{}, // Созревшие семенные экземпляры раскладывают на солнце или в теплом месте, где они делаются мягкими (РАСКЛАДЫВАТЬСЯ В, НА)
rus_verbs:ПОСЛУШАТЬ{}, // Послушайте друзей и врагов на расстоянии! (ПОСЛУШАТЬ НА)
rus_verbs:ВЕСТИСЬ{}, // На стороне противника всю ночь велась перегруппировка сил. (ВЕСТИСЬ НА)
rus_verbs:ПОИНТЕРЕСОВАТЬСЯ{}, // корреспондент поинтересовался у людей на улице (ПОИНТЕРЕСОВАТЬСЯ НА)
rus_verbs:ОТКРЫВАТЬСЯ{}, // Российские биржи открываются на негативном фоне (ОТКРЫВАТЬСЯ НА)
rus_verbs:СХОДИТЬ{}, // Вы сходите на следующей остановке? (СХОДИТЬ НА)
rus_verbs:ПОГИБНУТЬ{}, // Её отец погиб на войне. (ПОГИБНУТЬ НА)
rus_verbs:ВЫЙТИ{}, // Книга выйдет на будущей неделе. (ВЫЙТИ НА предл)
rus_verbs:НЕСТИСЬ{}, // Корабль несётся на всех парусах. (НЕСТИСЬ НА предл)
rus_verbs:вкалывать{}, // Папа вкалывает на работе, чтобы прокормить семью (вкалывать на)
rus_verbs:доказать{}, // разработчики доказали на практике применимость данного подхода к обсчету сцен (доказать на, применимость к)
rus_verbs:хулиганить{}, // дозволять кому-то хулиганить на кладбище (хулиганить на)
глагол:вычитать{вид:соверш}, инфинитив:вычитать{вид:соверш}, // вычитать на сайте (вычитать на сайте)
деепричастие:вычитав{},
rus_verbs:аккомпанировать{}, // он аккомпанировал певцу на губной гармошке (аккомпанировать на)
rus_verbs:набрать{}, // статья с заголовком, набранным на компьютере
rus_verbs:сделать{}, // книга с иллюстрацией, сделанной на компьютере
rus_verbs:развалиться{}, // Антонио развалился на диване
rus_verbs:улечься{}, // Антонио улегся на полу
rus_verbs:зарубить{}, // Заруби себе на носу.
rus_verbs:ценить{}, // Его ценят на заводе.
rus_verbs:вернуться{}, // Отец вернулся на закате.
rus_verbs:шить{}, // Вы умеете шить на машинке?
rus_verbs:бить{}, // Скот бьют на бойне.
rus_verbs:выехать{}, // Мы выехали на рассвете.
rus_verbs:валяться{}, // На полу валяется бумага.
rus_verbs:разложить{}, // она разложила полотенце на песке
rus_verbs:заниматься{}, // я занимаюсь на тренажере
rus_verbs:позаниматься{},
rus_verbs:порхать{}, // порхать на лугу
rus_verbs:пресекать{}, // пресекать на корню
rus_verbs:изъясняться{}, // изъясняться на непонятном языке
rus_verbs:развесить{}, // развесить на столбах
rus_verbs:обрасти{}, // обрасти на южной части
rus_verbs:откладываться{}, // откладываться на стенках артерий
rus_verbs:уносить{}, // уносить на носилках
rus_verbs:проплыть{}, // проплыть на плоту
rus_verbs:подъезжать{}, // подъезжать на повозках
rus_verbs:пульсировать{}, // пульсировать на лбу
rus_verbs:рассесться{}, // птицы расселись на ветках
rus_verbs:застопориться{}, // застопориться на первом пункте
rus_verbs:изловить{}, // изловить на окраинах
rus_verbs:покататься{}, // покататься на машинках
rus_verbs:залопотать{}, // залопотать на неизвестном языке
rus_verbs:растягивать{}, // растягивать на станке
rus_verbs:поделывать{}, // поделывать на пляже
rus_verbs:подстеречь{}, // подстеречь на площадке
rus_verbs:проектировать{}, // проектировать на компьютере
rus_verbs:притулиться{}, // притулиться на кушетке
rus_verbs:дозволять{}, // дозволять кому-то хулиганить на кладбище
rus_verbs:пострелять{}, // пострелять на испытательном полигоне
rus_verbs:засиживаться{}, // засиживаться на работе
rus_verbs:нежиться{}, // нежиться на солнышке
rus_verbs:притомиться{}, // притомиться на рабочем месте
rus_verbs:поселяться{}, // поселяться на чердаке
rus_verbs:потягиваться{}, // потягиваться на земле
rus_verbs:отлеживаться{}, // отлеживаться на койке
rus_verbs:протаранить{}, // протаранить на танке
rus_verbs:гарцевать{}, // гарцевать на коне
rus_verbs:облупиться{}, // облупиться на носу
rus_verbs:оговорить{}, // оговорить на собеседовании
rus_verbs:зарегистрироваться{}, // зарегистрироваться на сайте
rus_verbs:отпечатать{}, // отпечатать на картоне
rus_verbs:сэкономить{}, // сэкономить на мелочах
rus_verbs:покатать{}, // покатать на пони
rus_verbs:колесить{}, // колесить на старой машине
rus_verbs:понастроить{}, // понастроить на участках
rus_verbs:поджарить{}, // поджарить на костре
rus_verbs:узнаваться{}, // узнаваться на фотографии
rus_verbs:отощать{}, // отощать на казенных харчах
rus_verbs:редеть{}, // редеть на макушке
rus_verbs:оглашать{}, // оглашать на общем собрании
rus_verbs:лопотать{}, // лопотать на иврите
rus_verbs:пригреть{}, // пригреть на груди
rus_verbs:консультироваться{}, // консультироваться на форуме
rus_verbs:приноситься{}, // приноситься на одежде
rus_verbs:сушиться{}, // сушиться на балконе
rus_verbs:наследить{}, // наследить на полу
rus_verbs:нагреться{}, // нагреться на солнце
rus_verbs:рыбачить{}, // рыбачить на озере
rus_verbs:прокатить{}, // прокатить на выборах
rus_verbs:запинаться{}, // запинаться на ровном месте
rus_verbs:отрубиться{}, // отрубиться на мягкой подушке
rus_verbs:заморозить{}, // заморозить на улице
rus_verbs:промерзнуть{}, // промерзнуть на открытом воздухе
rus_verbs:просохнуть{}, // просохнуть на батарее
rus_verbs:развозить{}, // развозить на велосипеде
rus_verbs:прикорнуть{}, // прикорнуть на диванчике
rus_verbs:отпечататься{}, // отпечататься на коже
rus_verbs:выявлять{}, // выявлять на таможне
rus_verbs:расставлять{}, // расставлять на башнях
rus_verbs:прокрутить{}, // прокрутить на пальце
rus_verbs:умываться{}, // умываться на улице
rus_verbs:пересказывать{}, // пересказывать на страницах романа
rus_verbs:удалять{}, // удалять на пуховике
rus_verbs:хозяйничать{}, // хозяйничать на складе
rus_verbs:оперировать{}, // оперировать на поле боя
rus_verbs:поносить{}, // поносить на голове
rus_verbs:замурлыкать{}, // замурлыкать на коленях
rus_verbs:передвигать{}, // передвигать на тележке
rus_verbs:прочертить{}, // прочертить на земле
rus_verbs:колдовать{}, // колдовать на кухне
rus_verbs:отвозить{}, // отвозить на казенном транспорте
rus_verbs:трахать{}, // трахать на природе
rus_verbs:мастерить{}, // мастерить на кухне
rus_verbs:ремонтировать{}, // ремонтировать на коленке
rus_verbs:развезти{}, // развезти на велосипеде
rus_verbs:робеть{}, // робеть на сцене
инфинитив:реализовать{ вид:несоверш }, инфинитив:реализовать{ вид:соверш }, // реализовать на сайте
глагол:реализовать{ вид:несоверш }, глагол:реализовать{ вид:соверш },
деепричастие:реализовав{}, деепричастие:реализуя{},
rus_verbs:покаяться{}, // покаяться на смертном одре
rus_verbs:специализироваться{}, // специализироваться на тестировании
rus_verbs:попрыгать{}, // попрыгать на батуте
rus_verbs:переписывать{}, // переписывать на столе
rus_verbs:расписывать{}, // расписывать на доске
rus_verbs:зажимать{}, // зажимать на запястье
rus_verbs:практиковаться{}, // практиковаться на мышах
rus_verbs:уединиться{}, // уединиться на чердаке
rus_verbs:подохнуть{}, // подохнуть на чужбине
rus_verbs:приподниматься{}, // приподниматься на руках
rus_verbs:уродиться{}, // уродиться на полях
rus_verbs:продолжиться{}, // продолжиться на улице
rus_verbs:посапывать{}, // посапывать на диване
rus_verbs:ободрать{}, // ободрать на спине
rus_verbs:скрючиться{}, // скрючиться на песке
rus_verbs:тормознуть{}, // тормознуть на перекрестке
rus_verbs:лютовать{}, // лютовать на хуторе
rus_verbs:зарегистрировать{}, // зарегистрировать на сайте
rus_verbs:переждать{}, // переждать на вершине холма
rus_verbs:доминировать{}, // доминировать на территории
rus_verbs:публиковать{}, // публиковать на сайте
rus_verbs:морщить{}, // морщить на лбу
rus_verbs:сконцентрироваться{}, // сконцентрироваться на главном
rus_verbs:подрабатывать{}, // подрабатывать на рынке
rus_verbs:репетировать{}, // репетировать на заднем дворе
rus_verbs:подвернуть{}, // подвернуть на брусчатке
rus_verbs:зашелестеть{}, // зашелестеть на ветру
rus_verbs:расчесывать{}, // расчесывать на спине
rus_verbs:одевать{}, // одевать на рынке
rus_verbs:испечь{}, // испечь на углях
rus_verbs:сбрить{}, // сбрить на затылке
rus_verbs:согреться{}, // согреться на печке
rus_verbs:замаячить{}, // замаячить на горизонте
rus_verbs:пересчитывать{}, // пересчитывать на пальцах
rus_verbs:галдеть{}, // галдеть на крыльце
rus_verbs:переплыть{}, // переплыть на плоту
rus_verbs:передохнуть{}, // передохнуть на скамейке
rus_verbs:прижиться{}, // прижиться на ферме
rus_verbs:переправляться{}, // переправляться на плотах
rus_verbs:накупить{}, // накупить на блошином рынке
rus_verbs:проторчать{}, // проторчать на виду
rus_verbs:мокнуть{}, // мокнуть на улице
rus_verbs:застукать{}, // застукать на камбузе
rus_verbs:завязывать{}, // завязывать на ботинках
rus_verbs:повисать{}, // повисать на ветке
rus_verbs:подвизаться{}, // подвизаться на государственной службе
rus_verbs:кормиться{}, // кормиться на болоте
rus_verbs:покурить{}, // покурить на улице
rus_verbs:зимовать{}, // зимовать на болотах
rus_verbs:застегивать{}, // застегивать на гимнастерке
rus_verbs:поигрывать{}, // поигрывать на гитаре
rus_verbs:погореть{}, // погореть на махинациях с землей
rus_verbs:кувыркаться{}, // кувыркаться на батуте
rus_verbs:похрапывать{}, // похрапывать на диване
rus_verbs:пригревать{}, // пригревать на груди
rus_verbs:завязнуть{}, // завязнуть на болоте
rus_verbs:шастать{}, // шастать на втором этаже
rus_verbs:заночевать{}, // заночевать на сеновале
rus_verbs:отсиживаться{}, // отсиживаться на чердаке
rus_verbs:мчать{}, // мчать на байке
rus_verbs:сгнить{}, // сгнить на урановых рудниках
rus_verbs:тренировать{}, // тренировать на манекенах
rus_verbs:повеселиться{}, // повеселиться на празднике
rus_verbs:измучиться{}, // измучиться на болоте
rus_verbs:увянуть{}, // увянуть на подоконнике
rus_verbs:раскрутить{}, // раскрутить на оси
rus_verbs:выцвести{}, // выцвести на солнечном свету
rus_verbs:изготовлять{}, // изготовлять на коленке
rus_verbs:гнездиться{}, // гнездиться на вершине дерева
rus_verbs:разогнаться{}, // разогнаться на мотоцикле
rus_verbs:излагаться{}, // излагаться на страницах доклада
rus_verbs:сконцентрировать{}, // сконцентрировать на левом фланге
rus_verbs:расчесать{}, // расчесать на макушке
rus_verbs:плавиться{}, // плавиться на солнце
rus_verbs:редактировать{}, // редактировать на ноутбуке
rus_verbs:подскакивать{}, // подскакивать на месте
rus_verbs:покупаться{}, // покупаться на рынке
rus_verbs:промышлять{}, // промышлять на мелководье
rus_verbs:приобретаться{}, // приобретаться на распродажах
rus_verbs:наигрывать{}, // наигрывать на банджо
rus_verbs:маневрировать{}, // маневрировать на флангах
rus_verbs:запечатлеться{}, // запечатлеться на записях камер
rus_verbs:укрывать{}, // укрывать на чердаке
rus_verbs:подорваться{}, // подорваться на фугасе
rus_verbs:закрепиться{}, // закрепиться на занятых позициях
rus_verbs:громыхать{}, // громыхать на кухне
инфинитив:подвигаться{ вид:соверш }, глагол:подвигаться{ вид:соверш }, // подвигаться на полу
деепричастие:подвигавшись{},
rus_verbs:добываться{}, // добываться на территории Анголы
rus_verbs:приплясывать{}, // приплясывать на сцене
rus_verbs:доживать{}, // доживать на больничной койке
rus_verbs:отпраздновать{}, // отпраздновать на работе
rus_verbs:сгубить{}, // сгубить на корню
rus_verbs:схоронить{}, // схоронить на кладбище
rus_verbs:тускнеть{}, // тускнеть на солнце
rus_verbs:скопить{}, // скопить на счету
rus_verbs:помыть{}, // помыть на своем этаже
rus_verbs:пороть{}, // пороть на конюшне
rus_verbs:наличествовать{}, // наличествовать на складе
rus_verbs:нащупывать{}, // нащупывать на полке
rus_verbs:змеиться{}, // змеиться на дне
rus_verbs:пожелтеть{}, // пожелтеть на солнце
rus_verbs:заостриться{}, // заостриться на конце
rus_verbs:свезти{}, // свезти на поле
rus_verbs:прочувствовать{}, // прочувствовать на своей шкуре
rus_verbs:подкрутить{}, // подкрутить на приборной панели
rus_verbs:рубиться{}, // рубиться на мечах
rus_verbs:сиживать{}, // сиживать на крыльце
rus_verbs:тараторить{}, // тараторить на иностранном языке
rus_verbs:теплеть{}, // теплеть на сердце
rus_verbs:покачаться{}, // покачаться на ветке
rus_verbs:сосредоточиваться{}, // сосредоточиваться на главной задаче
rus_verbs:развязывать{}, // развязывать на ботинках
rus_verbs:подвозить{}, // подвозить на мотороллере
rus_verbs:вышивать{}, // вышивать на рубашке
rus_verbs:скупать{}, // скупать на открытом рынке
rus_verbs:оформлять{}, // оформлять на встрече
rus_verbs:распускаться{}, // распускаться на клумбах
rus_verbs:прогореть{}, // прогореть на спекуляциях
rus_verbs:приползти{}, // приползти на коленях
rus_verbs:загореть{}, // загореть на пляже
rus_verbs:остудить{}, // остудить на балконе
rus_verbs:нарвать{}, // нарвать на поляне
rus_verbs:издохнуть{}, // издохнуть на болоте
rus_verbs:разгружать{}, // разгружать на дороге
rus_verbs:произрастать{}, // произрастать на болотах
rus_verbs:разуться{}, // разуться на коврике
rus_verbs:сооружать{}, // сооружать на площади
rus_verbs:зачитывать{}, // зачитывать на митинге
rus_verbs:уместиться{}, // уместиться на ладони
rus_verbs:закупить{}, // закупить на рынке
rus_verbs:горланить{}, // горланить на улице
rus_verbs:экономить{}, // экономить на спичках
rus_verbs:исправлять{}, // исправлять на доске
rus_verbs:расслабляться{}, // расслабляться на лежаке
rus_verbs:скапливаться{}, // скапливаться на крыше
rus_verbs:сплетничать{}, // сплетничать на скамеечке
rus_verbs:отъезжать{}, // отъезжать на лимузине
rus_verbs:отчитывать{}, // отчитывать на собрании
rus_verbs:сфокусировать{}, // сфокусировать на удаленной точке
rus_verbs:потчевать{}, // потчевать на лаврах
rus_verbs:окопаться{}, // окопаться на окраине
rus_verbs:загорать{}, // загорать на пляже
rus_verbs:обгореть{}, // обгореть на солнце
rus_verbs:распознавать{}, // распознавать на фотографии
rus_verbs:заплетаться{}, // заплетаться на макушке
rus_verbs:перегреться{}, // перегреться на жаре
rus_verbs:подметать{}, // подметать на крыльце
rus_verbs:нарисоваться{}, // нарисоваться на горизонте
rus_verbs:проскакивать{}, // проскакивать на экране
rus_verbs:попивать{}, // попивать на балконе чай
rus_verbs:отплывать{}, // отплывать на лодке
rus_verbs:чирикать{}, // чирикать на ветках
rus_verbs:скупить{}, // скупить на оптовых базах
rus_verbs:наколоть{}, // наколоть на коже картинку
rus_verbs:созревать{}, // созревать на ветке
rus_verbs:проколоться{}, // проколоться на мелочи
rus_verbs:крутнуться{}, // крутнуться на заднем колесе
rus_verbs:переночевать{}, // переночевать на постоялом дворе
rus_verbs:концентрироваться{}, // концентрироваться на фильтре
rus_verbs:одичать{}, // одичать на хуторе
rus_verbs:спасаться{}, // спасаются на лодке
rus_verbs:доказываться{}, // доказываться на страницах книги
rus_verbs:познаваться{}, // познаваться на ринге
rus_verbs:замыкаться{}, // замыкаться на металлическом предмете
rus_verbs:заприметить{}, // заприметить на пригорке
rus_verbs:продержать{}, // продержать на морозе
rus_verbs:форсировать{}, // форсировать на плотах
rus_verbs:сохнуть{}, // сохнуть на солнце
rus_verbs:выявить{}, // выявить на поверхности
rus_verbs:заседать{}, // заседать на кафедре
rus_verbs:расплачиваться{}, // расплачиваться на выходе
rus_verbs:светлеть{}, // светлеть на горизонте
rus_verbs:залепетать{}, // залепетать на незнакомом языке
rus_verbs:подсчитывать{}, // подсчитывать на пальцах
rus_verbs:зарыть{}, // зарыть на пустыре
rus_verbs:сформироваться{}, // сформироваться на месте
rus_verbs:развертываться{}, // развертываться на площадке
rus_verbs:набивать{}, // набивать на манекенах
rus_verbs:замерзать{}, // замерзать на ветру
rus_verbs:схватывать{}, // схватывать на лету
rus_verbs:перевестись{}, // перевестись на Руси
rus_verbs:смешивать{}, // смешивать на блюдце
rus_verbs:прождать{}, // прождать на входе
rus_verbs:мерзнуть{}, // мерзнуть на ветру
rus_verbs:растирать{}, // растирать на коже
rus_verbs:переспать{}, // переспал на сеновале
rus_verbs:рассекать{}, // рассекать на скутере
rus_verbs:опровергнуть{}, // опровергнуть на высшем уровне
rus_verbs:дрыхнуть{}, // дрыхнуть на диване
rus_verbs:распять{}, // распять на кресте
rus_verbs:запечься{}, // запечься на костре
rus_verbs:застилать{}, // застилать на балконе
rus_verbs:сыскаться{}, // сыскаться на огороде
rus_verbs:разориться{}, // разориться на продаже спичек
rus_verbs:переделать{}, // переделать на станке
rus_verbs:разъяснять{}, // разъяснять на страницах газеты
rus_verbs:поседеть{}, // поседеть на висках
rus_verbs:протащить{}, // протащить на спине
rus_verbs:осуществиться{}, // осуществиться на деле
rus_verbs:селиться{}, // селиться на окраине
rus_verbs:оплачивать{}, // оплачивать на первой кассе
rus_verbs:переворачивать{}, // переворачивать на сковородке
rus_verbs:упражняться{}, // упражняться на батуте
rus_verbs:испробовать{}, // испробовать на себе
rus_verbs:разгладиться{}, // разгладиться на спине
rus_verbs:рисоваться{}, // рисоваться на стекле
rus_verbs:продрогнуть{}, // продрогнуть на морозе
rus_verbs:пометить{}, // пометить на доске
rus_verbs:приютить{}, // приютить на чердаке
rus_verbs:избирать{}, // избирать на первых свободных выборах
rus_verbs:затеваться{}, // затеваться на матче
rus_verbs:уплывать{}, // уплывать на катере
rus_verbs:замерцать{}, // замерцать на рекламном щите
rus_verbs:фиксироваться{}, // фиксироваться на достигнутом уровне
rus_verbs:запираться{}, // запираться на чердаке
rus_verbs:загубить{}, // загубить на корню
rus_verbs:развеяться{}, // развеяться на природе
rus_verbs:съезжаться{}, // съезжаться на лимузинах
rus_verbs:потанцевать{}, // потанцевать на могиле
rus_verbs:дохнуть{}, // дохнуть на солнце
rus_verbs:припарковаться{}, // припарковаться на газоне
rus_verbs:отхватить{}, // отхватить на распродаже
rus_verbs:остывать{}, // остывать на улице
rus_verbs:переваривать{}, // переваривать на высокой ветке
rus_verbs:подвесить{}, // подвесить на веревке
rus_verbs:хвастать{}, // хвастать на работе
rus_verbs:отрабатывать{}, // отрабатывать на уборке урожая
rus_verbs:разлечься{}, // разлечься на полу
rus_verbs:очертить{}, // очертить на полу
rus_verbs:председательствовать{}, // председательствовать на собрании
rus_verbs:сконфузиться{}, // сконфузиться на сцене
rus_verbs:выявляться{}, // выявляться на ринге
rus_verbs:крутануться{}, // крутануться на заднем колесе
rus_verbs:караулить{}, // караулить на входе
rus_verbs:перечислять{}, // перечислять на пальцах
rus_verbs:обрабатывать{}, // обрабатывать на станке
rus_verbs:настигать{}, // настигать на берегу
rus_verbs:разгуливать{}, // разгуливать на берегу
rus_verbs:насиловать{}, // насиловать на пляже
rus_verbs:поредеть{}, // поредеть на макушке
rus_verbs:учитывать{}, // учитывать на балансе
rus_verbs:зарождаться{}, // зарождаться на большой глубине
rus_verbs:распространять{}, // распространять на сайтах
rus_verbs:пировать{}, // пировать на вершине холма
rus_verbs:начертать{}, // начертать на стене
rus_verbs:расцветать{}, // расцветать на подоконнике
rus_verbs:умнеть{}, // умнеть на глазах
rus_verbs:царствовать{}, // царствовать на окраине
rus_verbs:закрутиться{}, // закрутиться на работе
rus_verbs:отработать{}, // отработать на шахте
rus_verbs:полечь{}, // полечь на поле брани
rus_verbs:щебетать{}, // щебетать на ветке
rus_verbs:подчеркиваться{}, // подчеркиваться на сайте
rus_verbs:посеять{}, // посеять на другом поле
rus_verbs:замечаться{}, // замечаться на пастбище
rus_verbs:просчитать{}, // просчитать на пальцах
rus_verbs:голосовать{}, // голосовать на трассе
rus_verbs:маяться{}, // маяться на пляже
rus_verbs:сколотить{}, // сколотить на службе
rus_verbs:обретаться{}, // обретаться на чужбине
rus_verbs:обливаться{}, // обливаться на улице
rus_verbs:катать{}, // катать на лошадке
rus_verbs:припрятать{}, // припрятать на теле
rus_verbs:запаниковать{}, // запаниковать на экзамене
инфинитив:слетать{ вид:соверш }, глагол:слетать{ вид:соверш }, // слетать на частном самолете
деепричастие:слетав{},
rus_verbs:срубить{}, // срубить денег на спекуляциях
rus_verbs:зажигаться{}, // зажигаться на улице
rus_verbs:жарить{}, // жарить на углях
rus_verbs:накапливаться{}, // накапливаться на счету
rus_verbs:распуститься{}, // распуститься на грядке
rus_verbs:рассаживаться{}, // рассаживаться на местах
rus_verbs:странствовать{}, // странствовать на лошади
rus_verbs:осматриваться{}, // осматриваться на месте
rus_verbs:разворачивать{}, // разворачивать на завоеванной территории
rus_verbs:согревать{}, // согревать на вершине горы
rus_verbs:заскучать{}, // заскучать на вахте
rus_verbs:перекусить{}, // перекусить на бегу
rus_verbs:приплыть{}, // приплыть на тримаране
rus_verbs:зажигать{}, // зажигать на танцах
rus_verbs:закопать{}, // закопать на поляне
rus_verbs:стирать{}, // стирать на берегу
rus_verbs:подстерегать{}, // подстерегать на подходе
rus_verbs:погулять{}, // погулять на свадьбе
rus_verbs:огласить{}, // огласить на митинге
rus_verbs:разбогатеть{}, // разбогатеть на прииске
rus_verbs:грохотать{}, // грохотать на чердаке
rus_verbs:расположить{}, // расположить на границе
rus_verbs:реализоваться{}, // реализоваться на новой работе
rus_verbs:застывать{}, // застывать на морозе
rus_verbs:запечатлеть{}, // запечатлеть на пленке
rus_verbs:тренироваться{}, // тренироваться на манекене
rus_verbs:поспорить{}, // поспорить на совещании
rus_verbs:затягивать{}, // затягивать на поясе
rus_verbs:зиждиться{}, // зиждиться на твердой основе
rus_verbs:построиться{}, // построиться на песке
rus_verbs:надрываться{}, // надрываться на работе
rus_verbs:закипать{}, // закипать на плите
rus_verbs:затонуть{}, // затонуть на мелководье
rus_verbs:побыть{}, // побыть на фазенде
rus_verbs:сгорать{}, // сгорать на солнце
инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать на улице
деепричастие:пописав{ aux stress="поп^исав" },
rus_verbs:подраться{}, // подраться на сцене
rus_verbs:заправить{}, // заправить на последней заправке
rus_verbs:обозначаться{}, // обозначаться на карте
rus_verbs:просиживать{}, // просиживать на берегу
rus_verbs:начертить{}, // начертить на листке
rus_verbs:тормозить{}, // тормозить на льду
rus_verbs:затевать{}, // затевать на космической базе
rus_verbs:задерживать{}, // задерживать на таможне
rus_verbs:прилетать{}, // прилетать на частном самолете
rus_verbs:полулежать{}, // полулежать на травке
rus_verbs:ерзать{}, // ерзать на табуретке
rus_verbs:покопаться{}, // покопаться на складе
rus_verbs:подвезти{}, // подвезти на машине
rus_verbs:полежать{}, // полежать на водном матрасе
rus_verbs:стыть{}, // стыть на улице
rus_verbs:стынуть{}, // стынуть на улице
rus_verbs:скреститься{}, // скреститься на груди
rus_verbs:припарковать{}, // припарковать на стоянке
rus_verbs:здороваться{}, // здороваться на кафедре
rus_verbs:нацарапать{}, // нацарапать на парте
rus_verbs:откопать{}, // откопать на поляне
rus_verbs:смастерить{}, // смастерить на коленках
rus_verbs:довезти{}, // довезти на машине
rus_verbs:избивать{}, // избивать на крыше
rus_verbs:сварить{}, // сварить на костре
rus_verbs:истребить{}, // истребить на корню
rus_verbs:раскопать{}, // раскопать на болоте
rus_verbs:попить{}, // попить на кухне
rus_verbs:заправлять{}, // заправлять на базе
rus_verbs:кушать{}, // кушать на кухне
rus_verbs:замолкать{}, // замолкать на половине фразы
rus_verbs:измеряться{}, // измеряться на весах
rus_verbs:сбываться{}, // сбываться на самом деле
rus_verbs:изображаться{}, // изображается на сцене
rus_verbs:фиксировать{}, // фиксировать на данной высоте
rus_verbs:ослаблять{}, // ослаблять на шее
rus_verbs:зреть{}, // зреть на грядке
rus_verbs:зеленеть{}, // зеленеть на грядке
rus_verbs:критиковать{}, // критиковать на страницах газеты
rus_verbs:облететь{}, // облететь на самолете
rus_verbs:заразиться{}, // заразиться на работе
rus_verbs:рассеять{}, // рассеять на территории
rus_verbs:печься{}, // печься на костре
rus_verbs:поспать{}, // поспать на земле
rus_verbs:сплетаться{}, // сплетаться на макушке
rus_verbs:удерживаться{}, // удерживаться на расстоянии
rus_verbs:помешаться{}, // помешаться на чистоте
rus_verbs:ликвидировать{}, // ликвидировать на полигоне
rus_verbs:проваляться{}, // проваляться на диване
rus_verbs:лечиться{}, // лечиться на дому
rus_verbs:обработать{}, // обработать на станке
rus_verbs:защелкнуть{}, // защелкнуть на руках
rus_verbs:разносить{}, // разносить на одежде
rus_verbs:чесать{}, // чесать на груди
rus_verbs:наладить{}, // наладить на конвейере выпуск
rus_verbs:отряхнуться{}, // отряхнуться на улице
rus_verbs:разыгрываться{}, // разыгрываться на скачках
rus_verbs:обеспечиваться{}, // обеспечиваться на выгодных условиях
rus_verbs:греться{}, // греться на вокзале
rus_verbs:засидеться{}, // засидеться на одном месте
rus_verbs:материализоваться{}, // материализоваться на границе
rus_verbs:рассеиваться{}, // рассеиваться на высоте вершин
rus_verbs:перевозить{}, // перевозить на платформе
rus_verbs:поиграть{}, // поиграть на скрипке
rus_verbs:потоптаться{}, // потоптаться на одном месте
rus_verbs:переправиться{}, // переправиться на плоту
rus_verbs:забрезжить{}, // забрезжить на горизонте
rus_verbs:завывать{}, // завывать на опушке
rus_verbs:заваривать{}, // заваривать на кухоньке
rus_verbs:перемещаться{}, // перемещаться на спасательном плоту
инфинитив:писаться{ aux stress="пис^аться" }, глагол:писаться{ aux stress="пис^аться" }, // писаться на бланке
rus_verbs:праздновать{}, // праздновать на улицах
rus_verbs:обучить{}, // обучить на корте
rus_verbs:орудовать{}, // орудовать на складе
rus_verbs:подрасти{}, // подрасти на глядке
rus_verbs:шелестеть{}, // шелестеть на ветру
rus_verbs:раздеваться{}, // раздеваться на публике
rus_verbs:пообедать{}, // пообедать на газоне
rus_verbs:жрать{}, // жрать на помойке
rus_verbs:исполняться{}, // исполняться на флейте
rus_verbs:похолодать{}, // похолодать на улице
rus_verbs:гнить{}, // гнить на каторге
rus_verbs:прослушать{}, // прослушать на концерте
rus_verbs:совещаться{}, // совещаться на заседании
rus_verbs:покачивать{}, // покачивать на волнах
rus_verbs:отсидеть{}, // отсидеть на гаупвахте
rus_verbs:формировать{}, // формировать на секретной базе
rus_verbs:захрапеть{}, // захрапеть на кровати
rus_verbs:объехать{}, // объехать на попутке
rus_verbs:поселить{}, // поселить на верхних этажах
rus_verbs:заворочаться{}, // заворочаться на сене
rus_verbs:напрятать{}, // напрятать на теле
rus_verbs:очухаться{}, // очухаться на земле
rus_verbs:полистать{}, // полистать на досуге
rus_verbs:завертеть{}, // завертеть на шесте
rus_verbs:печатать{}, // печатать на ноуте
rus_verbs:отыскаться{}, // отыскаться на складе
rus_verbs:зафиксировать{}, // зафиксировать на пленке
rus_verbs:расстилаться{}, // расстилаться на столе
rus_verbs:заместить{}, // заместить на посту
rus_verbs:угасать{}, // угасать на неуправляемом корабле
rus_verbs:сразить{}, // сразить на ринге
rus_verbs:расплываться{}, // расплываться на жаре
rus_verbs:сосчитать{}, // сосчитать на пальцах
rus_verbs:сгуститься{}, // сгуститься на небольшой высоте
rus_verbs:цитировать{}, // цитировать на плите
rus_verbs:ориентироваться{}, // ориентироваться на местности
rus_verbs:расширить{}, // расширить на другом конце
rus_verbs:обтереть{}, // обтереть на стоянке
rus_verbs:подстрелить{}, // подстрелить на охоте
rus_verbs:растереть{}, // растереть на твердой поверхности
rus_verbs:подавлять{}, // подавлять на первом этапе
rus_verbs:смешиваться{}, // смешиваться на поверхности
// инфинитив:вычитать{ aux stress="в^ычитать" }, глагол:вычитать{ aux stress="в^ычитать" }, // вычитать на сайте
// деепричастие:вычитав{},
rus_verbs:сократиться{}, // сократиться на втором этапе
rus_verbs:занервничать{}, // занервничать на экзамене
rus_verbs:соприкоснуться{}, // соприкоснуться на трассе
rus_verbs:обозначить{}, // обозначить на плане
rus_verbs:обучаться{}, // обучаться на производстве
rus_verbs:снизиться{}, // снизиться на большой высоте
rus_verbs:простудиться{}, // простудиться на ветру
rus_verbs:поддерживаться{}, // поддерживается на встрече
rus_verbs:уплыть{}, // уплыть на лодочке
rus_verbs:резвиться{}, // резвиться на песочке
rus_verbs:поерзать{}, // поерзать на скамеечке
rus_verbs:похвастаться{}, // похвастаться на встрече
rus_verbs:знакомиться{}, // знакомиться на уроке
rus_verbs:проплывать{}, // проплывать на катере
rus_verbs:засесть{}, // засесть на чердаке
rus_verbs:подцепить{}, // подцепить на дискотеке
rus_verbs:обыскать{}, // обыскать на входе
rus_verbs:оправдаться{}, // оправдаться на суде
rus_verbs:раскрываться{}, // раскрываться на сцене
rus_verbs:одеваться{}, // одеваться на вещевом рынке
rus_verbs:засветиться{}, // засветиться на фотографиях
rus_verbs:употребляться{}, // употребляться на птицефабриках
rus_verbs:грабить{}, // грабить на пустыре
rus_verbs:гонять{}, // гонять на повышенных оборотах
rus_verbs:развеваться{}, // развеваться на древке
rus_verbs:основываться{}, // основываться на безусловных фактах
rus_verbs:допрашивать{}, // допрашивать на базе
rus_verbs:проработать{}, // проработать на стройке
rus_verbs:сосредоточить{}, // сосредоточить на месте
rus_verbs:сочинять{}, // сочинять на ходу
rus_verbs:ползать{}, // ползать на камне
rus_verbs:раскинуться{}, // раскинуться на пустыре
rus_verbs:уставать{}, // уставать на работе
rus_verbs:укрепить{}, // укрепить на конце
rus_verbs:образовывать{}, // образовывать на открытом воздухе взрывоопасную смесь
rus_verbs:одобрять{}, // одобрять на словах
rus_verbs:приговорить{}, // приговорить на заседании тройки
rus_verbs:чернеть{}, // чернеть на свету
rus_verbs:гнуть{}, // гнуть на станке
rus_verbs:размещаться{}, // размещаться на бирже
rus_verbs:соорудить{}, // соорудить на даче
rus_verbs:пастись{}, // пастись на лугу
rus_verbs:формироваться{}, // формироваться на дне
rus_verbs:таить{}, // таить на дне
rus_verbs:приостановиться{}, // приостановиться на середине
rus_verbs:топтаться{}, // топтаться на месте
rus_verbs:громить{}, // громить на подступах
rus_verbs:вычислить{}, // вычислить на бумажке
rus_verbs:заказывать{}, // заказывать на сайте
rus_verbs:осуществить{}, // осуществить на практике
rus_verbs:обосноваться{}, // обосноваться на верхушке
rus_verbs:пытать{}, // пытать на электрическом стуле
rus_verbs:совершиться{}, // совершиться на заседании
rus_verbs:свернуться{}, // свернуться на медленном огне
rus_verbs:пролетать{}, // пролетать на дельтаплане
rus_verbs:сбыться{}, // сбыться на самом деле
rus_verbs:разговориться{}, // разговориться на уроке
rus_verbs:разворачиваться{}, // разворачиваться на перекрестке
rus_verbs:преподнести{}, // преподнести на блюдечке
rus_verbs:напечатать{}, // напечатать на лазернике
rus_verbs:прорвать{}, // прорвать на периферии
rus_verbs:раскачиваться{}, // раскачиваться на доске
rus_verbs:задерживаться{}, // задерживаться на старте
rus_verbs:угощать{}, // угощать на вечеринке
rus_verbs:шарить{}, // шарить на столе
rus_verbs:увеличивать{}, // увеличивать на первом этапе
rus_verbs:рехнуться{}, // рехнуться на старости лет
rus_verbs:расцвести{}, // расцвести на грядке
rus_verbs:закипеть{}, // закипеть на плите
rus_verbs:подлететь{}, // подлететь на параплане
rus_verbs:рыться{}, // рыться на свалке
rus_verbs:добираться{}, // добираться на попутках
rus_verbs:продержаться{}, // продержаться на вершине
rus_verbs:разыскивать{}, // разыскивать на выставках
rus_verbs:освобождать{}, // освобождать на заседании
rus_verbs:передвигаться{}, // передвигаться на самокате
rus_verbs:проявиться{}, // проявиться на свету
rus_verbs:заскользить{}, // заскользить на льду
rus_verbs:пересказать{}, // пересказать на сцене студенческого театра
rus_verbs:протестовать{}, // протестовать на улице
rus_verbs:указываться{}, // указываться на табличках
rus_verbs:прискакать{}, // прискакать на лошадке
rus_verbs:копошиться{}, // копошиться на свежем воздухе
rus_verbs:подсчитать{}, // подсчитать на бумажке
rus_verbs:разволноваться{}, // разволноваться на экзамене
rus_verbs:завертеться{}, // завертеться на полу
rus_verbs:ознакомиться{}, // ознакомиться на ходу
rus_verbs:ржать{}, // ржать на уроке
rus_verbs:раскинуть{}, // раскинуть на грядках
rus_verbs:разгромить{}, // разгромить на ринге
rus_verbs:подслушать{}, // подслушать на совещании
rus_verbs:описываться{}, // описываться на страницах книги
rus_verbs:качаться{}, // качаться на стуле
rus_verbs:усилить{}, // усилить на флангах
rus_verbs:набросать{}, // набросать на клочке картона
rus_verbs:расстреливать{}, // расстреливать на подходе
rus_verbs:запрыгать{}, // запрыгать на одной ноге
rus_verbs:сыскать{}, // сыскать на чужбине
rus_verbs:подтвердиться{}, // подтвердиться на практике
rus_verbs:плескаться{}, // плескаться на мелководье
rus_verbs:расширяться{}, // расширяться на конце
rus_verbs:подержать{}, // подержать на солнце
rus_verbs:планироваться{}, // планироваться на общем собрании
rus_verbs:сгинуть{}, // сгинуть на чужбине
rus_verbs:замкнуться{}, // замкнуться на точке
rus_verbs:закачаться{}, // закачаться на ветру
rus_verbs:перечитывать{}, // перечитывать на ходу
rus_verbs:перелететь{}, // перелететь на дельтаплане
rus_verbs:оживать{}, // оживать на солнце
rus_verbs:женить{}, // женить на богатой невесте
rus_verbs:заглохнуть{}, // заглохнуть на старте
rus_verbs:копаться{}, // копаться на полу
rus_verbs:развлекаться{}, // развлекаться на дискотеке
rus_verbs:печататься{}, // печататься на струйном принтере
rus_verbs:обрываться{}, // обрываться на полуслове
rus_verbs:ускакать{}, // ускакать на лошадке
rus_verbs:подписывать{}, // подписывать на столе
rus_verbs:добывать{}, // добывать на выработке
rus_verbs:скопиться{}, // скопиться на выходе
rus_verbs:повстречать{}, // повстречать на пути
rus_verbs:поцеловаться{}, // поцеловаться на площади
rus_verbs:растянуть{}, // растянуть на столе
rus_verbs:подаваться{}, // подаваться на благотворительном обеде
rus_verbs:повстречаться{}, // повстречаться на митинге
rus_verbs:примоститься{}, // примоститься на ступеньках
rus_verbs:отразить{}, // отразить на страницах доклада
rus_verbs:пояснять{}, // пояснять на страницах приложения
rus_verbs:накормить{}, // накормить на кухне
rus_verbs:поужинать{}, // поужинать на веранде
инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть на митинге
деепричастие:спев{},
инфинитив:спеть{ вид:несоверш }, глагол:спеть{ вид:несоверш },
rus_verbs:топить{}, // топить на мелководье
rus_verbs:освоить{}, // освоить на практике
rus_verbs:распластаться{}, // распластаться на травке
rus_verbs:отплыть{}, // отплыть на старом каяке
rus_verbs:улетать{}, // улетать на любом самолете
rus_verbs:отстаивать{}, // отстаивать на корте
rus_verbs:осуждать{}, // осуждать на словах
rus_verbs:переговорить{}, // переговорить на обеде
rus_verbs:укрыть{}, // укрыть на чердаке
rus_verbs:томиться{}, // томиться на привязи
rus_verbs:сжигать{}, // сжигать на полигоне
rus_verbs:позавтракать{}, // позавтракать на лоне природы
rus_verbs:функционировать{}, // функционирует на солнечной энергии
rus_verbs:разместить{}, // разместить на сайте
rus_verbs:пронести{}, // пронести на теле
rus_verbs:нашарить{}, // нашарить на столе
rus_verbs:корчиться{}, // корчиться на полу
rus_verbs:распознать{}, // распознать на снимке
rus_verbs:повеситься{}, // повеситься на шнуре
rus_verbs:обозначиться{}, // обозначиться на картах
rus_verbs:оступиться{}, // оступиться на скользком льду
rus_verbs:подносить{}, // подносить на блюдечке
rus_verbs:расстелить{}, // расстелить на газоне
rus_verbs:обсуждаться{}, // обсуждаться на собрании
rus_verbs:расписаться{}, // расписаться на бланке
rus_verbs:плестись{}, // плестись на привязи
rus_verbs:объявиться{}, // объявиться на сцене
rus_verbs:повышаться{}, // повышаться на первом датчике
rus_verbs:разрабатывать{}, // разрабатывать на заводе
rus_verbs:прерывать{}, // прерывать на середине
rus_verbs:каяться{}, // каяться на публике
rus_verbs:освоиться{}, // освоиться на лошади
rus_verbs:подплыть{}, // подплыть на плоту
rus_verbs:оскорбить{}, // оскорбить на митинге
rus_verbs:торжествовать{}, // торжествовать на пьедестале
rus_verbs:поправлять{}, // поправлять на одежде
rus_verbs:отражать{}, // отражать на картине
rus_verbs:дремать{}, // дремать на кушетке
rus_verbs:применяться{}, // применяться на производстве стали
rus_verbs:поражать{}, // поражать на большой дистанции
rus_verbs:расстрелять{}, // расстрелять на окраине хутора
rus_verbs:рассчитать{}, // рассчитать на калькуляторе
rus_verbs:записывать{}, // записывать на ленте
rus_verbs:перебирать{}, // перебирать на ладони
rus_verbs:разбиться{}, // разбиться на катере
rus_verbs:поискать{}, // поискать на ферме
rus_verbs:прятать{}, // прятать на заброшенном складе
rus_verbs:пропеть{}, // пропеть на эстраде
rus_verbs:замелькать{}, // замелькать на экране
rus_verbs:грустить{}, // грустить на веранде
rus_verbs:крутить{}, // крутить на оси
rus_verbs:подготовить{}, // подготовить на конспиративной квартире
rus_verbs:различать{}, // различать на картинке
rus_verbs:киснуть{}, // киснуть на чужбине
rus_verbs:оборваться{}, // оборваться на полуслове
rus_verbs:запутаться{}, // запутаться на простейшем тесте
rus_verbs:общаться{}, // общаться на уроке
rus_verbs:производиться{}, // производиться на фабрике
rus_verbs:сочинить{}, // сочинить на досуге
rus_verbs:давить{}, // давить на лице
rus_verbs:разработать{}, // разработать на секретном предприятии
rus_verbs:качать{}, // качать на качелях
rus_verbs:тушить{}, // тушить на крыше пожар
rus_verbs:охранять{}, // охранять на территории базы
rus_verbs:приметить{}, // приметить на взгорке
rus_verbs:скрыть{}, // скрыть на теле
rus_verbs:удерживать{}, // удерживать на руке
rus_verbs:усвоить{}, // усвоить на уроке
rus_verbs:растаять{}, // растаять на солнечной стороне
rus_verbs:красоваться{}, // красоваться на виду
rus_verbs:сохраняться{}, // сохраняться на холоде
rus_verbs:лечить{}, // лечить на дому
rus_verbs:прокатиться{}, // прокатиться на уницикле
rus_verbs:договариваться{}, // договариваться на нейтральной территории
rus_verbs:качнуться{}, // качнуться на одной ноге
rus_verbs:опубликовать{}, // опубликовать на сайте
rus_verbs:отражаться{}, // отражаться на поверхности воды
rus_verbs:обедать{}, // обедать на веранде
rus_verbs:посидеть{}, // посидеть на лавочке
rus_verbs:сообщаться{}, // сообщаться на официальном сайте
rus_verbs:свершиться{}, // свершиться на заседании
rus_verbs:ночевать{}, // ночевать на даче
rus_verbs:темнеть{}, // темнеть на свету
rus_verbs:гибнуть{}, // гибнуть на территории полигона
rus_verbs:усиливаться{}, // усиливаться на территории округа
rus_verbs:проживать{}, // проживать на даче
rus_verbs:исследовать{}, // исследовать на большой глубине
rus_verbs:обитать{}, // обитать на громадной глубине
rus_verbs:сталкиваться{}, // сталкиваться на большой высоте
rus_verbs:таиться{}, // таиться на большой глубине
rus_verbs:спасать{}, // спасать на пожаре
rus_verbs:сказываться{}, // сказываться на общем результате
rus_verbs:заблудиться{}, // заблудиться на стройке
rus_verbs:пошарить{}, // пошарить на полках
rus_verbs:планировать{}, // планировать на бумаге
rus_verbs:ранить{}, // ранить на полигоне
rus_verbs:хлопать{}, // хлопать на сцене
rus_verbs:основать{}, // основать на горе новый монастырь
rus_verbs:отбить{}, // отбить на столе
rus_verbs:отрицать{}, // отрицать на заседании комиссии
rus_verbs:устоять{}, // устоять на ногах
rus_verbs:отзываться{}, // отзываться на страницах отчёта
rus_verbs:притормозить{}, // притормозить на обочине
rus_verbs:читаться{}, // читаться на лице
rus_verbs:заиграть{}, // заиграть на саксофоне
rus_verbs:зависнуть{}, // зависнуть на игровой площадке
rus_verbs:сознаться{}, // сознаться на допросе
rus_verbs:выясняться{}, // выясняться на очной ставке
rus_verbs:наводить{}, // наводить на столе порядок
rus_verbs:покоиться{}, // покоиться на кладбище
rus_verbs:значиться{}, // значиться на бейджике
rus_verbs:съехать{}, // съехать на санках
rus_verbs:познакомить{}, // познакомить на свадьбе
rus_verbs:завязать{}, // завязать на спине
rus_verbs:грохнуть{}, // грохнуть на площади
rus_verbs:разъехаться{}, // разъехаться на узкой дороге
rus_verbs:столпиться{}, // столпиться на крыльце
rus_verbs:порыться{}, // порыться на полках
rus_verbs:ослабить{}, // ослабить на шее
rus_verbs:оправдывать{}, // оправдывать на суде
rus_verbs:обнаруживаться{}, // обнаруживаться на складе
rus_verbs:спастись{}, // спастись на дереве
rus_verbs:прерваться{}, // прерваться на полуслове
rus_verbs:строиться{}, // строиться на пустыре
rus_verbs:познать{}, // познать на практике
rus_verbs:путешествовать{}, // путешествовать на поезде
rus_verbs:побеждать{}, // побеждать на ринге
rus_verbs:рассматриваться{}, // рассматриваться на заседании
rus_verbs:продаваться{}, // продаваться на открытом рынке
rus_verbs:разместиться{}, // разместиться на базе
rus_verbs:завыть{}, // завыть на холме
rus_verbs:настигнуть{}, // настигнуть на окраине
rus_verbs:укрыться{}, // укрыться на чердаке
rus_verbs:расплакаться{}, // расплакаться на заседании комиссии
rus_verbs:заканчивать{}, // заканчивать на последнем задании
rus_verbs:пролежать{}, // пролежать на столе
rus_verbs:громоздиться{}, // громоздиться на полу
rus_verbs:замерзнуть{}, // замерзнуть на открытом воздухе
rus_verbs:поскользнуться{}, // поскользнуться на льду
rus_verbs:таскать{}, // таскать на спине
rus_verbs:просматривать{}, // просматривать на сайте
rus_verbs:обдумать{}, // обдумать на досуге
rus_verbs:гадать{}, // гадать на кофейной гуще
rus_verbs:останавливать{}, // останавливать на выходе
rus_verbs:обозначать{}, // обозначать на странице
rus_verbs:долететь{}, // долететь на спортивном байке
rus_verbs:тесниться{}, // тесниться на чердачке
rus_verbs:хоронить{}, // хоронить на частном кладбище
rus_verbs:установиться{}, // установиться на юге
rus_verbs:прикидывать{}, // прикидывать на клочке бумаги
rus_verbs:затаиться{}, // затаиться на дереве
rus_verbs:раздобыть{}, // раздобыть на складе
rus_verbs:перебросить{}, // перебросить на вертолетах
rus_verbs:захватывать{}, // захватывать на базе
rus_verbs:сказаться{}, // сказаться на итоговых оценках
rus_verbs:покачиваться{}, // покачиваться на волнах
rus_verbs:крутиться{}, // крутиться на кухне
rus_verbs:помещаться{}, // помещаться на полке
rus_verbs:питаться{}, // питаться на помойке
rus_verbs:отдохнуть{}, // отдохнуть на загородной вилле
rus_verbs:кататься{}, // кататься на велике
rus_verbs:поработать{}, // поработать на стройке
rus_verbs:ограбить{}, // ограбить на пустыре
rus_verbs:зарабатывать{}, // зарабатывать на бирже
rus_verbs:преуспеть{}, // преуспеть на ниве искусства
rus_verbs:заерзать{}, // заерзать на стуле
rus_verbs:разъяснить{}, // разъяснить на полях
rus_verbs:отчеканить{}, // отчеканить на медной пластине
rus_verbs:торговать{}, // торговать на рынке
rus_verbs:поколебаться{}, // поколебаться на пороге
rus_verbs:прикинуть{}, // прикинуть на бумажке
rus_verbs:рассечь{}, // рассечь на тупом конце
rus_verbs:посмеяться{}, // посмеяться на переменке
rus_verbs:остыть{}, // остыть на морозном воздухе
rus_verbs:запереться{}, // запереться на чердаке
rus_verbs:обогнать{}, // обогнать на повороте
rus_verbs:подтянуться{}, // подтянуться на турнике
rus_verbs:привозить{}, // привозить на машине
rus_verbs:подбирать{}, // подбирать на полу
rus_verbs:уничтожать{}, // уничтожать на подходе
rus_verbs:притаиться{}, // притаиться на вершине
rus_verbs:плясать{}, // плясать на костях
rus_verbs:поджидать{}, // поджидать на вокзале
rus_verbs:закончить{}, // Мы закончили игру на самом интересном месте (САМ не может быть первым прилагательным в цепочке!)
rus_verbs:смениться{}, // смениться на посту
rus_verbs:посчитать{}, // посчитать на пальцах
rus_verbs:прицелиться{}, // прицелиться на бегу
rus_verbs:нарисовать{}, // нарисовать на стене
rus_verbs:прыгать{}, // прыгать на сцене
rus_verbs:повертеть{}, // повертеть на пальце
rus_verbs:попрощаться{}, // попрощаться на панихиде
инфинитив:просыпаться{ вид:соверш }, глагол:просыпаться{ вид:соверш }, // просыпаться на диване
rus_verbs:разобрать{}, // разобрать на столе
rus_verbs:помереть{}, // помереть на чужбине
rus_verbs:различить{}, // различить на нечеткой фотографии
rus_verbs:рисовать{}, // рисовать на доске
rus_verbs:проследить{}, // проследить на экране
rus_verbs:задремать{}, // задремать на диване
rus_verbs:ругаться{}, // ругаться на людях
rus_verbs:сгореть{}, // сгореть на работе
rus_verbs:зазвучать{}, // зазвучать на коротких волнах
rus_verbs:задохнуться{}, // задохнуться на вершине горы
rus_verbs:порождать{}, // порождать на поверхности небольшую рябь
rus_verbs:отдыхать{}, // отдыхать на курорте
rus_verbs:образовать{}, // образовать на дне толстый слой
rus_verbs:поправиться{}, // поправиться на дармовых харчах
rus_verbs:отмечать{}, // отмечать на календаре
rus_verbs:реять{}, // реять на флагштоке
rus_verbs:ползти{}, // ползти на коленях
rus_verbs:продавать{}, // продавать на аукционе
rus_verbs:сосредоточиться{}, // сосредоточиться на основной задаче
rus_verbs:рыскать{}, // мышки рыскали на кухне
rus_verbs:расстегнуть{}, // расстегнуть на куртке все пуговицы
rus_verbs:напасть{}, // напасть на территории другого государства
rus_verbs:издать{}, // издать на западе
rus_verbs:оставаться{}, // оставаться на страже порядка
rus_verbs:появиться{}, // наконец появиться на экране
rus_verbs:лежать{}, // лежать на столе
rus_verbs:ждать{}, // ждать на берегу
инфинитив:писать{aux stress="пис^ать"}, // писать на бумаге
глагол:писать{aux stress="пис^ать"},
rus_verbs:оказываться{}, // оказываться на полу
rus_verbs:поставить{}, // поставить на столе
rus_verbs:держать{}, // держать на крючке
rus_verbs:выходить{}, // выходить на остановке
rus_verbs:заговорить{}, // заговорить на китайском языке
rus_verbs:ожидать{}, // ожидать на стоянке
rus_verbs:закричать{}, // закричал на минарете муэдзин
rus_verbs:простоять{}, // простоять на посту
rus_verbs:продолжить{}, // продолжить на первом этаже
rus_verbs:ощутить{}, // ощутить на себе влияние кризиса
rus_verbs:состоять{}, // состоять на учете
rus_verbs:готовиться{},
инфинитив:акклиматизироваться{вид:несоверш}, // альпинисты готовятся акклиматизироваться на новой высоте
глагол:акклиматизироваться{вид:несоверш},
rus_verbs:арестовать{}, // грабители были арестованы на месте преступления
rus_verbs:схватить{}, // грабители были схвачены на месте преступления
инфинитив:атаковать{ вид:соверш }, // взвод был атакован на границе
глагол:атаковать{ вид:соверш },
прилагательное:атакованный{ вид:соверш },
прилагательное:атаковавший{ вид:соверш },
rus_verbs:базировать{}, // установка будет базирована на границе
rus_verbs:базироваться{}, // установка базируется на границе
rus_verbs:барахтаться{}, // дети барахтались на мелководье
rus_verbs:браконьерить{}, // Охотники браконьерили ночью на реке
rus_verbs:браконьерствовать{}, // Охотники ночью браконьерствовали на реке
rus_verbs:бренчать{}, // парень что-то бренчал на гитаре
rus_verbs:бренькать{}, // парень что-то бренькает на гитаре
rus_verbs:начать{}, // Рынок акций РФ начал торги на отрицательной территории.
rus_verbs:буксовать{}, // Колеса буксуют на льду
rus_verbs:вертеться{}, // Непоседливый ученик много вертится на стуле
rus_verbs:взвести{}, // Боец взвел на оружии предохранитель
rus_verbs:вилять{}, // Машина сильно виляла на дороге
rus_verbs:висеть{}, // Яблоко висит на ветке
rus_verbs:возлежать{}, // возлежать на лежанке
rus_verbs:подниматься{}, // Мы поднимаемся на лифте
rus_verbs:подняться{}, // Мы поднимемся на лифте
rus_verbs:восседать{}, // Коля восседает на лошади
rus_verbs:воссиять{}, // Луна воссияла на небе
rus_verbs:воцариться{}, // Мир воцарился на всей земле
rus_verbs:воцаряться{}, // Мир воцаряется на всей земле
rus_verbs:вращать{}, // вращать на поясе
rus_verbs:вращаться{}, // вращаться на поясе
rus_verbs:встретить{}, // встретить друга на улице
rus_verbs:встретиться{}, // встретиться на занятиях
rus_verbs:встречать{}, // встречать на занятиях
rus_verbs:въебывать{}, // въебывать на работе
rus_verbs:въезжать{}, // въезжать на автомобиле
rus_verbs:въехать{}, // въехать на автомобиле
rus_verbs:выгорать{}, // ткань выгорает на солнце
rus_verbs:выгореть{}, // ткань выгорела на солнце
rus_verbs:выгравировать{}, // выгравировать на табличке надпись
rus_verbs:выжить{}, // выжить на необитаемом острове
rus_verbs:вылежаться{}, // помидоры вылежались на солнце
rus_verbs:вылеживаться{}, // вылеживаться на солнце
rus_verbs:выместить{}, // выместить на ком-то злобу
rus_verbs:вымещать{}, // вымещать на ком-то свое раздражение
rus_verbs:вымещаться{}, // вымещаться на ком-то
rus_verbs:выращивать{}, // выращивать на грядке помидоры
rus_verbs:выращиваться{}, // выращиваться на грядке
инфинитив:вырезать{вид:соверш}, // вырезать на доске надпись
глагол:вырезать{вид:соверш},
инфинитив:вырезать{вид:несоверш},
глагол:вырезать{вид:несоверш},
rus_verbs:вырисоваться{}, // вырисоваться на графике
rus_verbs:вырисовываться{}, // вырисовываться на графике
rus_verbs:высаживать{}, // высаживать на необитаемом острове
rus_verbs:высаживаться{}, // высаживаться на острове
rus_verbs:высвечивать{}, // высвечивать на дисплее температуру
rus_verbs:высвечиваться{}, // высвечиваться на дисплее
rus_verbs:выстроить{}, // выстроить на фундаменте
rus_verbs:выстроиться{}, // выстроиться на плацу
rus_verbs:выстудить{}, // выстудить на морозе
rus_verbs:выстудиться{}, // выстудиться на морозе
rus_verbs:выстужать{}, // выстужать на морозе
rus_verbs:выстуживать{}, // выстуживать на морозе
rus_verbs:выстуживаться{}, // выстуживаться на морозе
rus_verbs:выстукать{}, // выстукать на клавиатуре
rus_verbs:выстукивать{}, // выстукивать на клавиатуре
rus_verbs:выстукиваться{}, // выстукиваться на клавиатуре
rus_verbs:выступать{}, // выступать на сцене
rus_verbs:выступить{}, // выступить на сцене
rus_verbs:выстучать{}, // выстучать на клавиатуре
rus_verbs:выстывать{}, // выстывать на морозе
rus_verbs:выстыть{}, // выстыть на морозе
rus_verbs:вытатуировать{}, // вытатуировать на руке якорь
rus_verbs:говорить{}, // говорить на повышенных тонах
rus_verbs:заметить{}, // заметить на берегу
rus_verbs:стоять{}, // твёрдо стоять на ногах
rus_verbs:оказаться{}, // оказаться на передовой линии
rus_verbs:почувствовать{}, // почувствовать на своей шкуре
rus_verbs:остановиться{}, // остановиться на первом пункте
rus_verbs:показаться{}, // показаться на горизонте
rus_verbs:чувствовать{}, // чувствовать на своей шкуре
rus_verbs:искать{}, // искать на открытом пространстве
rus_verbs:иметься{}, // иметься на складе
rus_verbs:клясться{}, // клясться на Коране
rus_verbs:прервать{}, // прервать на полуслове
rus_verbs:играть{}, // играть на чувствах
rus_verbs:спуститься{}, // спуститься на парашюте
rus_verbs:понадобиться{}, // понадобиться на экзамене
rus_verbs:служить{}, // служить на флоте
rus_verbs:подобрать{}, // подобрать на улице
rus_verbs:появляться{}, // появляться на сцене
rus_verbs:селить{}, // селить на чердаке
rus_verbs:поймать{}, // поймать на границе
rus_verbs:увидать{}, // увидать на опушке
rus_verbs:подождать{}, // подождать на перроне
rus_verbs:прочесть{}, // прочесть на полях
rus_verbs:тонуть{}, // тонуть на мелководье
rus_verbs:ощущать{}, // ощущать на коже
rus_verbs:отметить{}, // отметить на полях
rus_verbs:показывать{}, // показывать на графике
rus_verbs:разговаривать{}, // разговаривать на иностранном языке
rus_verbs:прочитать{}, // прочитать на сайте
rus_verbs:попробовать{}, // попробовать на практике
rus_verbs:замечать{}, // замечать на коже грязь
rus_verbs:нести{}, // нести на плечах
rus_verbs:носить{}, // носить на голове
rus_verbs:гореть{}, // гореть на работе
rus_verbs:застыть{}, // застыть на пороге
инфинитив:жениться{ вид:соверш }, // жениться на королеве
глагол:жениться{ вид:соверш },
прилагательное:женатый{},
прилагательное:женившийся{},
rus_verbs:спрятать{}, // спрятать на чердаке
rus_verbs:развернуться{}, // развернуться на плацу
rus_verbs:строить{}, // строить на песке
rus_verbs:устроить{}, // устроить на даче тестральный вечер
rus_verbs:настаивать{}, // настаивать на выполнении приказа
rus_verbs:находить{}, // находить на берегу
rus_verbs:мелькнуть{}, // мелькнуть на экране
rus_verbs:очутиться{}, // очутиться на опушке леса
инфинитив:использовать{вид:соверш}, // использовать на работе
глагол:использовать{вид:соверш},
инфинитив:использовать{вид:несоверш},
глагол:использовать{вид:несоверш},
прилагательное:использованный{},
прилагательное:использующий{},
прилагательное:использовавший{},
rus_verbs:лететь{}, // лететь на воздушном шаре
rus_verbs:смеяться{}, // смеяться на сцене
rus_verbs:ездить{}, // ездить на мопеде
rus_verbs:заснуть{}, // заснуть на диване
rus_verbs:застать{}, // застать на рабочем месте
rus_verbs:очнуться{}, // очнуться на больничной койке
rus_verbs:разглядеть{}, // разглядеть на фотографии
rus_verbs:обойти{}, // обойти на вираже
rus_verbs:удержаться{}, // удержаться на троне
rus_verbs:побывать{}, // побывать на другой планете
rus_verbs:заняться{}, // заняться на выходных делом
rus_verbs:вянуть{}, // вянуть на солнце
rus_verbs:постоять{}, // постоять на голове
rus_verbs:приобрести{}, // приобрести на распродаже
rus_verbs:попасться{}, // попасться на краже
rus_verbs:продолжаться{}, // продолжаться на земле
rus_verbs:открывать{}, // открывать на арене
rus_verbs:создавать{}, // создавать на сцене
rus_verbs:обсуждать{}, // обсуждать на кухне
rus_verbs:отыскать{}, // отыскать на полу
rus_verbs:уснуть{}, // уснуть на диване
rus_verbs:задержаться{}, // задержаться на работе
rus_verbs:курить{}, // курить на свежем воздухе
rus_verbs:приподняться{}, // приподняться на локтях
rus_verbs:установить{}, // установить на вершине
rus_verbs:запереть{}, // запереть на балконе
rus_verbs:синеть{}, // синеть на воздухе
rus_verbs:убивать{}, // убивать на нейтральной территории
rus_verbs:скрываться{}, // скрываться на даче
rus_verbs:родить{}, // родить на полу
rus_verbs:описать{}, // описать на страницах книги
rus_verbs:перехватить{}, // перехватить на подлете
rus_verbs:скрывать{}, // скрывать на даче
rus_verbs:сменить{}, // сменить на посту
rus_verbs:мелькать{}, // мелькать на экране
rus_verbs:присутствовать{}, // присутствовать на мероприятии
rus_verbs:украсть{}, // украсть на рынке
rus_verbs:победить{}, // победить на ринге
rus_verbs:упомянуть{}, // упомянуть на страницах романа
rus_verbs:плыть{}, // плыть на старой лодке
rus_verbs:повиснуть{}, // повиснуть на перекладине
rus_verbs:нащупать{}, // нащупать на дне
rus_verbs:затихнуть{}, // затихнуть на дне
rus_verbs:построить{}, // построить на участке
rus_verbs:поддерживать{}, // поддерживать на поверхности
rus_verbs:заработать{}, // заработать на бирже
rus_verbs:провалиться{}, // провалиться на экзамене
rus_verbs:сохранить{}, // сохранить на диске
rus_verbs:располагаться{}, // располагаться на софе
rus_verbs:поклясться{}, // поклясться на библии
rus_verbs:сражаться{}, // сражаться на арене
rus_verbs:спускаться{}, // спускаться на дельтаплане
rus_verbs:уничтожить{}, // уничтожить на подступах
rus_verbs:изучить{}, // изучить на практике
rus_verbs:рождаться{}, // рождаться на праздниках
rus_verbs:прилететь{}, // прилететь на самолете
rus_verbs:догнать{}, // догнать на перекрестке
rus_verbs:изобразить{}, // изобразить на бумаге
rus_verbs:проехать{}, // проехать на тракторе
rus_verbs:приготовить{}, // приготовить на масле
rus_verbs:споткнуться{}, // споткнуться на полу
rus_verbs:собирать{}, // собирать на берегу
rus_verbs:отсутствовать{}, // отсутствовать на тусовке
rus_verbs:приземлиться{}, // приземлиться на военном аэродроме
rus_verbs:сыграть{}, // сыграть на трубе
rus_verbs:прятаться{}, // прятаться на даче
rus_verbs:спрятаться{}, // спрятаться на чердаке
rus_verbs:провозгласить{}, // провозгласить на митинге
rus_verbs:изложить{}, // изложить на бумаге
rus_verbs:использоваться{}, // использоваться на практике
rus_verbs:замяться{}, // замяться на входе
rus_verbs:раздаваться{}, // Крик ягуара раздается на краю болота
rus_verbs:сверкнуть{}, // сверкнуть на солнце
rus_verbs:сверкать{}, // сверкать на свету
rus_verbs:задержать{}, // задержать на митинге
rus_verbs:осечься{}, // осечься на первом слове
rus_verbs:хранить{}, // хранить на банковском счету
rus_verbs:шутить{}, // шутить на уроке
rus_verbs:кружиться{}, // кружиться на балу
rus_verbs:чертить{}, // чертить на доске
rus_verbs:отразиться{}, // отразиться на оценках
rus_verbs:греть{}, // греть на солнце
rus_verbs:рассуждать{}, // рассуждать на страницах своей книги
rus_verbs:окружать{}, // окружать на острове
rus_verbs:сопровождать{}, // сопровождать на охоте
rus_verbs:заканчиваться{}, // заканчиваться на самом интересном месте
rus_verbs:содержаться{}, // содержаться на приусадебном участке
rus_verbs:поселиться{}, // поселиться на даче
rus_verbs:запеть{}, // запеть на сцене
инфинитив:провозить{ вид:несоверш }, // провозить на теле
глагол:провозить{ вид:несоверш },
прилагательное:провезенный{},
прилагательное:провозивший{вид:несоверш},
прилагательное:провозящий{вид:несоверш},
деепричастие:провозя{},
rus_verbs:мочить{}, // мочить на месте
rus_verbs:преследовать{}, // преследовать на территории другого штата
rus_verbs:пролететь{}, // пролетел на параплане
rus_verbs:драться{}, // драться на рапирах
rus_verbs:просидеть{}, // просидеть на занятиях
rus_verbs:убираться{}, // убираться на балконе
rus_verbs:таять{}, // таять на солнце
rus_verbs:проверять{}, // проверять на полиграфе
rus_verbs:убеждать{}, // убеждать на примере
rus_verbs:скользить{}, // скользить на льду
rus_verbs:приобретать{}, // приобретать на распродаже
rus_verbs:летать{}, // летать на метле
rus_verbs:толпиться{}, // толпиться на перроне
rus_verbs:плавать{}, // плавать на надувном матрасе
rus_verbs:описывать{}, // описывать на страницах повести
rus_verbs:пробыть{}, // пробыть на солнце слишком долго
rus_verbs:застрять{}, // застрять на верхнем этаже
rus_verbs:метаться{}, // метаться на полу
rus_verbs:сжечь{}, // сжечь на костре
rus_verbs:расслабиться{}, // расслабиться на кушетке
rus_verbs:услыхать{}, // услыхать на рынке
rus_verbs:удержать{}, // удержать на прежнем уровне
rus_verbs:образоваться{}, // образоваться на дне
rus_verbs:рассмотреть{}, // рассмотреть на поверхности чипа
rus_verbs:уезжать{}, // уезжать на попутке
rus_verbs:похоронить{}, // похоронить на закрытом кладбище
rus_verbs:настоять{}, // настоять на пересмотре оценок
rus_verbs:растянуться{}, // растянуться на горячем песке
rus_verbs:покрутить{}, // покрутить на шесте
rus_verbs:обнаружиться{}, // обнаружиться на болоте
rus_verbs:гулять{}, // гулять на свадьбе
rus_verbs:утонуть{}, // утонуть на курорте
rus_verbs:храниться{}, // храниться на депозите
rus_verbs:танцевать{}, // танцевать на свадьбе
rus_verbs:трудиться{}, // трудиться на заводе
инфинитив:засыпать{переходность:непереходный вид:несоверш}, // засыпать на кровати
глагол:засыпать{переходность:непереходный вид:несоверш},
деепричастие:засыпая{переходность:непереходный вид:несоверш},
прилагательное:засыпавший{переходность:непереходный вид:несоверш},
прилагательное:засыпающий{ вид:несоверш переходность:непереходный }, // ребенок, засыпающий на руках
rus_verbs:сушить{}, // сушить на открытом воздухе
rus_verbs:зашевелиться{}, // зашевелиться на чердаке
rus_verbs:обдумывать{}, // обдумывать на досуге
rus_verbs:докладывать{}, // докладывать на научной конференции
rus_verbs:промелькнуть{}, // промелькнуть на экране
// прилагательное:находящийся{ вид:несоверш }, // колонна, находящаяся на ничейной территории
прилагательное:написанный{}, // слово, написанное на заборе
rus_verbs:умещаться{}, // компьютер, умещающийся на ладони
rus_verbs:открыть{}, // книга, открытая на последней странице
rus_verbs:спать{}, // йог, спящий на гвоздях
rus_verbs:пробуксовывать{}, // колесо, пробуксовывающее на обледенелом асфальте
rus_verbs:забуксовать{}, // колесо, забуксовавшее на обледенелом асфальте
rus_verbs:отобразиться{}, // удивление, отобразившееся на лице
rus_verbs:увидеть{}, // на полу я увидел чьи-то следы
rus_verbs:видеть{}, // на полу я вижу чьи-то следы
rus_verbs:оставить{}, // Мел оставил на доске белый след.
rus_verbs:оставлять{}, // Мел оставляет на доске белый след.
rus_verbs:встречаться{}, // встречаться на лекциях
rus_verbs:познакомиться{}, // познакомиться на занятиях
rus_verbs:устроиться{}, // она устроилась на кровати
rus_verbs:ложиться{}, // ложись на полу
rus_verbs:останавливаться{}, // останавливаться на достигнутом
rus_verbs:спотыкаться{}, // спотыкаться на ровном месте
rus_verbs:распечатать{}, // распечатать на бумаге
rus_verbs:распечатывать{}, // распечатывать на бумаге
rus_verbs:просмотреть{}, // просмотреть на бумаге
rus_verbs:закрепляться{}, // закрепляться на плацдарме
rus_verbs:погреться{}, // погреться на солнышке
rus_verbs:мешать{}, // Он мешал краски на палитре.
rus_verbs:занять{}, // Он занял первое место на соревнованиях.
rus_verbs:заговариваться{}, // Он заговаривался иногда на уроках.
деепричастие:женившись{ вид:соверш },
rus_verbs:везти{}, // Он везёт песок на тачке.
прилагательное:казненный{}, // Он был казнён на электрическом стуле.
rus_verbs:прожить{}, // Он безвыездно прожил всё лето на даче.
rus_verbs:принести{}, // Официантка принесла нам обед на подносе.
rus_verbs:переписать{}, // Перепишите эту рукопись на машинке.
rus_verbs:идти{}, // Поезд идёт на малой скорости.
rus_verbs:петь{}, // птички поют на рассвете
rus_verbs:смотреть{}, // Смотри на обороте.
rus_verbs:прибрать{}, // прибрать на столе
rus_verbs:прибраться{}, // прибраться на столе
rus_verbs:растить{}, // растить капусту на огороде
rus_verbs:тащить{}, // тащить ребенка на руках
rus_verbs:убирать{}, // убирать на столе
rus_verbs:простыть{}, // Я простыл на морозе.
rus_verbs:сиять{}, // ясные звезды мирно сияли на безоблачном весеннем небе.
rus_verbs:проводиться{}, // такие эксперименты не проводятся на воде
rus_verbs:достать{}, // Я не могу достать до яблок на верхних ветках.
rus_verbs:расплыться{}, // Чернила расплылись на плохой бумаге.
rus_verbs:вскочить{}, // У него вскочил прыщ на носу.
rus_verbs:свить{}, // У нас на балконе воробей свил гнездо.
rus_verbs:оторваться{}, // У меня на пальто оторвалась пуговица.
rus_verbs:восходить{}, // Солнце восходит на востоке.
rus_verbs:блестеть{}, // Снег блестит на солнце.
rus_verbs:побить{}, // Рысак побил всех лошадей на скачках.
rus_verbs:литься{}, // Реки крови льются на войне.
rus_verbs:держаться{}, // Ребёнок уже твёрдо держится на ногах.
rus_verbs:клубиться{}, // Пыль клубится на дороге.
инфинитив:написать{ aux stress="напис^ать" }, // Ты должен написать статью на английском языке
глагол:написать{ aux stress="напис^ать" }, // Он написал статью на русском языке.
// глагол:находиться{вид:несоверш}, // мой поезд находится на первом пути
// инфинитив:находиться{вид:несоверш},
rus_verbs:жить{}, // Было интересно жить на курорте.
rus_verbs:повидать{}, // Он много повидал на своём веку.
rus_verbs:разъезжаться{}, // Ноги разъезжаются не только на льду.
rus_verbs:расположиться{}, // Оба села расположились на берегу реки.
rus_verbs:объясняться{}, // Они объясняются на иностранном языке.
rus_verbs:прощаться{}, // Они долго прощались на вокзале.
rus_verbs:работать{}, // Она работает на ткацкой фабрике.
rus_verbs:купить{}, // Она купила молоко на рынке.
rus_verbs:поместиться{}, // Все книги поместились на полке.
глагол:проводить{вид:несоверш}, инфинитив:проводить{вид:несоверш}, // Нужно проводить теорию на практике.
rus_verbs:пожить{}, // Недолго она пожила на свете.
rus_verbs:краснеть{}, // Небо краснеет на закате.
rus_verbs:бывать{}, // На Волге бывает сильное волнение.
rus_verbs:ехать{}, // Мы туда ехали на автобусе.
rus_verbs:провести{}, // Мы провели месяц на даче.
rus_verbs:поздороваться{}, // Мы поздоровались при встрече на улице.
rus_verbs:расти{}, // Арбузы растут теперь не только на юге.
ГЛ_ИНФ(сидеть), // три больших пса сидят на траве
ГЛ_ИНФ(сесть), // три больших пса сели на траву
ГЛ_ИНФ(перевернуться), // На дороге перевернулся автомобиль
ГЛ_ИНФ(повезти), // я повезу тебя на машине
ГЛ_ИНФ(отвезти), // мы отвезем тебя на такси
ГЛ_ИНФ(пить), // пить на кухне чай
ГЛ_ИНФ(найти), // найти на острове
ГЛ_ИНФ(быть), // на этих костях есть следы зубов
ГЛ_ИНФ(высадиться), // помощники высадились на острове
ГЛ_ИНФ(делать),прилагательное:делающий{}, прилагательное:делавший{}, деепричастие:делая{}, // смотрю фильм о том, что пираты делали на необитаемом острове
ГЛ_ИНФ(случиться), // это случилось на опушке леса
ГЛ_ИНФ(продать),
ГЛ_ИНФ(есть) // кошки ели мой корм на песчаном берегу
}
#endregion VerbList
// Чтобы разрешить связывание в паттернах типа: смотреть на youtube
fact гл_предл
{
if context { Гл_НА_Предл предлог:в{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_НА_Предл предлог:на{} *:*{падеж:предл} }
then return true
}
// локатив
fact гл_предл
{
if context { Гл_НА_Предл предлог:на{} *:*{падеж:мест} }
then return true
}
#endregion ПРЕДЛОЖНЫЙ
#region ВИНИТЕЛЬНЫЙ
// НА+винительный падеж:
// ЗАБИРАТЬСЯ НА ВЕРШИНУ ГОРЫ
#region VerbList
wordentry_set Гл_НА_Вин=
{
rus_verbs:переметнуться{}, // Ее взгляд растерянно переметнулся на Лили.
rus_verbs:отогнать{}, // Водитель отогнал машину на стоянку.
rus_verbs:фапать{}, // Не фапай на желтяк и не перебивай.
rus_verbs:умножить{}, // Умножьте это количество примерно на 10.
//rus_verbs:умножать{},
rus_verbs:откатить{}, // Откатил Шпак валун на шлях и перекрыл им дорогу.
rus_verbs:откатывать{},
rus_verbs:доносить{}, // Вот и побежали на вас доносить.
rus_verbs:донести{},
rus_verbs:разбирать{}, // Ворованные автомобили злоумышленники разбирали на запчасти и продавали.
безлич_глагол:хватит{}, // - На одну атаку хватит.
rus_verbs:скупиться{}, // Он сражался за жизнь, не скупясь на хитрости и усилия, и пока этот стиль давал неплохие результаты.
rus_verbs:поскупиться{}, // Не поскупись на похвалы!
rus_verbs:подыматься{},
rus_verbs:транспортироваться{},
rus_verbs:бахнуть{}, // Бахнуть стакан на пол
rus_verbs:РАЗДЕЛИТЬ{}, // Президентские выборы разделили Венесуэлу на два непримиримых лагеря (РАЗДЕЛИТЬ)
rus_verbs:НАЦЕЛИВАТЬСЯ{}, // Невдалеке пролетел кондор, нацеливаясь на бизонью тушу. (НАЦЕЛИВАТЬСЯ)
rus_verbs:ВЫПЛЕСНУТЬ{}, // Низкий вибрирующий гул напоминал вулкан, вот-вот готовый выплеснуть на земную твердь потоки раскаленной лавы. (ВЫПЛЕСНУТЬ)
rus_verbs:ИСЧЕЗНУТЬ{}, // Оно фыркнуло и исчезло в лесу на другой стороне дороги (ИСЧЕЗНУТЬ)
rus_verbs:ВЫЗВАТЬ{}, // вызвать своего брата на поединок. (ВЫЗВАТЬ)
rus_verbs:ПОБРЫЗГАТЬ{}, // Матрос побрызгал немного фимиама на крошечный огонь (ПОБРЫЗГАТЬ/БРЫЗГАТЬ/БРЫЗНУТЬ/КАПНУТЬ/КАПАТЬ/ПОКАПАТЬ)
rus_verbs:БРЫЗГАТЬ{},
rus_verbs:БРЫЗНУТЬ{},
rus_verbs:КАПНУТЬ{},
rus_verbs:КАПАТЬ{},
rus_verbs:ПОКАПАТЬ{},
rus_verbs:ПООХОТИТЬСЯ{}, // Мы можем когда-нибудь вернуться и поохотиться на него. (ПООХОТИТЬСЯ/ОХОТИТЬСЯ)
rus_verbs:ОХОТИТЬСЯ{}, //
rus_verbs:ПОПАСТЬСЯ{}, // Не думал я, что они попадутся на это (ПОПАСТЬСЯ/НАРВАТЬСЯ/НАТОЛКНУТЬСЯ)
rus_verbs:НАРВАТЬСЯ{}, //
rus_verbs:НАТОЛКНУТЬСЯ{}, //
rus_verbs:ВЫСЛАТЬ{}, // Он выслал разведчиков на большое расстояние от основного отряда. (ВЫСЛАТЬ)
прилагательное:ПОХОЖИЙ{}, // Ты не выглядишь похожим на индейца (ПОХОЖИЙ)
rus_verbs:РАЗОРВАТЬ{}, // Через минуту он был мертв и разорван на части. (РАЗОРВАТЬ)
rus_verbs:СТОЛКНУТЬ{}, // Только быстрыми выпадами копья он сумел столкнуть их обратно на карниз. (СТОЛКНУТЬ/СТАЛКИВАТЬ)
rus_verbs:СТАЛКИВАТЬ{}, //
rus_verbs:СПУСТИТЬ{}, // Я побежал к ним, но они к тому времени спустили лодку на воду (СПУСТИТЬ)
rus_verbs:ПЕРЕБРАСЫВАТЬ{}, // Сирия перебрасывает на юг страны воинские подкрепления (ПЕРЕБРАСЫВАТЬ, ПЕРЕБРОСИТЬ, НАБРАСЫВАТЬ, НАБРОСИТЬ)
rus_verbs:ПЕРЕБРОСИТЬ{}, //
rus_verbs:НАБРАСЫВАТЬ{}, //
rus_verbs:НАБРОСИТЬ{}, //
rus_verbs:СВЕРНУТЬ{}, // Он вывел машину на бульвар и поехал на восток, а затем свернул на юг. (СВЕРНУТЬ/СВОРАЧИВАТЬ/ПОВЕРНУТЬ/ПОВОРАЧИВАТЬ)
rus_verbs:СВОРАЧИВАТЬ{}, // //
rus_verbs:ПОВЕРНУТЬ{}, //
rus_verbs:ПОВОРАЧИВАТЬ{}, //
rus_verbs:наорать{},
rus_verbs:ПРОДВИНУТЬСЯ{}, // Полк продвинется на десятки километров (ПРОДВИНУТЬСЯ)
rus_verbs:БРОСАТЬ{}, // Он бросает обещания на ветер (БРОСАТЬ)
rus_verbs:ОДОЛЖИТЬ{}, // Я вам одолжу книгу на десять дней (ОДОЛЖИТЬ)
rus_verbs:перегнать{}, // Скот нужно перегнать с этого пастбища на другое
rus_verbs:перегонять{},
rus_verbs:выгонять{},
rus_verbs:выгнать{},
rus_verbs:СВОДИТЬСЯ{}, // сейчас панели кузовов расходятся по десяткам покрасочных постов и потом сводятся вновь на общий конвейер (СВОДИТЬСЯ)
rus_verbs:ПОЖЕРТВОВАТЬ{}, // Бывший функционер компартии Эстонии пожертвовал деньги на расследования преступлений коммунизма (ПОЖЕРТВОВАТЬ)
rus_verbs:ПРОВЕРЯТЬ{}, // Школьников будут принудительно проверять на курение (ПРОВЕРЯТЬ)
rus_verbs:ОТПУСТИТЬ{}, // Приставы отпустят должников на отдых (ОТПУСТИТЬ)
rus_verbs:использоваться{}, // имеющийся у государства денежный запас активно используется на поддержание рынка акций
rus_verbs:назначаться{}, // назначаться на пост
rus_verbs:наблюдать{}, // Судья , долго наблюдавший в трубу , вдруг вскричал
rus_verbs:ШПИОНИТЬ{}, // Канадского офицера, шпионившего на Россию, приговорили к 20 годам тюрьмы (ШПИОНИТЬ НА вин)
rus_verbs:ЗАПЛАНИРОВАТЬ{}, // все деньги , запланированные на сейсмоукрепление домов на Камчатке (ЗАПЛАНИРОВАТЬ НА)
// rus_verbs:ПОХОДИТЬ{}, // больше походил на обвинительную речь , адресованную руководству республики (ПОХОДИТЬ НА)
rus_verbs:ДЕЙСТВОВАТЬ{}, // выявленный контрабандный канал действовал на постоянной основе (ДЕЙСТВОВАТЬ НА)
rus_verbs:ПЕРЕДАТЬ{}, // после чего должно быть передано на рассмотрение суда (ПЕРЕДАТЬ НА вин)
rus_verbs:НАЗНАЧИТЬСЯ{}, // Зимой на эту должность пытался назначиться народный депутат (НАЗНАЧИТЬСЯ НА)
rus_verbs:РЕШИТЬСЯ{}, // Франция решилась на одностороннее и рискованное военное вмешательство (РЕШИТЬСЯ НА)
rus_verbs:ОРИЕНТИРОВАТЬ{}, // Этот браузер полностью ориентирован на планшеты и сенсорный ввод (ОРИЕНТИРОВАТЬ НА вин)
rus_verbs:ЗАВЕСТИ{}, // на Витьку завели дело (ЗАВЕСТИ НА)
rus_verbs:ОБРУШИТЬСЯ{}, // В Северной Осетии на воинскую часть обрушилась снежная лавина (ОБРУШИТЬСЯ В, НА)
rus_verbs:НАСТРАИВАТЬСЯ{}, // гетеродин, настраивающийся на волну (НАСТРАИВАТЬСЯ НА)
rus_verbs:СУЩЕСТВОВАТЬ{}, // Он существует на средства родителей. (СУЩЕСТВОВАТЬ НА)
прилагательное:способный{}, // Он способен на убийство. (СПОСОБНЫЙ НА)
rus_verbs:посыпаться{}, // на Нину посыпались снежинки
инфинитив:нарезаться{ вид:несоверш }, // Урожай собирают механически или вручную, стебли нарезаются на куски и быстро транспортируются на перерабатывающий завод.
глагол:нарезаться{ вид:несоверш },
rus_verbs:пожаловать{}, // скандально известный певец пожаловал к нам на передачу
rus_verbs:показать{}, // Вадим показал на Колю
rus_verbs:съехаться{}, // Финалисты съехались на свои игры в Лос-Анжелес. (СЪЕХАТЬСЯ НА, В)
rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА)
rus_verbs:упасть{}, // В Таиланде на автобус с российскими туристами упал башенный кран (УПАСТЬ В, НА)
прилагательное:тугой{}, // Бабушка туга на ухо. (ТУГОЙ НА)
rus_verbs:свисать{}, // Волосы свисают на лоб. (свисать на)
rus_verbs:ЦЕНИТЬСЯ{}, // Всякая рабочая рука ценилась на вес золота. (ЦЕНИТЬСЯ НА)
rus_verbs:ШУМЕТЬ{}, // Вы шумите на весь дом! (ШУМЕТЬ НА)
rus_verbs:протянуться{}, // Дорога протянулась на сотни километров. (протянуться на)
rus_verbs:РАССЧИТАТЬ{}, // Книга рассчитана на массового читателя. (РАССЧИТАТЬ НА)
rus_verbs:СОРИЕНТИРОВАТЬ{}, // мы сориентировали процесс на повышение котировок (СОРИЕНТИРОВАТЬ НА)
rus_verbs:рыкнуть{}, // рыкнуть на остальных членов стаи (рыкнуть на)
rus_verbs:оканчиваться{}, // оканчиваться на звонкую согласную (оканчиваться на)
rus_verbs:выехать{}, // посигналить нарушителю, выехавшему на встречную полосу (выехать на)
rus_verbs:прийтись{}, // Пятое число пришлось на субботу.
rus_verbs:крениться{}, // корабль кренился на правый борт (крениться на)
rus_verbs:приходиться{}, // основной налоговый гнет приходится на средний бизнес (приходиться на)
rus_verbs:верить{}, // верить людям на слово (верить на слово)
rus_verbs:выезжать{}, // Завтра вся семья выезжает на новую квартиру.
rus_verbs:записать{}, // Запишите меня на завтрашний приём к доктору.
rus_verbs:пасть{}, // Жребий пал на меня.
rus_verbs:ездить{}, // Вчера мы ездили на оперу.
rus_verbs:влезть{}, // Мальчик влез на дерево.
rus_verbs:выбежать{}, // Мальчик выбежал из комнаты на улицу.
rus_verbs:разбиться{}, // окно разбилось на мелкие осколки
rus_verbs:бежать{}, // я бегу на урок
rus_verbs:сбегаться{}, // сбегаться на происшествие
rus_verbs:присылать{}, // присылать на испытание
rus_verbs:надавить{}, // надавить на педать
rus_verbs:внести{}, // внести законопроект на рассмотрение
rus_verbs:вносить{}, // вносить законопроект на рассмотрение
rus_verbs:поворачиваться{}, // поворачиваться на 180 градусов
rus_verbs:сдвинуть{}, // сдвинуть на несколько сантиметров
rus_verbs:опубликовать{}, // С.Митрохин опубликовал компромат на думских подельников Гудкова
rus_verbs:вырасти{}, // Официальный курс доллара вырос на 26 копеек.
rus_verbs:оглядываться{}, // оглядываться на девушек
rus_verbs:расходиться{}, // расходиться на отдых
rus_verbs:поскакать{}, // поскакать на службу
rus_verbs:прыгать{}, // прыгать на сцену
rus_verbs:приглашать{}, // приглашать на обед
rus_verbs:рваться{}, // Кусок ткани рвется на части
rus_verbs:понестись{}, // понестись на волю
rus_verbs:распространяться{}, // распространяться на всех жителей штата
инфинитив:просыпаться{ вид:соверш }, глагол:просыпаться{ вид:соверш }, // просыпаться на пол
инфинитив:просыпаться{ вид:несоверш }, глагол:просыпаться{ вид:несоверш },
деепричастие:просыпавшись{}, деепричастие:просыпаясь{},
rus_verbs:заехать{}, // заехать на пандус
rus_verbs:разобрать{}, // разобрать на составляющие
rus_verbs:опускаться{}, // опускаться на колени
rus_verbs:переехать{}, // переехать на конспиративную квартиру
rus_verbs:закрывать{}, // закрывать глаза на действия конкурентов
rus_verbs:поместить{}, // поместить на поднос
rus_verbs:отходить{}, // отходить на подготовленные позиции
rus_verbs:сыпаться{}, // сыпаться на плечи
rus_verbs:отвезти{}, // отвезти на занятия
rus_verbs:накинуть{}, // накинуть на плечи
rus_verbs:отлететь{}, // отлететь на пол
rus_verbs:закинуть{}, // закинуть на чердак
rus_verbs:зашипеть{}, // зашипеть на собаку
rus_verbs:прогреметь{}, // прогреметь на всю страну
rus_verbs:повалить{}, // повалить на стол
rus_verbs:опереть{}, // опереть на фундамент
rus_verbs:забросить{}, // забросить на антресоль
rus_verbs:подействовать{}, // подействовать на материал
rus_verbs:разделять{}, // разделять на части
rus_verbs:прикрикнуть{}, // прикрикнуть на детей
rus_verbs:разложить{}, // разложить на множители
rus_verbs:провожать{}, // провожать на работу
rus_verbs:катить{}, // катить на стройку
rus_verbs:наложить{}, // наложить запрет на проведение операций с недвижимостью
rus_verbs:сохранять{}, // сохранять на память
rus_verbs:злиться{}, // злиться на друга
rus_verbs:оборачиваться{}, // оборачиваться на свист
rus_verbs:сползти{}, // сползти на землю
rus_verbs:записывать{}, // записывать на ленту
rus_verbs:загнать{}, // загнать на дерево
rus_verbs:забормотать{}, // забормотать на ухо
rus_verbs:протиснуться{}, // протиснуться на самый край
rus_verbs:заторопиться{}, // заторопиться на вручение премии
rus_verbs:гаркнуть{}, // гаркнуть на шалунов
rus_verbs:навалиться{}, // навалиться на виновника всей толпой
rus_verbs:проскользнуть{}, // проскользнуть на крышу дома
rus_verbs:подтянуть{}, // подтянуть на палубу
rus_verbs:скатиться{}, // скатиться на двойки
rus_verbs:давить{}, // давить на жалость
rus_verbs:намекнуть{}, // намекнуть на новые обстоятельства
rus_verbs:замахнуться{}, // замахнуться на святое
rus_verbs:заменить{}, // заменить на свежую салфетку
rus_verbs:свалить{}, // свалить на землю
rus_verbs:стекать{}, // стекать на оголенные провода
rus_verbs:увеличиваться{}, // увеличиваться на сотню процентов
rus_verbs:развалиться{}, // развалиться на части
rus_verbs:сердиться{}, // сердиться на товарища
rus_verbs:обронить{}, // обронить на пол
rus_verbs:подсесть{}, // подсесть на наркоту
rus_verbs:реагировать{}, // реагировать на импульсы
rus_verbs:отпускать{}, // отпускать на волю
rus_verbs:прогнать{}, // прогнать на рабочее место
rus_verbs:ложить{}, // ложить на стол
rus_verbs:рвать{}, // рвать на части
rus_verbs:разлететься{}, // разлететься на кусочки
rus_verbs:превышать{}, // превышать на существенную величину
rus_verbs:сбиться{}, // сбиться на рысь
rus_verbs:пристроиться{}, // пристроиться на хорошую работу
rus_verbs:удрать{}, // удрать на пастбище
rus_verbs:толкать{}, // толкать на преступление
rus_verbs:посматривать{}, // посматривать на экран
rus_verbs:набирать{}, // набирать на судно
rus_verbs:отступать{}, // отступать на дерево
rus_verbs:подуть{}, // подуть на молоко
rus_verbs:плеснуть{}, // плеснуть на голову
rus_verbs:соскользнуть{}, // соскользнуть на землю
rus_verbs:затаить{}, // затаить на кого-то обиду
rus_verbs:обижаться{}, // обижаться на Колю
rus_verbs:смахнуть{}, // смахнуть на пол
rus_verbs:застегнуть{}, // застегнуть на все пуговицы
rus_verbs:спускать{}, // спускать на землю
rus_verbs:греметь{}, // греметь на всю округу
rus_verbs:скосить{}, // скосить на соседа глаз
rus_verbs:отважиться{}, // отважиться на прыжок
rus_verbs:литься{}, // литься на землю
rus_verbs:порвать{}, // порвать на тряпки
rus_verbs:проследовать{}, // проследовать на сцену
rus_verbs:надевать{}, // надевать на голову
rus_verbs:проскочить{}, // проскочить на красный свет
rus_verbs:прилечь{}, // прилечь на диванчик
rus_verbs:разделиться{}, // разделиться на небольшие группы
rus_verbs:завыть{}, // завыть на луну
rus_verbs:переносить{}, // переносить на другую машину
rus_verbs:наговорить{}, // наговорить на сотню рублей
rus_verbs:намекать{}, // намекать на новые обстоятельства
rus_verbs:нападать{}, // нападать на охранников
rus_verbs:убегать{}, // убегать на другое место
rus_verbs:тратить{}, // тратить на развлечения
rus_verbs:присаживаться{}, // присаживаться на корточки
rus_verbs:переместиться{}, // переместиться на вторую линию
rus_verbs:завалиться{}, // завалиться на диван
rus_verbs:удалиться{}, // удалиться на покой
rus_verbs:уменьшаться{}, // уменьшаться на несколько процентов
rus_verbs:обрушить{}, // обрушить на голову
rus_verbs:резать{}, // резать на части
rus_verbs:умчаться{}, // умчаться на юг
rus_verbs:навернуться{}, // навернуться на камень
rus_verbs:примчаться{}, // примчаться на матч
rus_verbs:издавать{}, // издавать на собственные средства
rus_verbs:переключить{}, // переключить на другой язык
rus_verbs:отправлять{}, // отправлять на пенсию
rus_verbs:залечь{}, // залечь на дно
rus_verbs:установиться{}, // установиться на диск
rus_verbs:направлять{}, // направлять на дополнительное обследование
rus_verbs:разрезать{}, // разрезать на части
rus_verbs:оскалиться{}, // оскалиться на прохожего
rus_verbs:рычать{}, // рычать на пьяных
rus_verbs:погружаться{}, // погружаться на дно
rus_verbs:опираться{}, // опираться на костыли
rus_verbs:поторопиться{}, // поторопиться на учебу
rus_verbs:сдвинуться{}, // сдвинуться на сантиметр
rus_verbs:увеличить{}, // увеличить на процент
rus_verbs:опускать{}, // опускать на землю
rus_verbs:созвать{}, // созвать на митинг
rus_verbs:делить{}, // делить на части
rus_verbs:пробиться{}, // пробиться на заключительную часть
rus_verbs:простираться{}, // простираться на много миль
rus_verbs:забить{}, // забить на учебу
rus_verbs:переложить{}, // переложить на чужие плечи
rus_verbs:грохнуться{}, // грохнуться на землю
rus_verbs:прорваться{}, // прорваться на сцену
rus_verbs:разлить{}, // разлить на землю
rus_verbs:укладываться{}, // укладываться на ночевку
rus_verbs:уволить{}, // уволить на пенсию
rus_verbs:наносить{}, // наносить на кожу
rus_verbs:набежать{}, // набежать на берег
rus_verbs:заявиться{}, // заявиться на стрельбище
rus_verbs:налиться{}, // налиться на крышку
rus_verbs:надвигаться{}, // надвигаться на берег
rus_verbs:распустить{}, // распустить на каникулы
rus_verbs:переключиться{}, // переключиться на другую задачу
rus_verbs:чихнуть{}, // чихнуть на окружающих
rus_verbs:шлепнуться{}, // шлепнуться на спину
rus_verbs:устанавливать{}, // устанавливать на крышу
rus_verbs:устанавливаться{}, // устанавливаться на крышу
rus_verbs:устраиваться{}, // устраиваться на работу
rus_verbs:пропускать{}, // пропускать на стадион
инфинитив:сбегать{ вид:соверш }, глагол:сбегать{ вид:соверш }, // сбегать на фильм
инфинитив:сбегать{ вид:несоверш }, глагол:сбегать{ вид:несоверш },
деепричастие:сбегав{}, деепричастие:сбегая{},
rus_verbs:показываться{}, // показываться на глаза
rus_verbs:прибегать{}, // прибегать на урок
rus_verbs:съездить{}, // съездить на ферму
rus_verbs:прославиться{}, // прославиться на всю страну
rus_verbs:опрокинуться{}, // опрокинуться на спину
rus_verbs:насыпать{}, // насыпать на землю
rus_verbs:употреблять{}, // употреблять на корм скоту
rus_verbs:пристроить{}, // пристроить на работу
rus_verbs:заворчать{}, // заворчать на вошедшего
rus_verbs:завязаться{}, // завязаться на поставщиков
rus_verbs:сажать{}, // сажать на стул
rus_verbs:напрашиваться{}, // напрашиваться на жесткие ответные меры
rus_verbs:заменять{}, // заменять на исправную
rus_verbs:нацепить{}, // нацепить на голову
rus_verbs:сыпать{}, // сыпать на землю
rus_verbs:закрываться{}, // закрываться на ремонт
rus_verbs:распространиться{}, // распространиться на всю популяцию
rus_verbs:поменять{}, // поменять на велосипед
rus_verbs:пересесть{}, // пересесть на велосипеды
rus_verbs:подоспеть{}, // подоспеть на разбор
rus_verbs:шипеть{}, // шипеть на собак
rus_verbs:поделить{}, // поделить на части
rus_verbs:подлететь{}, // подлететь на расстояние выстрела
rus_verbs:нажимать{}, // нажимать на все кнопки
rus_verbs:распасться{}, // распасться на части
rus_verbs:приволочь{}, // приволочь на диван
rus_verbs:пожить{}, // пожить на один доллар
rus_verbs:устремляться{}, // устремляться на свободу
rus_verbs:смахивать{}, // смахивать на пол
rus_verbs:забежать{}, // забежать на обед
rus_verbs:увеличиться{}, // увеличиться на существенную величину
rus_verbs:прокрасться{}, // прокрасться на склад
rus_verbs:пущать{}, // пущать на постой
rus_verbs:отклонить{}, // отклонить на несколько градусов
rus_verbs:насмотреться{}, // насмотреться на безобразия
rus_verbs:настроить{}, // настроить на короткие волны
rus_verbs:уменьшиться{}, // уменьшиться на пару сантиметров
rus_verbs:поменяться{}, // поменяться на другую книжку
rus_verbs:расколоться{}, // расколоться на части
rus_verbs:разлиться{}, // разлиться на землю
rus_verbs:срываться{}, // срываться на жену
rus_verbs:осудить{}, // осудить на пожизненное заключение
rus_verbs:передвинуть{}, // передвинуть на первое место
rus_verbs:допускаться{}, // допускаться на полигон
rus_verbs:задвинуть{}, // задвинуть на полку
rus_verbs:повлиять{}, // повлиять на оценку
rus_verbs:отбавлять{}, // отбавлять на осмотр
rus_verbs:сбрасывать{}, // сбрасывать на землю
rus_verbs:накинуться{}, // накинуться на случайных прохожих
rus_verbs:пролить{}, // пролить на кожу руки
rus_verbs:затащить{}, // затащить на сеновал
rus_verbs:перебежать{}, // перебежать на сторону противника
rus_verbs:наливать{}, // наливать на скатерть
rus_verbs:пролезть{}, // пролезть на сцену
rus_verbs:откладывать{}, // откладывать на черный день
rus_verbs:распадаться{}, // распадаться на небольшие фрагменты
rus_verbs:перечислить{}, // перечислить на счет
rus_verbs:закачаться{}, // закачаться на верхний уровень
rus_verbs:накрениться{}, // накрениться на правый борт
rus_verbs:подвинуться{}, // подвинуться на один уровень
rus_verbs:разнести{}, // разнести на мелкие кусочки
rus_verbs:зажить{}, // зажить на широкую ногу
rus_verbs:оглохнуть{}, // оглохнуть на правое ухо
rus_verbs:посетовать{}, // посетовать на бюрократизм
rus_verbs:уводить{}, // уводить на осмотр
rus_verbs:ускакать{}, // ускакать на забег
rus_verbs:посветить{}, // посветить на стену
rus_verbs:разрываться{}, // разрываться на части
rus_verbs:побросать{}, // побросать на землю
rus_verbs:карабкаться{}, // карабкаться на скалу
rus_verbs:нахлынуть{}, // нахлынуть на кого-то
rus_verbs:разлетаться{}, // разлетаться на мелкие осколочки
rus_verbs:среагировать{}, // среагировать на сигнал
rus_verbs:претендовать{}, // претендовать на приз
rus_verbs:дунуть{}, // дунуть на одуванчик
rus_verbs:переводиться{}, // переводиться на другую работу
rus_verbs:перевезти{}, // перевезти на другую площадку
rus_verbs:топать{}, // топать на урок
rus_verbs:относить{}, // относить на склад
rus_verbs:сбивать{}, // сбивать на землю
rus_verbs:укладывать{}, // укладывать на спину
rus_verbs:укатить{}, // укатить на отдых
rus_verbs:убирать{}, // убирать на полку
rus_verbs:опасть{}, // опасть на землю
rus_verbs:ронять{}, // ронять на снег
rus_verbs:пялиться{}, // пялиться на тело
rus_verbs:глазеть{}, // глазеть на тело
rus_verbs:снижаться{}, // снижаться на безопасную высоту
rus_verbs:запрыгнуть{}, // запрыгнуть на платформу
rus_verbs:разбиваться{}, // разбиваться на главы
rus_verbs:сгодиться{}, // сгодиться на фарш
rus_verbs:перескочить{}, // перескочить на другую страницу
rus_verbs:нацелиться{}, // нацелиться на главную добычу
rus_verbs:заезжать{}, // заезжать на бордюр
rus_verbs:забираться{}, // забираться на крышу
rus_verbs:проорать{}, // проорать на всё село
rus_verbs:сбежаться{}, // сбежаться на шум
rus_verbs:сменять{}, // сменять на хлеб
rus_verbs:мотать{}, // мотать на ус
rus_verbs:раскалываться{}, // раскалываться на две половинки
rus_verbs:коситься{}, // коситься на режиссёра
rus_verbs:плевать{}, // плевать на законы
rus_verbs:ссылаться{}, // ссылаться на авторитетное мнение
rus_verbs:наставить{}, // наставить на путь истинный
rus_verbs:завывать{}, // завывать на Луну
rus_verbs:опаздывать{}, // опаздывать на совещание
rus_verbs:залюбоваться{}, // залюбоваться на пейзаж
rus_verbs:повергнуть{}, // повергнуть на землю
rus_verbs:надвинуть{}, // надвинуть на лоб
rus_verbs:стекаться{}, // стекаться на площадь
rus_verbs:обозлиться{}, // обозлиться на тренера
rus_verbs:оттянуть{}, // оттянуть на себя
rus_verbs:истратить{}, // истратить на дешевых шлюх
rus_verbs:вышвырнуть{}, // вышвырнуть на улицу
rus_verbs:затолкать{}, // затолкать на верхнюю полку
rus_verbs:заскочить{}, // заскочить на огонек
rus_verbs:проситься{}, // проситься на улицу
rus_verbs:натыкаться{}, // натыкаться на борщевик
rus_verbs:обрушиваться{}, // обрушиваться на митингующих
rus_verbs:переписать{}, // переписать на чистовик
rus_verbs:переноситься{}, // переноситься на другое устройство
rus_verbs:напроситься{}, // напроситься на обидный ответ
rus_verbs:натягивать{}, // натягивать на ноги
rus_verbs:кидаться{}, // кидаться на прохожих
rus_verbs:откликаться{}, // откликаться на призыв
rus_verbs:поспевать{}, // поспевать на балет
rus_verbs:обратиться{}, // обратиться на кафедру
rus_verbs:полюбоваться{}, // полюбоваться на бюст
rus_verbs:таращиться{}, // таращиться на мустангов
rus_verbs:напороться{}, // напороться на колючки
rus_verbs:раздать{}, // раздать на руки
rus_verbs:дивиться{}, // дивиться на танцовщиц
rus_verbs:назначать{}, // назначать на ответственнейший пост
rus_verbs:кидать{}, // кидать на балкон
rus_verbs:нахлобучить{}, // нахлобучить на башку
rus_verbs:увлекать{}, // увлекать на луг
rus_verbs:ругнуться{}, // ругнуться на животину
rus_verbs:переселиться{}, // переселиться на хутор
rus_verbs:разрывать{}, // разрывать на части
rus_verbs:утащить{}, // утащить на дерево
rus_verbs:наставлять{}, // наставлять на путь
rus_verbs:соблазнить{}, // соблазнить на обмен
rus_verbs:накладывать{}, // накладывать на рану
rus_verbs:набрести{}, // набрести на грибную поляну
rus_verbs:наведываться{}, // наведываться на прежнюю работу
rus_verbs:погулять{}, // погулять на чужие деньги
rus_verbs:уклоняться{}, // уклоняться на два градуса влево
rus_verbs:слезать{}, // слезать на землю
rus_verbs:клевать{}, // клевать на мотыля
// rus_verbs:назначаться{}, // назначаться на пост
rus_verbs:напялить{}, // напялить на голову
rus_verbs:натянуться{}, // натянуться на рамку
rus_verbs:разгневаться{}, // разгневаться на придворных
rus_verbs:эмигрировать{}, // эмигрировать на Кипр
rus_verbs:накатить{}, // накатить на основу
rus_verbs:пригнать{}, // пригнать на пастбище
rus_verbs:обречь{}, // обречь на мучения
rus_verbs:сокращаться{}, // сокращаться на четверть
rus_verbs:оттеснить{}, // оттеснить на пристань
rus_verbs:подбить{}, // подбить на аферу
rus_verbs:заманить{}, // заманить на дерево
инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать на кустик
// деепричастие:пописав{ aux stress="поп^исать" },
rus_verbs:посходить{}, // посходить на перрон
rus_verbs:налечь{}, // налечь на мясцо
rus_verbs:отбирать{}, // отбирать на флот
rus_verbs:нашептывать{}, // нашептывать на ухо
rus_verbs:откладываться{}, // откладываться на будущее
rus_verbs:залаять{}, // залаять на грабителя
rus_verbs:настроиться{}, // настроиться на прием
rus_verbs:разбивать{}, // разбивать на куски
rus_verbs:пролиться{}, // пролиться на почву
rus_verbs:сетовать{}, // сетовать на объективные трудности
rus_verbs:подвезти{}, // подвезти на митинг
rus_verbs:припереться{}, // припереться на праздник
rus_verbs:подталкивать{}, // подталкивать на прыжок
rus_verbs:прорываться{}, // прорываться на сцену
rus_verbs:снижать{}, // снижать на несколько процентов
rus_verbs:нацелить{}, // нацелить на танк
rus_verbs:расколоть{}, // расколоть на два куска
rus_verbs:увозить{}, // увозить на обкатку
rus_verbs:оседать{}, // оседать на дно
rus_verbs:съедать{}, // съедать на ужин
rus_verbs:навлечь{}, // навлечь на себя
rus_verbs:равняться{}, // равняться на лучших
rus_verbs:сориентироваться{}, // сориентироваться на местности
rus_verbs:снизить{}, // снизить на несколько процентов
rus_verbs:перенестись{}, // перенестись на много лет назад
rus_verbs:завезти{}, // завезти на склад
rus_verbs:проложить{}, // проложить на гору
rus_verbs:понадеяться{}, // понадеяться на удачу
rus_verbs:заступить{}, // заступить на вахту
rus_verbs:засеменить{}, // засеменить на выход
rus_verbs:запирать{}, // запирать на ключ
rus_verbs:скатываться{}, // скатываться на землю
rus_verbs:дробить{}, // дробить на части
rus_verbs:разваливаться{}, // разваливаться на кусочки
rus_verbs:завозиться{}, // завозиться на склад
rus_verbs:нанимать{}, // нанимать на дневную работу
rus_verbs:поспеть{}, // поспеть на концерт
rus_verbs:променять{}, // променять на сытость
rus_verbs:переправить{}, // переправить на север
rus_verbs:налетать{}, // налетать на силовое поле
rus_verbs:затворить{}, // затворить на замок
rus_verbs:подогнать{}, // подогнать на пристань
rus_verbs:наехать{}, // наехать на камень
rus_verbs:распевать{}, // распевать на разные голоса
rus_verbs:разносить{}, // разносить на клочки
rus_verbs:преувеличивать{}, // преувеличивать на много килограммов
rus_verbs:хромать{}, // хромать на одну ногу
rus_verbs:телеграфировать{}, // телеграфировать на базу
rus_verbs:порезать{}, // порезать на лоскуты
rus_verbs:порваться{}, // порваться на части
rus_verbs:загонять{}, // загонять на дерево
rus_verbs:отбывать{}, // отбывать на место службы
rus_verbs:усаживаться{}, // усаживаться на трон
rus_verbs:накопить{}, // накопить на квартиру
rus_verbs:зыркнуть{}, // зыркнуть на визитера
rus_verbs:копить{}, // копить на машину
rus_verbs:помещать{}, // помещать на верхнюю грань
rus_verbs:сползать{}, // сползать на снег
rus_verbs:попроситься{}, // попроситься на улицу
rus_verbs:перетащить{}, // перетащить на чердак
rus_verbs:растащить{}, // растащить на сувениры
rus_verbs:ниспадать{}, // ниспадать на землю
rus_verbs:сфотографировать{}, // сфотографировать на память
rus_verbs:нагонять{}, // нагонять на конкурентов страх
rus_verbs:покушаться{}, // покушаться на понтифика
rus_verbs:покуситься{},
rus_verbs:наняться{}, // наняться на службу
rus_verbs:просачиваться{}, // просачиваться на поверхность
rus_verbs:пускаться{}, // пускаться на ветер
rus_verbs:отваживаться{}, // отваживаться на прыжок
rus_verbs:досадовать{}, // досадовать на объективные трудности
rus_verbs:унестись{}, // унестись на небо
rus_verbs:ухудшаться{}, // ухудшаться на несколько процентов
rus_verbs:насадить{}, // насадить на копьё
rus_verbs:нагрянуть{}, // нагрянуть на праздник
rus_verbs:зашвырнуть{}, // зашвырнуть на полку
rus_verbs:грешить{}, // грешить на постояльцев
rus_verbs:просочиться{}, // просочиться на поверхность
rus_verbs:надоумить{}, // надоумить на глупость
rus_verbs:намотать{}, // намотать на шпиндель
rus_verbs:замкнуть{}, // замкнуть на корпус
rus_verbs:цыкнуть{}, // цыкнуть на детей
rus_verbs:переворачиваться{}, // переворачиваться на спину
rus_verbs:соваться{}, // соваться на площать
rus_verbs:отлучиться{}, // отлучиться на обед
rus_verbs:пенять{}, // пенять на себя
rus_verbs:нарезать{}, // нарезать на ломтики
rus_verbs:поставлять{}, // поставлять на Кипр
rus_verbs:залезать{}, // залезать на балкон
rus_verbs:отлучаться{}, // отлучаться на обед
rus_verbs:сбиваться{}, // сбиваться на шаг
rus_verbs:таращить{}, // таращить глаза на вошедшего
rus_verbs:прошмыгнуть{}, // прошмыгнуть на кухню
rus_verbs:опережать{}, // опережать на пару сантиметров
rus_verbs:переставить{}, // переставить на стол
rus_verbs:раздирать{}, // раздирать на части
rus_verbs:затвориться{}, // затвориться на засовы
rus_verbs:материться{}, // материться на кого-то
rus_verbs:наскочить{}, // наскочить на риф
rus_verbs:набираться{}, // набираться на борт
rus_verbs:покрикивать{}, // покрикивать на помощников
rus_verbs:заменяться{}, // заменяться на более новый
rus_verbs:подсадить{}, // подсадить на верхнюю полку
rus_verbs:проковылять{}, // проковылять на кухню
rus_verbs:прикатить{}, // прикатить на старт
rus_verbs:залететь{}, // залететь на чужую территорию
rus_verbs:загрузить{}, // загрузить на конвейер
rus_verbs:уплывать{}, // уплывать на материк
rus_verbs:опозорить{}, // опозорить на всю деревню
rus_verbs:провоцировать{}, // провоцировать на ответную агрессию
rus_verbs:забивать{}, // забивать на учебу
rus_verbs:набегать{}, // набегать на прибрежные деревни
rus_verbs:запираться{}, // запираться на ключ
rus_verbs:фотографировать{}, // фотографировать на мыльницу
rus_verbs:подымать{}, // подымать на недосягаемую высоту
rus_verbs:съезжаться{}, // съезжаться на симпозиум
rus_verbs:отвлекаться{}, // отвлекаться на игру
rus_verbs:проливать{}, // проливать на брюки
rus_verbs:спикировать{}, // спикировать на зазевавшегося зайца
rus_verbs:уползти{}, // уползти на вершину холма
rus_verbs:переместить{}, // переместить на вторую палубу
rus_verbs:превысить{}, // превысить на несколько метров
rus_verbs:передвинуться{}, // передвинуться на соседнюю клетку
rus_verbs:спровоцировать{}, // спровоцировать на бросок
rus_verbs:сместиться{}, // сместиться на соседнюю клетку
rus_verbs:заготовить{}, // заготовить на зиму
rus_verbs:плеваться{}, // плеваться на пол
rus_verbs:переселить{}, // переселить на север
rus_verbs:напирать{}, // напирать на дверь
rus_verbs:переезжать{}, // переезжать на другой этаж
rus_verbs:приподнимать{}, // приподнимать на несколько сантиметров
rus_verbs:трогаться{}, // трогаться на красный свет
rus_verbs:надвинуться{}, // надвинуться на глаза
rus_verbs:засмотреться{}, // засмотреться на купальники
rus_verbs:убыть{}, // убыть на фронт
rus_verbs:передвигать{}, // передвигать на второй уровень
rus_verbs:отвозить{}, // отвозить на свалку
rus_verbs:обрекать{}, // обрекать на гибель
rus_verbs:записываться{}, // записываться на танцы
rus_verbs:настраивать{}, // настраивать на другой диапазон
rus_verbs:переписывать{}, // переписывать на диск
rus_verbs:израсходовать{}, // израсходовать на гонки
rus_verbs:обменять{}, // обменять на перспективного игрока
rus_verbs:трубить{}, // трубить на всю округу
rus_verbs:набрасываться{}, // набрасываться на жертву
rus_verbs:чихать{}, // чихать на правила
rus_verbs:наваливаться{}, // наваливаться на рычаг
rus_verbs:сподобиться{}, // сподобиться на повторный анализ
rus_verbs:намазать{}, // намазать на хлеб
rus_verbs:прореагировать{}, // прореагировать на вызов
rus_verbs:зачислить{}, // зачислить на факультет
rus_verbs:наведаться{}, // наведаться на склад
rus_verbs:откидываться{}, // откидываться на спинку кресла
rus_verbs:захромать{}, // захромать на левую ногу
rus_verbs:перекочевать{}, // перекочевать на другой берег
rus_verbs:накатываться{}, // накатываться на песчаный берег
rus_verbs:приостановить{}, // приостановить на некоторое время
rus_verbs:запрятать{}, // запрятать на верхнюю полочку
rus_verbs:прихрамывать{}, // прихрамывать на правую ногу
rus_verbs:упорхнуть{}, // упорхнуть на свободу
rus_verbs:расстегивать{}, // расстегивать на пальто
rus_verbs:напуститься{}, // напуститься на бродягу
rus_verbs:накатывать{}, // накатывать на оригинал
rus_verbs:наезжать{}, // наезжать на простофилю
rus_verbs:тявкнуть{}, // тявкнуть на подошедшего человека
rus_verbs:отрядить{}, // отрядить на починку
rus_verbs:положиться{}, // положиться на главаря
rus_verbs:опрокидывать{}, // опрокидывать на голову
rus_verbs:поторапливаться{}, // поторапливаться на рейс
rus_verbs:налагать{}, // налагать на заемщика
rus_verbs:скопировать{}, // скопировать на диск
rus_verbs:опадать{}, // опадать на землю
rus_verbs:купиться{}, // купиться на посулы
rus_verbs:гневаться{}, // гневаться на слуг
rus_verbs:слететься{}, // слететься на раздачу
rus_verbs:убавить{}, // убавить на два уровня
rus_verbs:спихнуть{}, // спихнуть на соседа
rus_verbs:накричать{}, // накричать на ребенка
rus_verbs:приберечь{}, // приберечь на ужин
rus_verbs:приклеить{}, // приклеить на ветровое стекло
rus_verbs:ополчиться{}, // ополчиться на посредников
rus_verbs:тратиться{}, // тратиться на сувениры
rus_verbs:слетаться{}, // слетаться на свет
rus_verbs:доставляться{}, // доставляться на базу
rus_verbs:поплевать{}, // поплевать на руки
rus_verbs:огрызаться{}, // огрызаться на замечание
rus_verbs:попереться{}, // попереться на рынок
rus_verbs:растягиваться{}, // растягиваться на полу
rus_verbs:повергать{}, // повергать на землю
rus_verbs:ловиться{}, // ловиться на мотыля
rus_verbs:наседать{}, // наседать на обороняющихся
rus_verbs:развалить{}, // развалить на кирпичи
rus_verbs:разломить{}, // разломить на несколько частей
rus_verbs:примерить{}, // примерить на себя
rus_verbs:лепиться{}, // лепиться на стену
rus_verbs:скопить{}, // скопить на старость
rus_verbs:затратить{}, // затратить на ликвидацию последствий
rus_verbs:притащиться{}, // притащиться на гулянку
rus_verbs:осерчать{}, // осерчать на прислугу
rus_verbs:натравить{}, // натравить на медведя
rus_verbs:ссыпать{}, // ссыпать на землю
rus_verbs:подвозить{}, // подвозить на пристань
rus_verbs:мобилизовать{}, // мобилизовать на сборы
rus_verbs:смотаться{}, // смотаться на работу
rus_verbs:заглядеться{}, // заглядеться на девчонок
rus_verbs:таскаться{}, // таскаться на работу
rus_verbs:разгружать{}, // разгружать на транспортер
rus_verbs:потреблять{}, // потреблять на кондиционирование
инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять на базу
деепричастие:сгоняв{},
rus_verbs:посылаться{}, // посылаться на разведку
rus_verbs:окрыситься{}, // окрыситься на кого-то
rus_verbs:отлить{}, // отлить на сковороду
rus_verbs:шикнуть{}, // шикнуть на детишек
rus_verbs:уповать{}, // уповать на бескорысную помощь
rus_verbs:класться{}, // класться на стол
rus_verbs:поковылять{}, // поковылять на выход
rus_verbs:навевать{}, // навевать на собравшихся скуку
rus_verbs:накладываться{}, // накладываться на грунтовку
rus_verbs:наноситься{}, // наноситься на чистую кожу
// rus_verbs:запланировать{}, // запланировать на среду
rus_verbs:кувыркнуться{}, // кувыркнуться на землю
rus_verbs:гавкнуть{}, // гавкнуть на хозяина
rus_verbs:перестроиться{}, // перестроиться на новый лад
rus_verbs:расходоваться{}, // расходоваться на образование
rus_verbs:дуться{}, // дуться на бабушку
rus_verbs:перетаскивать{}, // перетаскивать на рабочий стол
rus_verbs:издаться{}, // издаться на деньги спонсоров
rus_verbs:смещаться{}, // смещаться на несколько миллиметров
rus_verbs:зазывать{}, // зазывать на новогоднюю распродажу
rus_verbs:пикировать{}, // пикировать на окопы
rus_verbs:чертыхаться{}, // чертыхаться на мешающихся детей
rus_verbs:зудить{}, // зудить на ухо
rus_verbs:подразделяться{}, // подразделяться на группы
rus_verbs:изливаться{}, // изливаться на землю
rus_verbs:помочиться{}, // помочиться на траву
rus_verbs:примерять{}, // примерять на себя
rus_verbs:разрядиться{}, // разрядиться на землю
rus_verbs:мотнуться{}, // мотнуться на крышу
rus_verbs:налегать{}, // налегать на весла
rus_verbs:зацокать{}, // зацокать на куриц
rus_verbs:наниматься{}, // наниматься на корабль
rus_verbs:сплевывать{}, // сплевывать на землю
rus_verbs:настучать{}, // настучать на саботажника
rus_verbs:приземляться{}, // приземляться на брюхо
rus_verbs:наталкиваться{}, // наталкиваться на объективные трудности
rus_verbs:посигналить{}, // посигналить нарушителю, выехавшему на встречную полосу
rus_verbs:серчать{}, // серчать на нерасторопную помощницу
rus_verbs:сваливать{}, // сваливать на подоконник
rus_verbs:засобираться{}, // засобираться на работу
rus_verbs:распилить{}, // распилить на одинаковые бруски
//rus_verbs:умножать{}, // умножать на константу
rus_verbs:копировать{}, // копировать на диск
rus_verbs:накрутить{}, // накрутить на руку
rus_verbs:навалить{}, // навалить на телегу
rus_verbs:натолкнуть{}, // натолкнуть на свежую мысль
rus_verbs:шлепаться{}, // шлепаться на бетон
rus_verbs:ухлопать{}, // ухлопать на скупку произведений искусства
rus_verbs:замахиваться{}, // замахиваться на авторитетнейшее мнение
rus_verbs:посягнуть{}, // посягнуть на святое
rus_verbs:разменять{}, // разменять на мелочь
rus_verbs:откатываться{}, // откатываться на заранее подготовленные позиции
rus_verbs:усаживать{}, // усаживать на скамейку
rus_verbs:натаскать{}, // натаскать на поиск наркотиков
rus_verbs:зашикать{}, // зашикать на кошку
rus_verbs:разломать{}, // разломать на равные части
rus_verbs:приглашаться{}, // приглашаться на сцену
rus_verbs:присягать{}, // присягать на верность
rus_verbs:запрограммировать{}, // запрограммировать на постоянную уборку
rus_verbs:расщедриться{}, // расщедриться на новый компьютер
rus_verbs:насесть{}, // насесть на двоечников
rus_verbs:созывать{}, // созывать на собрание
rus_verbs:позариться{}, // позариться на чужое добро
rus_verbs:перекидываться{}, // перекидываться на соседние здания
rus_verbs:наползать{}, // наползать на неповрежденную ткань
rus_verbs:изрубить{}, // изрубить на мелкие кусочки
rus_verbs:наворачиваться{}, // наворачиваться на глаза
rus_verbs:раскричаться{}, // раскричаться на всю округу
rus_verbs:переползти{}, // переползти на светлую сторону
rus_verbs:уполномочить{}, // уполномочить на разведовательную операцию
rus_verbs:мочиться{}, // мочиться на трупы убитых врагов
rus_verbs:радировать{}, // радировать на базу
rus_verbs:промотать{}, // промотать на начало
rus_verbs:заснять{}, // заснять на видео
rus_verbs:подбивать{}, // подбивать на матч-реванш
rus_verbs:наплевать{}, // наплевать на справедливость
rus_verbs:подвывать{}, // подвывать на луну
rus_verbs:расплескать{}, // расплескать на пол
rus_verbs:польститься{}, // польститься на бесплатный сыр
rus_verbs:помчать{}, // помчать на работу
rus_verbs:съезжать{}, // съезжать на обочину
rus_verbs:нашептать{}, // нашептать кому-то на ухо
rus_verbs:наклеить{}, // наклеить на доску объявлений
rus_verbs:завозить{}, // завозить на склад
rus_verbs:заявляться{}, // заявляться на любимую работу
rus_verbs:наглядеться{}, // наглядеться на воробьев
rus_verbs:хлопнуться{}, // хлопнуться на живот
rus_verbs:забредать{}, // забредать на поляну
rus_verbs:посягать{}, // посягать на исконные права собственности
rus_verbs:сдвигать{}, // сдвигать на одну позицию
rus_verbs:спрыгивать{}, // спрыгивать на землю
rus_verbs:сдвигаться{}, // сдвигаться на две позиции
rus_verbs:разделать{}, // разделать на орехи
rus_verbs:разлагать{}, // разлагать на элементарные элементы
rus_verbs:обрушивать{}, // обрушивать на головы врагов
rus_verbs:натечь{}, // натечь на пол
rus_verbs:политься{}, // вода польется на землю
rus_verbs:успеть{}, // Они успеют на поезд.
инфинитив:мигрировать{ вид:несоверш }, глагол:мигрировать{ вид:несоверш },
деепричастие:мигрируя{},
инфинитив:мигрировать{ вид:соверш }, глагол:мигрировать{ вид:соверш },
деепричастие:мигрировав{},
rus_verbs:двинуться{}, // Мы скоро двинемся на дачу.
rus_verbs:подойти{}, // Он не подойдёт на должность секретаря.
rus_verbs:потянуть{}, // Он не потянет на директора.
rus_verbs:тянуть{}, // Он не тянет на директора.
rus_verbs:перескакивать{}, // перескакивать с одного примера на другой
rus_verbs:жаловаться{}, // Он жалуется на нездоровье.
rus_verbs:издать{}, // издать на деньги спонсоров
rus_verbs:показаться{}, // показаться на глаза
rus_verbs:высаживать{}, // высаживать на необитаемый остров
rus_verbs:вознестись{}, // вознестись на самую вершину славы
rus_verbs:залить{}, // залить на youtube
rus_verbs:закачать{}, // закачать на youtube
rus_verbs:сыграть{}, // сыграть на деньги
rus_verbs:экстраполировать{}, // Формулу можно экстраполировать на случай нескольких переменных
инфинитив:экстраполироваться{ вид:несоверш}, // Ситуация легко экстраполируется на случай нескольких переменных
глагол:экстраполироваться{ вид:несоверш},
инфинитив:экстраполироваться{ вид:соверш},
глагол:экстраполироваться{ вид:соверш},
деепричастие:экстраполируясь{},
инфинитив:акцентировать{вид:соверш}, // оратор акцентировал внимание слушателей на новый аспект проблемы
глагол:акцентировать{вид:соверш},
инфинитив:акцентировать{вид:несоверш},
глагол:акцентировать{вид:несоверш},
прилагательное:акцентировавший{вид:несоверш},
//прилагательное:акцентировавший{вид:соверш},
прилагательное:акцентирующий{},
деепричастие:акцентировав{},
деепричастие:акцентируя{},
rus_verbs:бабахаться{}, // он бабахался на пол
rus_verbs:бабахнуться{}, // мальчил бабахнулся на асфальт
rus_verbs:батрачить{}, // Крестьяне батрачили на хозяина
rus_verbs:бахаться{}, // Наездники бахались на землю
rus_verbs:бахнуться{}, // Наездник опять бахнулся на землю
rus_verbs:благословить{}, // батюшка благословил отрока на подвиг
rus_verbs:благословлять{}, // батюшка благословляет отрока на подвиг
rus_verbs:блевануть{}, // Он блеванул на землю
rus_verbs:блевать{}, // Он блюет на землю
rus_verbs:бухнуться{}, // Наездник бухнулся на землю
rus_verbs:валить{}, // Ветер валил деревья на землю
rus_verbs:спилить{}, // Спиленное дерево валится на землю
rus_verbs:ввезти{}, // Предприятие ввезло товар на таможню
rus_verbs:вдохновить{}, // Фильм вдохновил мальчика на поход в лес
rus_verbs:вдохновиться{}, // Мальчик вдохновился на поход
rus_verbs:вдохновлять{}, // Фильм вдохновляет на поход в лес
rus_verbs:вестись{}, // Не ведись на эти уловки!
rus_verbs:вешать{}, // Гости вешают одежду на вешалку
rus_verbs:вешаться{}, // Одежда вешается на вешалки
rus_verbs:вещать{}, // радиостанция вещает на всю страну
rus_verbs:взбираться{}, // Туристы взбираются на заросший лесом холм
rus_verbs:взбредать{}, // Что иногда взбредает на ум
rus_verbs:взбрести{}, // Что-то взбрело на ум
rus_verbs:взвалить{}, // Мама взвалила на свои плечи всё домашнее хозяйство
rus_verbs:взваливаться{}, // Все домашнее хозяйство взваливается на мамины плечи
rus_verbs:взваливать{}, // Не надо взваливать всё на мои плечи
rus_verbs:взглянуть{}, // Кошка взглянула на мышку
rus_verbs:взгромождать{}, // Мальчик взгромождает стул на стол
rus_verbs:взгромождаться{}, // Мальчик взгромождается на стол
rus_verbs:взгромоздить{}, // Мальчик взгромоздил стул на стол
rus_verbs:взгромоздиться{}, // Мальчик взгромоздился на стул
rus_verbs:взирать{}, // Очевидцы взирали на непонятный объект
rus_verbs:взлетать{}, // Фабрика фейерверков взлетает на воздух
rus_verbs:взлететь{}, // Фабрика фейерверков взлетела на воздух
rus_verbs:взобраться{}, // Туристы взобрались на гору
rus_verbs:взойти{}, // Туристы взошли на гору
rus_verbs:взъесться{}, // Отец взъелся на непутевого сына
rus_verbs:взъяриться{}, // Отец взъярился на непутевого сына
rus_verbs:вкатить{}, // рабочие вкатили бочку на пандус
rus_verbs:вкатывать{}, // рабочик вкатывают бочку на пандус
rus_verbs:влиять{}, // Это решение влияет на всех игроков рынка
rus_verbs:водворить{}, // водворить нарушителя на место
rus_verbs:водвориться{}, // водвориться на свое место
rus_verbs:водворять{}, // водворять вещь на свое место
rus_verbs:водворяться{}, // водворяться на свое место
rus_verbs:водружать{}, // водружать флаг на флагшток
rus_verbs:водружаться{}, // Флаг водружается на флагшток
rus_verbs:водрузить{}, // водрузить флаг на флагшток
rus_verbs:водрузиться{}, // Флаг водрузился на вершину горы
rus_verbs:воздействовать{}, // Излучение воздействует на кожу
rus_verbs:воззреть{}, // воззреть на поле боя
rus_verbs:воззриться{}, // воззриться на поле боя
rus_verbs:возить{}, // возить туристов на гору
rus_verbs:возлагать{}, // Многочисленные посетители возлагают цветы на могилу
rus_verbs:возлагаться{}, // Ответственность возлагается на начальство
rus_verbs:возлечь{}, // возлечь на лежанку
rus_verbs:возложить{}, // возложить цветы на могилу поэта
rus_verbs:вознести{}, // вознести кого-то на вершину славы
rus_verbs:возноситься{}, // возносится на вершину успеха
rus_verbs:возносить{}, // возносить счастливчика на вершину успеха
rus_verbs:подниматься{}, // Мы поднимаемся на восьмой этаж
rus_verbs:подняться{}, // Мы поднялись на восьмой этаж
rus_verbs:вонять{}, // Кусок сыра воняет на всю округу
rus_verbs:воодушевлять{}, // Идеалы воодушевляют на подвиги
rus_verbs:воодушевляться{}, // Люди воодушевляются на подвиги
rus_verbs:ворчать{}, // Старый пес ворчит на прохожих
rus_verbs:воспринимать{}, // воспринимать сообщение на слух
rus_verbs:восприниматься{}, // сообщение плохо воспринимается на слух
rus_verbs:воспринять{}, // воспринять сообщение на слух
rus_verbs:восприняться{}, // восприняться на слух
rus_verbs:воссесть{}, // Коля воссел на трон
rus_verbs:вправить{}, // вправить мозг на место
rus_verbs:вправлять{}, // вправлять мозги на место
rus_verbs:временить{}, // временить с выходом на пенсию
rus_verbs:врубать{}, // врубать на полную мощность
rus_verbs:врубить{}, // врубить на полную мощность
rus_verbs:врубиться{}, // врубиться на полную мощность
rus_verbs:врываться{}, // врываться на собрание
rus_verbs:вскарабкаться{}, // вскарабкаться на утёс
rus_verbs:вскарабкиваться{}, // вскарабкиваться на утёс
rus_verbs:вскочить{}, // вскочить на ноги
rus_verbs:всплывать{}, // всплывать на поверхность воды
rus_verbs:всплыть{}, // всплыть на поверхность воды
rus_verbs:вспрыгивать{}, // вспрыгивать на платформу
rus_verbs:вспрыгнуть{}, // вспрыгнуть на платформу
rus_verbs:встать{}, // встать на защиту чести и достоинства
rus_verbs:вторгаться{}, // вторгаться на чужую территорию
rus_verbs:вторгнуться{}, // вторгнуться на чужую территорию
rus_verbs:въезжать{}, // въезжать на пандус
rus_verbs:наябедничать{}, // наябедничать на соседа по парте
rus_verbs:выблевать{}, // выблевать завтрак на пол
rus_verbs:выблеваться{}, // выблеваться на пол
rus_verbs:выблевывать{}, // выблевывать завтрак на пол
rus_verbs:выблевываться{}, // выблевываться на пол
rus_verbs:вывезти{}, // вывезти мусор на свалку
rus_verbs:вывесить{}, // вывесить белье на просушку
rus_verbs:вывести{}, // вывести собаку на прогулку
rus_verbs:вывешивать{}, // вывешивать белье на веревку
rus_verbs:вывозить{}, // вывозить детей на природу
rus_verbs:вызывать{}, // Начальник вызывает на ковер
rus_verbs:выйти{}, // выйти на свободу
rus_verbs:выкладывать{}, // выкладывать на всеобщее обозрение
rus_verbs:выкладываться{}, // выкладываться на всеобщее обозрение
rus_verbs:выливать{}, // выливать на землю
rus_verbs:выливаться{}, // выливаться на землю
rus_verbs:вылить{}, // вылить жидкость на землю
rus_verbs:вылиться{}, // Топливо вылилось на землю
rus_verbs:выложить{}, // выложить на берег
rus_verbs:выменивать{}, // выменивать золото на хлеб
rus_verbs:вымениваться{}, // Золото выменивается на хлеб
rus_verbs:выменять{}, // выменять золото на хлеб
rus_verbs:выпадать{}, // снег выпадает на землю
rus_verbs:выплевывать{}, // выплевывать на землю
rus_verbs:выплевываться{}, // выплевываться на землю
rus_verbs:выплескать{}, // выплескать на землю
rus_verbs:выплескаться{}, // выплескаться на землю
rus_verbs:выплескивать{}, // выплескивать на землю
rus_verbs:выплескиваться{}, // выплескиваться на землю
rus_verbs:выплывать{}, // выплывать на поверхность
rus_verbs:выплыть{}, // выплыть на поверхность
rus_verbs:выплюнуть{}, // выплюнуть на пол
rus_verbs:выползать{}, // выползать на свежий воздух
rus_verbs:выпроситься{}, // выпроситься на улицу
rus_verbs:выпрыгивать{}, // выпрыгивать на свободу
rus_verbs:выпрыгнуть{}, // выпрыгнуть на перрон
rus_verbs:выпускать{}, // выпускать на свободу
rus_verbs:выпустить{}, // выпустить на свободу
rus_verbs:выпучивать{}, // выпучивать на кого-то глаза
rus_verbs:выпучиваться{}, // глаза выпучиваются на кого-то
rus_verbs:выпучить{}, // выпучить глаза на кого-то
rus_verbs:выпучиться{}, // выпучиться на кого-то
rus_verbs:выронить{}, // выронить на землю
rus_verbs:высадить{}, // высадить на берег
rus_verbs:высадиться{}, // высадиться на берег
rus_verbs:высаживаться{}, // высаживаться на остров
rus_verbs:выскальзывать{}, // выскальзывать на землю
rus_verbs:выскочить{}, // выскочить на сцену
rus_verbs:высморкаться{}, // высморкаться на землю
rus_verbs:высморкнуться{}, // высморкнуться на землю
rus_verbs:выставить{}, // выставить на всеобщее обозрение
rus_verbs:выставиться{}, // выставиться на всеобщее обозрение
rus_verbs:выставлять{}, // выставлять на всеобщее обозрение
rus_verbs:выставляться{}, // выставляться на всеобщее обозрение
инфинитив:высыпать{вид:соверш}, // высыпать на землю
инфинитив:высыпать{вид:несоверш},
глагол:высыпать{вид:соверш},
глагол:высыпать{вид:несоверш},
деепричастие:высыпав{},
деепричастие:высыпая{},
прилагательное:высыпавший{вид:соверш},
//++прилагательное:высыпавший{вид:несоверш},
прилагательное:высыпающий{вид:несоверш},
rus_verbs:высыпаться{}, // высыпаться на землю
rus_verbs:вытаращивать{}, // вытаращивать глаза на медведя
rus_verbs:вытаращиваться{}, // вытаращиваться на медведя
rus_verbs:вытаращить{}, // вытаращить глаза на медведя
rus_verbs:вытаращиться{}, // вытаращиться на медведя
rus_verbs:вытекать{}, // вытекать на землю
rus_verbs:вытечь{}, // вытечь на землю
rus_verbs:выучиваться{}, // выучиваться на кого-то
rus_verbs:выучиться{}, // выучиться на кого-то
rus_verbs:посмотреть{}, // посмотреть на экран
rus_verbs:нашить{}, // нашить что-то на одежду
rus_verbs:придти{}, // придти на помощь кому-то
инфинитив:прийти{}, // прийти на помощь кому-то
глагол:прийти{},
деепричастие:придя{}, // Придя на вокзал, он поспешно взял билеты.
rus_verbs:поднять{}, // поднять на вершину
rus_verbs:согласиться{}, // согласиться на ничью
rus_verbs:послать{}, // послать на фронт
rus_verbs:слать{}, // слать на фронт
rus_verbs:надеяться{}, // надеяться на лучшее
rus_verbs:крикнуть{}, // крикнуть на шалунов
rus_verbs:пройти{}, // пройти на пляж
rus_verbs:прислать{}, // прислать на экспертизу
rus_verbs:жить{}, // жить на подачки
rus_verbs:становиться{}, // становиться на ноги
rus_verbs:наслать{}, // наслать на кого-то
rus_verbs:принять{}, // принять на заметку
rus_verbs:собираться{}, // собираться на экзамен
rus_verbs:оставить{}, // оставить на всякий случай
rus_verbs:звать{}, // звать на помощь
rus_verbs:направиться{}, // направиться на прогулку
rus_verbs:отвечать{}, // отвечать на звонки
rus_verbs:отправиться{}, // отправиться на прогулку
rus_verbs:поставить{}, // поставить на пол
rus_verbs:обернуться{}, // обернуться на зов
rus_verbs:отозваться{}, // отозваться на просьбу
rus_verbs:закричать{}, // закричать на собаку
rus_verbs:опустить{}, // опустить на землю
rus_verbs:принести{}, // принести на пляж свой жезлонг
rus_verbs:указать{}, // указать на дверь
rus_verbs:ходить{}, // ходить на занятия
rus_verbs:уставиться{}, // уставиться на листок
rus_verbs:приходить{}, // приходить на экзамен
rus_verbs:махнуть{}, // махнуть на пляж
rus_verbs:явиться{}, // явиться на допрос
rus_verbs:оглянуться{}, // оглянуться на дорогу
rus_verbs:уехать{}, // уехать на заработки
rus_verbs:повести{}, // повести на штурм
rus_verbs:опуститься{}, // опуститься на колени
//rus_verbs:передать{}, // передать на проверку
rus_verbs:побежать{}, // побежать на занятия
rus_verbs:прибыть{}, // прибыть на место службы
rus_verbs:кричать{}, // кричать на медведя
rus_verbs:стечь{}, // стечь на землю
rus_verbs:обратить{}, // обратить на себя внимание
rus_verbs:подать{}, // подать на пропитание
rus_verbs:привести{}, // привести на съемки
rus_verbs:испытывать{}, // испытывать на животных
rus_verbs:перевести{}, // перевести на жену
rus_verbs:купить{}, // купить на заемные деньги
rus_verbs:собраться{}, // собраться на встречу
rus_verbs:заглянуть{}, // заглянуть на огонёк
rus_verbs:нажать{}, // нажать на рычаг
rus_verbs:поспешить{}, // поспешить на праздник
rus_verbs:перейти{}, // перейти на русский язык
rus_verbs:поверить{}, // поверить на честное слово
rus_verbs:глянуть{}, // глянуть на обложку
rus_verbs:зайти{}, // зайти на огонёк
rus_verbs:проходить{}, // проходить на сцену
rus_verbs:глядеть{}, // глядеть на актрису
//rus_verbs:решиться{}, // решиться на прыжок
rus_verbs:пригласить{}, // пригласить на танец
rus_verbs:позвать{}, // позвать на экзамен
rus_verbs:усесться{}, // усесться на стул
rus_verbs:поступить{}, // поступить на математический факультет
rus_verbs:лечь{}, // лечь на живот
rus_verbs:потянуться{}, // потянуться на юг
rus_verbs:присесть{}, // присесть на корточки
rus_verbs:наступить{}, // наступить на змею
rus_verbs:заорать{}, // заорать на попрошаек
rus_verbs:надеть{}, // надеть на голову
rus_verbs:поглядеть{}, // поглядеть на девчонок
rus_verbs:принимать{}, // принимать на гарантийное обслуживание
rus_verbs:привезти{}, // привезти на испытания
rus_verbs:рухнуть{}, // рухнуть на асфальт
rus_verbs:пускать{}, // пускать на корм
rus_verbs:отвести{}, // отвести на приём
rus_verbs:отправить{}, // отправить на утилизацию
rus_verbs:двигаться{}, // двигаться на восток
rus_verbs:нести{}, // нести на пляж
rus_verbs:падать{}, // падать на руки
rus_verbs:откинуться{}, // откинуться на спинку кресла
rus_verbs:рявкнуть{}, // рявкнуть на детей
rus_verbs:получать{}, // получать на проживание
rus_verbs:полезть{}, // полезть на рожон
rus_verbs:направить{}, // направить на дообследование
rus_verbs:приводить{}, // приводить на проверку
rus_verbs:потребоваться{}, // потребоваться на замену
rus_verbs:кинуться{}, // кинуться на нападавшего
rus_verbs:учиться{}, // учиться на токаря
rus_verbs:приподнять{}, // приподнять на один метр
rus_verbs:налить{}, // налить на стол
rus_verbs:играть{}, // играть на деньги
rus_verbs:рассчитывать{}, // рассчитывать на подмогу
rus_verbs:шепнуть{}, // шепнуть на ухо
rus_verbs:швырнуть{}, // швырнуть на землю
rus_verbs:прыгнуть{}, // прыгнуть на оленя
rus_verbs:предлагать{}, // предлагать на выбор
rus_verbs:садиться{}, // садиться на стул
rus_verbs:лить{}, // лить на землю
rus_verbs:испытать{}, // испытать на животных
rus_verbs:фыркнуть{}, // фыркнуть на детеныша
rus_verbs:годиться{}, // мясо годится на фарш
rus_verbs:проверить{}, // проверить высказывание на истинность
rus_verbs:откликнуться{}, // откликнуться на призывы
rus_verbs:полагаться{}, // полагаться на интуицию
rus_verbs:покоситься{}, // покоситься на соседа
rus_verbs:повесить{}, // повесить на гвоздь
инфинитив:походить{вид:соверш}, // походить на занятия
глагол:походить{вид:соверш},
деепричастие:походив{},
прилагательное:походивший{},
rus_verbs:помчаться{}, // помчаться на экзамен
rus_verbs:ставить{}, // ставить на контроль
rus_verbs:свалиться{}, // свалиться на землю
rus_verbs:валиться{}, // валиться на землю
rus_verbs:подарить{}, // подарить на день рожденья
rus_verbs:сбежать{}, // сбежать на необитаемый остров
rus_verbs:стрелять{}, // стрелять на поражение
rus_verbs:обращать{}, // обращать на себя внимание
rus_verbs:наступать{}, // наступать на те же грабли
rus_verbs:сбросить{}, // сбросить на землю
rus_verbs:обидеться{}, // обидеться на друга
rus_verbs:устроиться{}, // устроиться на стажировку
rus_verbs:погрузиться{}, // погрузиться на большую глубину
rus_verbs:течь{}, // течь на землю
rus_verbs:отбросить{}, // отбросить на землю
rus_verbs:метать{}, // метать на дно
rus_verbs:пустить{}, // пустить на переплавку
rus_verbs:прожить{}, // прожить на пособие
rus_verbs:полететь{}, // полететь на континент
rus_verbs:пропустить{}, // пропустить на сцену
rus_verbs:указывать{}, // указывать на ошибку
rus_verbs:наткнуться{}, // наткнуться на клад
rus_verbs:рвануть{}, // рвануть на юг
rus_verbs:ступать{}, // ступать на землю
rus_verbs:спрыгнуть{}, // спрыгнуть на берег
rus_verbs:заходить{}, // заходить на огонёк
rus_verbs:нырнуть{}, // нырнуть на глубину
rus_verbs:рвануться{}, // рвануться на свободу
rus_verbs:натянуть{}, // натянуть на голову
rus_verbs:забраться{}, // забраться на стол
rus_verbs:помахать{}, // помахать на прощание
rus_verbs:содержать{}, // содержать на спонсорскую помощь
rus_verbs:приезжать{}, // приезжать на праздники
rus_verbs:проникнуть{}, // проникнуть на территорию
rus_verbs:подъехать{}, // подъехать на митинг
rus_verbs:устремиться{}, // устремиться на волю
rus_verbs:посадить{}, // посадить на стул
rus_verbs:ринуться{}, // ринуться на голкипера
rus_verbs:подвигнуть{}, // подвигнуть на подвиг
rus_verbs:отдавать{}, // отдавать на перевоспитание
rus_verbs:отложить{}, // отложить на черный день
rus_verbs:убежать{}, // убежать на танцы
rus_verbs:поднимать{}, // поднимать на верхний этаж
rus_verbs:переходить{}, // переходить на цифровой сигнал
rus_verbs:отослать{}, // отослать на переаттестацию
rus_verbs:отодвинуть{}, // отодвинуть на другую половину стола
rus_verbs:назначить{}, // назначить на должность
rus_verbs:осесть{}, // осесть на дно
rus_verbs:торопиться{}, // торопиться на экзамен
rus_verbs:менять{}, // менять на еду
rus_verbs:доставить{}, // доставить на шестой этаж
rus_verbs:заслать{}, // заслать на проверку
rus_verbs:дуть{}, // дуть на воду
rus_verbs:сослать{}, // сослать на каторгу
rus_verbs:останавливаться{}, // останавливаться на отдых
rus_verbs:сдаваться{}, // сдаваться на милость победителя
rus_verbs:сослаться{}, // сослаться на презумпцию невиновности
rus_verbs:рассердиться{}, // рассердиться на дочь
rus_verbs:кинуть{}, // кинуть на землю
rus_verbs:расположиться{}, // расположиться на ночлег
rus_verbs:осмелиться{}, // осмелиться на подлог
rus_verbs:шептать{}, // шептать на ушко
rus_verbs:уронить{}, // уронить на землю
rus_verbs:откинуть{}, // откинуть на спинку кресла
rus_verbs:перенести{}, // перенести на рабочий стол
rus_verbs:сдаться{}, // сдаться на милость победителя
rus_verbs:светить{}, // светить на дорогу
rus_verbs:мчаться{}, // мчаться на бал
rus_verbs:нестись{}, // нестись на свидание
rus_verbs:поглядывать{}, // поглядывать на экран
rus_verbs:орать{}, // орать на детей
rus_verbs:уложить{}, // уложить на лопатки
rus_verbs:решаться{}, // решаться на поступок
rus_verbs:попадать{}, // попадать на карандаш
rus_verbs:сплюнуть{}, // сплюнуть на землю
rus_verbs:снимать{}, // снимать на телефон
rus_verbs:опоздать{}, // опоздать на работу
rus_verbs:посылать{}, // посылать на проверку
rus_verbs:погнать{}, // погнать на пастбище
rus_verbs:поступать{}, // поступать на кибернетический факультет
rus_verbs:спускаться{}, // спускаться на уровень моря
rus_verbs:усадить{}, // усадить на диван
rus_verbs:проиграть{}, // проиграть на спор
rus_verbs:прилететь{}, // прилететь на фестиваль
rus_verbs:повалиться{}, // повалиться на спину
rus_verbs:огрызнуться{}, // Собака огрызнулась на хозяина
rus_verbs:задавать{}, // задавать на выходные
rus_verbs:запасть{}, // запасть на девочку
rus_verbs:лезть{}, // лезть на забор
rus_verbs:потащить{}, // потащить на выборы
rus_verbs:направляться{}, // направляться на экзамен
rus_verbs:определять{}, // определять на вкус
rus_verbs:поползти{}, // поползти на стену
rus_verbs:поплыть{}, // поплыть на берег
rus_verbs:залезть{}, // залезть на яблоню
rus_verbs:сдать{}, // сдать на мясокомбинат
rus_verbs:приземлиться{}, // приземлиться на дорогу
rus_verbs:лаять{}, // лаять на прохожих
rus_verbs:перевернуть{}, // перевернуть на бок
rus_verbs:ловить{}, // ловить на живца
rus_verbs:отнести{}, // отнести животное на хирургический стол
rus_verbs:плюнуть{}, // плюнуть на условности
rus_verbs:передавать{}, // передавать на проверку
rus_verbs:нанять{}, // Босс нанял на работу еще несколько человек
rus_verbs:разозлиться{}, // Папа разозлился на сына из-за плохих оценок по математике
инфинитив:рассыпаться{вид:несоверш}, // рассыпаться на мелкие детали
инфинитив:рассыпаться{вид:соверш},
глагол:рассыпаться{вид:несоверш},
глагол:рассыпаться{вид:соверш},
деепричастие:рассыпавшись{},
деепричастие:рассыпаясь{},
прилагательное:рассыпавшийся{вид:несоверш},
прилагательное:рассыпавшийся{вид:соверш},
прилагательное:рассыпающийся{},
rus_verbs:зарычать{}, // Медведица зарычала на медвежонка
rus_verbs:призвать{}, // призвать на сборы
rus_verbs:увезти{}, // увезти на дачу
rus_verbs:содержаться{}, // содержаться на пожертвования
rus_verbs:навести{}, // навести на скопление телескоп
rus_verbs:отправляться{}, // отправляться на утилизацию
rus_verbs:улечься{}, // улечься на животик
rus_verbs:налететь{}, // налететь на препятствие
rus_verbs:перевернуться{}, // перевернуться на спину
rus_verbs:улететь{}, // улететь на родину
rus_verbs:ложиться{}, // ложиться на бок
rus_verbs:класть{}, // класть на место
rus_verbs:отреагировать{}, // отреагировать на выступление
rus_verbs:доставлять{}, // доставлять на дом
rus_verbs:отнять{}, // отнять на благо правящей верхушки
rus_verbs:ступить{}, // ступить на землю
rus_verbs:сводить{}, // сводить на концерт знаменитой рок-группы
rus_verbs:унести{}, // унести на работу
rus_verbs:сходить{}, // сходить на концерт
rus_verbs:потратить{}, // потратить на корм и наполнитель для туалета все деньги
rus_verbs:соскочить{}, // соскочить на землю
rus_verbs:пожаловаться{}, // пожаловаться на соседей
rus_verbs:тащить{}, // тащить на замену
rus_verbs:замахать{}, // замахать руками на паренька
rus_verbs:заглядывать{}, // заглядывать на обед
rus_verbs:соглашаться{}, // соглашаться на равный обмен
rus_verbs:плюхнуться{}, // плюхнуться на мягкий пуфик
rus_verbs:увести{}, // увести на осмотр
rus_verbs:успевать{}, // успевать на контрольную работу
rus_verbs:опрокинуть{}, // опрокинуть на себя
rus_verbs:подавать{}, // подавать на апелляцию
rus_verbs:прибежать{}, // прибежать на вокзал
rus_verbs:отшвырнуть{}, // отшвырнуть на замлю
rus_verbs:привлекать{}, // привлекать на свою сторону
rus_verbs:опереться{}, // опереться на палку
rus_verbs:перебраться{}, // перебраться на маленький островок
rus_verbs:уговорить{}, // уговорить на новые траты
rus_verbs:гулять{}, // гулять на спонсорские деньги
rus_verbs:переводить{}, // переводить на другой путь
rus_verbs:заколебаться{}, // заколебаться на один миг
rus_verbs:зашептать{}, // зашептать на ушко
rus_verbs:привстать{}, // привстать на цыпочки
rus_verbs:хлынуть{}, // хлынуть на берег
rus_verbs:наброситься{}, // наброситься на еду
rus_verbs:напасть{}, // повстанцы, напавшие на конвой
rus_verbs:убрать{}, // книга, убранная на полку
rus_verbs:попасть{}, // путешественники, попавшие на ничейную территорию
rus_verbs:засматриваться{}, // засматриваться на девчонок
rus_verbs:застегнуться{}, // застегнуться на все пуговицы
rus_verbs:провериться{}, // провериться на заболевания
rus_verbs:проверяться{}, // проверяться на заболевания
rus_verbs:тестировать{}, // тестировать на профпригодность
rus_verbs:протестировать{}, // протестировать на профпригодность
rus_verbs:уходить{}, // отец, уходящий на работу
rus_verbs:налипнуть{}, // снег, налипший на провода
rus_verbs:налипать{}, // снег, налипающий на провода
rus_verbs:улетать{}, // Многие птицы улетают осенью на юг.
rus_verbs:поехать{}, // она поехала на встречу с заказчиком
rus_verbs:переключать{}, // переключать на резервную линию
rus_verbs:переключаться{}, // переключаться на резервную линию
rus_verbs:подписаться{}, // подписаться на обновление
rus_verbs:нанести{}, // нанести на кожу
rus_verbs:нарываться{}, // нарываться на неприятности
rus_verbs:выводить{}, // выводить на орбиту
rus_verbs:вернуться{}, // вернуться на родину
rus_verbs:возвращаться{}, // возвращаться на родину
прилагательное:падкий{}, // Он падок на деньги.
прилагательное:обиженный{}, // Он обижен на отца.
rus_verbs:косить{}, // Он косит на оба глаза.
rus_verbs:закрыть{}, // Он забыл закрыть дверь на замок.
прилагательное:готовый{}, // Он готов на всякие жертвы.
rus_verbs:говорить{}, // Он говорит на скользкую тему.
прилагательное:глухой{}, // Он глух на одно ухо.
rus_verbs:взять{}, // Он взял ребёнка себе на колени.
rus_verbs:оказывать{}, // Лекарство не оказывало на него никакого действия.
rus_verbs:вести{}, // Лестница ведёт на третий этаж.
rus_verbs:уполномочивать{}, // уполномочивать на что-либо
глагол:спешить{ вид:несоверш }, // Я спешу на поезд.
rus_verbs:брать{}, // Я беру всю ответственность на себя.
rus_verbs:произвести{}, // Это произвело на меня глубокое впечатление.
rus_verbs:употребить{}, // Эти деньги можно употребить на ремонт фабрики.
rus_verbs:наводить{}, // Эта песня наводит на меня сон и скуку.
rus_verbs:разбираться{}, // Эта машина разбирается на части.
rus_verbs:оказать{}, // Эта книга оказала на меня большое влияние.
rus_verbs:разбить{}, // Учитель разбил учеников на несколько групп.
rus_verbs:отразиться{}, // Усиленная работа отразилась на его здоровье.
rus_verbs:перегрузить{}, // Уголь надо перегрузить на другое судно.
rus_verbs:делиться{}, // Тридцать делится на пять без остатка.
rus_verbs:удаляться{}, // Суд удаляется на совещание.
rus_verbs:показывать{}, // Стрелка компаса всегда показывает на север.
rus_verbs:сохранить{}, // Сохраните это на память обо мне.
rus_verbs:уезжать{}, // Сейчас все студенты уезжают на экскурсию.
rus_verbs:лететь{}, // Самолёт летит на север.
rus_verbs:бить{}, // Ружьё бьёт на пятьсот метров.
// rus_verbs:прийтись{}, // Пятое число пришлось на субботу.
rus_verbs:вынести{}, // Они вынесли из лодки на берег все вещи.
rus_verbs:смотреть{}, // Она смотрит на нас из окна.
rus_verbs:отдать{}, // Она отдала мне деньги на сохранение.
rus_verbs:налюбоваться{}, // Не могу налюбоваться на картину.
rus_verbs:любоваться{}, // гости любовались на картину
rus_verbs:попробовать{}, // Дайте мне попробовать на ощупь.
прилагательное:действительный{}, // Прививка оспы действительна только на три года.
rus_verbs:спуститься{}, // На город спустился смог
прилагательное:нечистый{}, // Он нечист на руку.
прилагательное:неспособный{}, // Он неспособен на такую низость.
прилагательное:злой{}, // кот очень зол на хозяина
rus_verbs:пойти{}, // Девочка не пошла на урок физультуры
rus_verbs:прибывать{}, // мой поезд прибывает на первый путь
rus_verbs:застегиваться{}, // пальто застегивается на двадцать одну пуговицу
rus_verbs:идти{}, // Дело идёт на лад.
rus_verbs:лазить{}, // Он лазил на чердак.
rus_verbs:поддаваться{}, // Он легко поддаётся на уговоры.
// rus_verbs:действовать{}, // действующий на нервы
rus_verbs:выходить{}, // Балкон выходит на площадь.
rus_verbs:работать{}, // Время работает на нас.
глагол:написать{aux stress="напис^ать"}, // Он написал музыку на слова Пушкина.
rus_verbs:бросить{}, // Они бросили все силы на строительство.
// глагол:разрезать{aux stress="разр^езать"}, глагол:разрезать{aux stress="разрез^ать"}, // Она разрезала пирог на шесть кусков.
rus_verbs:броситься{}, // Она радостно бросилась мне на шею.
rus_verbs:оправдать{}, // Она оправдала неявку на занятия болезнью.
rus_verbs:ответить{}, // Она не ответила на мой поклон.
rus_verbs:нашивать{}, // Она нашивала заплату на локоть.
rus_verbs:молиться{}, // Она молится на свою мать.
rus_verbs:запереть{}, // Она заперла дверь на замок.
rus_verbs:заявить{}, // Она заявила свои права на наследство.
rus_verbs:уйти{}, // Все деньги ушли на путешествие.
rus_verbs:вступить{}, // Водолаз вступил на берег.
rus_verbs:сойти{}, // Ночь сошла на землю.
rus_verbs:приехать{}, // Мы приехали на вокзал слишком рано.
rus_verbs:рыдать{}, // Не рыдай так безумно над ним.
rus_verbs:подписать{}, // Не забудьте подписать меня на газету.
rus_verbs:держать{}, // Наш пароход держал курс прямо на север.
rus_verbs:свезти{}, // На выставку свезли экспонаты со всего мира.
rus_verbs:ехать{}, // Мы сейчас едем на завод.
rus_verbs:выбросить{}, // Волнами лодку выбросило на берег.
ГЛ_ИНФ(сесть), // сесть на снег
ГЛ_ИНФ(записаться),
ГЛ_ИНФ(положить) // положи книгу на стол
}
#endregion VerbList
// Чтобы разрешить связывание в паттернах типа: залить на youtube
fact гл_предл
{
if context { Гл_НА_Вин предлог:на{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { глагол:купить{} предлог:на{} 'деньги'{падеж:вин} }
then return true
}
fact гл_предл
{
if context { Гл_НА_Вин предлог:на{} *:*{ падеж:вин } }
then return true
}
// смещаться на несколько миллиметров
fact гл_предл
{
if context { Гл_НА_Вин предлог:на{} наречие:*{} }
then return true
}
// партия взяла на себя нереалистичные обязательства
fact гл_предл
{
if context { глагол:взять{} предлог:на{} 'себя'{падеж:вин} }
then return true
}
#endregion ВИНИТЕЛЬНЫЙ
// Все остальные варианты с предлогом 'НА' по умолчанию запрещаем.
fact гл_предл
{
if context { * предлог:на{} *:*{ падеж:предл } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:на{} *:*{ падеж:мест } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:на{} *:*{ падеж:вин } }
then return false,-4
}
// Этот вариант нужен для обработки конструкций с числительными:
// Президентские выборы разделили Венесуэлу на два непримиримых лагеря
fact гл_предл
{
if context { * предлог:на{} *:*{ падеж:род } }
then return false,-4
}
// Продавать на eBay
fact гл_предл
{
if context { * предлог:на{} * }
then return false,-6
}
#endregion Предлог_НА
#region Предлог_С
// ------------- ПРЕДЛОГ 'С' -----------------
// У этого предлога предпочтительная семантика привязывает его обычно к существительному.
// Поэтому запрещаем по умолчанию его привязку к глаголам, а разрешенные глаголы перечислим.
#region ТВОРИТЕЛЬНЫЙ
wordentry_set Гл_С_Твор={
rus_verbs:помогать{}, // будет готов помогать врачам в онкологическом центре с постановкой верных диагнозов
rus_verbs:перепихнуться{}, // неужели ты не хочешь со мной перепихнуться
rus_verbs:забраться{},
rus_verbs:ДРАТЬСЯ{}, // Мои же собственные ратники забросали бы меня гнилой капустой, и мне пришлось бы драться с каждым рыцарем в стране, чтобы доказать свою смелость. (ДРАТЬСЯ/БИТЬСЯ/ПОДРАТЬСЯ)
rus_verbs:БИТЬСЯ{}, //
rus_verbs:ПОДРАТЬСЯ{}, //
прилагательное:СХОЖИЙ{}, // Не был ли он схожим с одним из живых языков Земли (СХОЖИЙ)
rus_verbs:ВСТУПИТЬ{}, // Он намеревался вступить с Вольфом в ближний бой. (ВСТУПИТЬ)
rus_verbs:КОРРЕЛИРОВАТЬ{}, // Это коррелирует с традиционно сильными направлениями московской математической школы. (КОРРЕЛИРОВАТЬ)
rus_verbs:УВИДЕТЬСЯ{}, // Он проигнорирует истерические протесты жены и увидится сначала с доктором, а затем с психотерапевтом (УВИДЕТЬСЯ)
rus_verbs:ОЧНУТЬСЯ{}, // Когда он очнулся с болью в левой стороне черепа, у него возникло пугающее ощущение. (ОЧНУТЬСЯ)
прилагательное:сходный{}, // Мозг этих существ сходен по размерам с мозгом динозавра
rus_verbs:накрыться{}, // Было холодно, и он накрылся с головой одеялом.
rus_verbs:РАСПРЕДЕЛИТЬ{}, // Бюджет распределят с участием горожан (РАСПРЕДЕЛИТЬ)
rus_verbs:НАБРОСИТЬСЯ{}, // Пьяный водитель набросился с ножом на сотрудников ГИБДД (НАБРОСИТЬСЯ)
rus_verbs:БРОСИТЬСЯ{}, // она со смехом бросилась прочь (БРОСИТЬСЯ)
rus_verbs:КОНТАКТИРОВАТЬ{}, // Электронным магазинам стоит контактировать с клиентами (КОНТАКТИРОВАТЬ)
rus_verbs:ВИДЕТЬСЯ{}, // Тогда мы редко виделись друг с другом
rus_verbs:сесть{}, // сел в него с дорожной сумкой , наполненной наркотиками
rus_verbs:купить{}, // Мы купили с ним одну и ту же книгу
rus_verbs:ПРИМЕНЯТЬ{}, // Меры по стимулированию спроса в РФ следует применять с осторожностью (ПРИМЕНЯТЬ)
rus_verbs:УЙТИ{}, // ты мог бы уйти со мной (УЙТИ)
rus_verbs:ЖДАТЬ{}, // С нарастающим любопытством ждем результатов аудита золотых хранилищ европейских и американских центробанков (ЖДАТЬ)
rus_verbs:ГОСПИТАЛИЗИРОВАТЬ{}, // Мэра Твери, участвовавшего в спартакиаде, госпитализировали с инфарктом (ГОСПИТАЛИЗИРОВАТЬ)
rus_verbs:ЗАХЛОПНУТЬСЯ{}, // она захлопнулась со звоном (ЗАХЛОПНУТЬСЯ)
rus_verbs:ОТВЕРНУТЬСЯ{}, // она со вздохом отвернулась (ОТВЕРНУТЬСЯ)
rus_verbs:отправить{}, // вы можете отправить со мной человека
rus_verbs:выступать{}, // Градоначальник , выступая с обзором основных городских событий , поведал об этом депутатам
rus_verbs:ВЫЕЗЖАТЬ{}, // заключенные сами шьют куклы и иногда выезжают с представлениями в детский дом неподалеку (ВЫЕЗЖАТЬ С твор)
rus_verbs:ПОКОНЧИТЬ{}, // со всем этим покончено (ПОКОНЧИТЬ С)
rus_verbs:ПОБЕЖАТЬ{}, // Дмитрий побежал со всеми (ПОБЕЖАТЬ С)
прилагательное:несовместимый{}, // характер ранений был несовместим с жизнью (НЕСОВМЕСТИМЫЙ С)
rus_verbs:ПОСЕТИТЬ{}, // Его кабинет местные тележурналисты посетили со скрытой камерой (ПОСЕТИТЬ С)
rus_verbs:СЛОЖИТЬСЯ{}, // сами банки принимают меры по урегулированию сложившейся с вкладчиками ситуации (СЛОЖИТЬСЯ С)
rus_verbs:ЗАСТАТЬ{}, // Молодой человек убил пенсионера , застав его в постели с женой (ЗАСТАТЬ С)
rus_verbs:ОЗНАКАМЛИВАТЬСЯ{}, // при заполнении заявления владельцы судов ознакамливаются с режимом (ОЗНАКАМЛИВАТЬСЯ С)
rus_verbs:СООБРАЗОВЫВАТЬ{}, // И все свои задачи мы сообразовываем с этим пониманием (СООБРАЗОВЫВАТЬ С)
rus_verbs:СВЫКАТЬСЯ{},
rus_verbs:стаскиваться{},
rus_verbs:спиливаться{},
rus_verbs:КОНКУРИРОВАТЬ{}, // Бедные и менее развитые страны не могут конкурировать с этими субсидиями (КОНКУРИРОВАТЬ С)
rus_verbs:ВЫРВАТЬСЯ{}, // тот с трудом вырвался (ВЫРВАТЬСЯ С твор)
rus_verbs:СОБРАТЬСЯ{}, // нужно собраться с силами (СОБРАТЬСЯ С)
rus_verbs:УДАВАТЬСЯ{}, // удавалось это с трудом (УДАВАТЬСЯ С)
rus_verbs:РАСПАХНУТЬСЯ{}, // дверь с треском распахнулась (РАСПАХНУТЬСЯ С)
rus_verbs:НАБЛЮДАТЬ{}, // Олег наблюдал с любопытством (НАБЛЮДАТЬ С)
rus_verbs:ПОТЯНУТЬ{}, // затем с силой потянул (ПОТЯНУТЬ С)
rus_verbs:КИВНУТЬ{}, // Питер с трудом кивнул (КИВНУТЬ С)
rus_verbs:СГЛОТНУТЬ{}, // Борис с трудом сглотнул (СГЛОТНУТЬ С)
rus_verbs:ЗАБРАТЬ{}, // забрать его с собой (ЗАБРАТЬ С)
rus_verbs:ОТКРЫТЬСЯ{}, // дверь с шипением открылась (ОТКРЫТЬСЯ С)
rus_verbs:ОТОРВАТЬ{}, // с усилием оторвал взгляд (ОТОРВАТЬ С твор)
rus_verbs:ОГЛЯДЕТЬСЯ{}, // Рома с любопытством огляделся (ОГЛЯДЕТЬСЯ С)
rus_verbs:ФЫРКНУТЬ{}, // турок фыркнул с отвращением (ФЫРКНУТЬ С)
rus_verbs:согласиться{}, // с этим согласились все (согласиться с)
rus_verbs:ПОСЫПАТЬСЯ{}, // с грохотом посыпались камни (ПОСЫПАТЬСЯ С твор)
rus_verbs:ВЗДОХНУТЬ{}, // Алиса вздохнула с облегчением (ВЗДОХНУТЬ С)
rus_verbs:ОБЕРНУТЬСЯ{}, // та с удивлением обернулась (ОБЕРНУТЬСЯ С)
rus_verbs:ХМЫКНУТЬ{}, // Алексей хмыкнул с сомнением (ХМЫКНУТЬ С твор)
rus_verbs:ВЫЕХАТЬ{}, // они выехали с рассветом (ВЫЕХАТЬ С твор)
rus_verbs:ВЫДОХНУТЬ{}, // Владимир выдохнул с облегчением (ВЫДОХНУТЬ С)
rus_verbs:УХМЫЛЬНУТЬСЯ{}, // Кеша ухмыльнулся с сомнением (УХМЫЛЬНУТЬСЯ С)
rus_verbs:НЕСТИСЬ{}, // тот несся с криком (НЕСТИСЬ С твор)
rus_verbs:ПАДАТЬ{}, // падают с глухим стуком (ПАДАТЬ С твор)
rus_verbs:ТВОРИТЬСЯ{}, // странное творилось с глазами (ТВОРИТЬСЯ С твор)
rus_verbs:УХОДИТЬ{}, // с ними уходили эльфы (УХОДИТЬ С твор)
rus_verbs:СКАКАТЬ{}, // скакали тут с топорами (СКАКАТЬ С твор)
rus_verbs:ЕСТЬ{}, // здесь едят с зеленью (ЕСТЬ С твор)
rus_verbs:ПОЯВИТЬСЯ{}, // с рассветом появились птицы (ПОЯВИТЬСЯ С твор)
rus_verbs:ВСКОЧИТЬ{}, // Олег вскочил с готовностью (ВСКОЧИТЬ С твор)
rus_verbs:БЫТЬ{}, // хочу быть с тобой (БЫТЬ С твор)
rus_verbs:ПОКАЧАТЬ{}, // с сомнением покачал головой. (ПОКАЧАТЬ С СОМНЕНИЕМ)
rus_verbs:ВЫРУГАТЬСЯ{}, // капитан с чувством выругался (ВЫРУГАТЬСЯ С ЧУВСТВОМ)
rus_verbs:ОТКРЫТЬ{}, // с трудом открыл глаза (ОТКРЫТЬ С ТРУДОМ, таких много)
rus_verbs:ПОЛУЧИТЬСЯ{}, // забавно получилось с ним (ПОЛУЧИТЬСЯ С)
rus_verbs:ВЫБЕЖАТЬ{}, // старый выбежал с копьем (ВЫБЕЖАТЬ С)
rus_verbs:ГОТОВИТЬСЯ{}, // Большинство компотов готовится с использованием сахара (ГОТОВИТЬСЯ С)
rus_verbs:ПОДИСКУТИРОВАТЬ{}, // я бы подискутировал с Андрюхой (ПОДИСКУТИРОВАТЬ С)
rus_verbs:ТУСИТЬ{}, // кто тусил со Светкой (ТУСИТЬ С)
rus_verbs:БЕЖАТЬ{}, // куда она бежит со всеми? (БЕЖАТЬ С твор)
rus_verbs:ГОРЕТЬ{}, // ты горел со своим кораблем? (ГОРЕТЬ С)
rus_verbs:ВЫПИТЬ{}, // хотите выпить со мной чаю? (ВЫПИТЬ С)
rus_verbs:МЕНЯТЬСЯ{}, // Я меняюсь с товарищем книгами. (МЕНЯТЬСЯ С)
rus_verbs:ВАЛЯТЬСЯ{}, // Он уже неделю валяется с гриппом. (ВАЛЯТЬСЯ С)
rus_verbs:ПИТЬ{}, // вы даже будете пить со мной пиво. (ПИТЬ С)
инфинитив:кристаллизоваться{ вид:соверш }, // После этого пересыщенный раствор кристаллизуется с образованием кристаллов сахара.
инфинитив:кристаллизоваться{ вид:несоверш },
глагол:кристаллизоваться{ вид:соверш },
глагол:кристаллизоваться{ вид:несоверш },
rus_verbs:ПООБЩАТЬСЯ{}, // пообщайся с Борисом (ПООБЩАТЬСЯ С)
rus_verbs:ОБМЕНЯТЬСЯ{}, // Миша обменялся с Петей марками (ОБМЕНЯТЬСЯ С)
rus_verbs:ПРОХОДИТЬ{}, // мы с тобой сегодня весь день проходили с вещами. (ПРОХОДИТЬ С)
rus_verbs:ВСТАТЬ{}, // Он занимался всю ночь и встал с головной болью. (ВСТАТЬ С)
rus_verbs:ПОВРЕМЕНИТЬ{}, // МВФ рекомендует Ирландии повременить с мерами экономии (ПОВРЕМЕНИТЬ С)
rus_verbs:ГЛЯДЕТЬ{}, // Её глаза глядели с мягкой грустью. (ГЛЯДЕТЬ С + твор)
rus_verbs:ВЫСКОЧИТЬ{}, // Зачем ты выскочил со своим замечанием? (ВЫСКОЧИТЬ С)
rus_verbs:НЕСТИ{}, // плот несло со страшной силой. (НЕСТИ С)
rus_verbs:приближаться{}, // стена приближалась со страшной быстротой. (приближаться с)
rus_verbs:заниматься{}, // После уроков я занимался с отстающими учениками. (заниматься с)
rus_verbs:разработать{}, // Этот лекарственный препарат разработан с использованием рецептов традиционной китайской медицины. (разработать с)
rus_verbs:вестись{}, // Разработка месторождения ведется с использованием большого количества техники. (вестись с)
rus_verbs:конфликтовать{}, // Маша конфликтует с Петей (конфликтовать с)
rus_verbs:мешать{}, // мешать воду с мукой (мешать с)
rus_verbs:иметь{}, // мне уже приходилось несколько раз иметь с ним дело.
rus_verbs:синхронизировать{}, // синхронизировать с эталонным генератором
rus_verbs:засинхронизировать{}, // засинхронизировать с эталонным генератором
rus_verbs:синхронизироваться{}, // синхронизироваться с эталонным генератором
rus_verbs:засинхронизироваться{}, // засинхронизироваться с эталонным генератором
rus_verbs:стирать{}, // стирать с мылом рубашку в тазу
rus_verbs:прыгать{}, // парашютист прыгает с парашютом
rus_verbs:выступить{}, // Он выступил с приветствием съезду.
rus_verbs:ходить{}, // В чужой монастырь со своим уставом не ходят.
rus_verbs:отозваться{}, // Он отозвался об этой книге с большой похвалой.
rus_verbs:отзываться{}, // Он отзывается об этой книге с большой похвалой.
rus_verbs:вставать{}, // он встаёт с зарёй
rus_verbs:мирить{}, // Его ум мирил всех с его дурным характером.
rus_verbs:продолжаться{}, // стрельба тем временем продолжалась с прежней точностью.
rus_verbs:договориться{}, // мы договоримся с вами
rus_verbs:побыть{}, // он хотел побыть с тобой
rus_verbs:расти{}, // Мировые производственные мощности растут с беспрецедентной скоростью
rus_verbs:вязаться{}, // вязаться с фактами
rus_verbs:отнестись{}, // отнестись к животным с сочуствием
rus_verbs:относиться{}, // относиться с пониманием
rus_verbs:пойти{}, // Спектакль пойдёт с участием известных артистов.
rus_verbs:бракосочетаться{}, // Потомственный кузнец бракосочетался с разорившейся графиней
rus_verbs:гулять{}, // бабушка гуляет с внуком
rus_verbs:разбираться{}, // разбираться с задачей
rus_verbs:сверить{}, // Данные были сверены с эталонными значениями
rus_verbs:делать{}, // Что делать со старым телефоном
rus_verbs:осматривать{}, // осматривать с удивлением
rus_verbs:обсудить{}, // обсудить с приятелем прохождение уровня в новой игре
rus_verbs:попрощаться{}, // попрощаться с талантливым актером
rus_verbs:задремать{}, // задремать с кружкой чая в руке
rus_verbs:связать{}, // связать катастрофу с действиями конкурентов
rus_verbs:носиться{}, // носиться с безумной идеей
rus_verbs:кончать{}, // кончать с собой
rus_verbs:обмениваться{}, // обмениваться с собеседниками
rus_verbs:переговариваться{}, // переговариваться с маяком
rus_verbs:общаться{}, // общаться с полицией
rus_verbs:завершить{}, // завершить с ошибкой
rus_verbs:обняться{}, // обняться с подругой
rus_verbs:сливаться{}, // сливаться с фоном
rus_verbs:смешаться{}, // смешаться с толпой
rus_verbs:договариваться{}, // договариваться с потерпевшим
rus_verbs:обедать{}, // обедать с гостями
rus_verbs:сообщаться{}, // сообщаться с подземной рекой
rus_verbs:сталкиваться{}, // сталкиваться со стаей птиц
rus_verbs:читаться{}, // читаться с трудом
rus_verbs:смириться{}, // смириться с утратой
rus_verbs:разделить{}, // разделить с другими ответственность
rus_verbs:роднить{}, // роднить с медведем
rus_verbs:медлить{}, // медлить с ответом
rus_verbs:скрестить{}, // скрестить с ужом
rus_verbs:покоиться{}, // покоиться с миром
rus_verbs:делиться{}, // делиться с друзьями
rus_verbs:познакомить{}, // познакомить с Олей
rus_verbs:порвать{}, // порвать с Олей
rus_verbs:завязать{}, // завязать с Олей знакомство
rus_verbs:суетиться{}, // суетиться с изданием романа
rus_verbs:соединиться{}, // соединиться с сервером
rus_verbs:справляться{}, // справляться с нуждой
rus_verbs:замешкаться{}, // замешкаться с ответом
rus_verbs:поссориться{}, // поссориться с подругой
rus_verbs:ссориться{}, // ссориться с друзьями
rus_verbs:торопить{}, // торопить с решением
rus_verbs:поздравить{}, // поздравить с победой
rus_verbs:проститься{}, // проститься с человеком
rus_verbs:поработать{}, // поработать с деревом
rus_verbs:приключиться{}, // приключиться с Колей
rus_verbs:сговориться{}, // сговориться с Ваней
rus_verbs:отъехать{}, // отъехать с ревом
rus_verbs:объединять{}, // объединять с другой кампанией
rus_verbs:употребить{}, // употребить с молоком
rus_verbs:перепутать{}, // перепутать с другой книгой
rus_verbs:запоздать{}, // запоздать с ответом
rus_verbs:подружиться{}, // подружиться с другими детьми
rus_verbs:дружить{}, // дружить с Сережей
rus_verbs:поравняться{}, // поравняться с финишной чертой
rus_verbs:ужинать{}, // ужинать с гостями
rus_verbs:расставаться{}, // расставаться с приятелями
rus_verbs:завтракать{}, // завтракать с семьей
rus_verbs:объединиться{}, // объединиться с соседями
rus_verbs:сменяться{}, // сменяться с напарником
rus_verbs:соединить{}, // соединить с сетью
rus_verbs:разговориться{}, // разговориться с охранником
rus_verbs:преподнести{}, // преподнести с помпой
rus_verbs:напечатать{}, // напечатать с картинками
rus_verbs:соединять{}, // соединять с сетью
rus_verbs:расправиться{}, // расправиться с беззащитным человеком
rus_verbs:распрощаться{}, // распрощаться с деньгами
rus_verbs:сравнить{}, // сравнить с конкурентами
rus_verbs:ознакомиться{}, // ознакомиться с выступлением
инфинитив:сочетаться{ вид:несоверш }, глагол:сочетаться{ вид:несоверш }, // сочетаться с сумочкой
деепричастие:сочетаясь{}, прилагательное:сочетающийся{}, прилагательное:сочетавшийся{},
rus_verbs:изнасиловать{}, // изнасиловать с применением чрезвычайного насилия
rus_verbs:прощаться{}, // прощаться с боевым товарищем
rus_verbs:сравнивать{}, // сравнивать с конкурентами
rus_verbs:складывать{}, // складывать с весом упаковки
rus_verbs:повестись{}, // повестись с ворами
rus_verbs:столкнуть{}, // столкнуть с отбойником
rus_verbs:переглядываться{}, // переглядываться с соседом
rus_verbs:поторопить{}, // поторопить с откликом
rus_verbs:развлекаться{}, // развлекаться с подружками
rus_verbs:заговаривать{}, // заговаривать с незнакомцами
rus_verbs:поцеловаться{}, // поцеловаться с первой девушкой
инфинитив:согласоваться{ вид:несоверш }, глагол:согласоваться{ вид:несоверш }, // согласоваться с подлежащим
деепричастие:согласуясь{}, прилагательное:согласующийся{},
rus_verbs:совпасть{}, // совпасть с оригиналом
rus_verbs:соединяться{}, // соединяться с куратором
rus_verbs:повстречаться{}, // повстречаться с героями
rus_verbs:поужинать{}, // поужинать с родителями
rus_verbs:развестись{}, // развестись с первым мужем
rus_verbs:переговорить{}, // переговорить с коллегами
rus_verbs:сцепиться{}, // сцепиться с бродячей собакой
rus_verbs:сожрать{}, // сожрать с потрохами
rus_verbs:побеседовать{}, // побеседовать со шпаной
rus_verbs:поиграть{}, // поиграть с котятами
rus_verbs:сцепить{}, // сцепить с тягачом
rus_verbs:помириться{}, // помириться с подружкой
rus_verbs:связываться{}, // связываться с бандитами
rus_verbs:совещаться{}, // совещаться с мастерами
rus_verbs:обрушиваться{}, // обрушиваться с беспощадной критикой
rus_verbs:переплестись{}, // переплестись с кустами
rus_verbs:мутить{}, // мутить с одногрупницами
rus_verbs:приглядываться{}, // приглядываться с интересом
rus_verbs:сблизиться{}, // сблизиться с врагами
rus_verbs:перешептываться{}, // перешептываться с симпатичной соседкой
rus_verbs:растереть{}, // растереть с солью
rus_verbs:смешиваться{}, // смешиваться с известью
rus_verbs:соприкоснуться{}, // соприкоснуться с тайной
rus_verbs:ладить{}, // ладить с родственниками
rus_verbs:сотрудничать{}, // сотрудничать с органами дознания
rus_verbs:съехаться{}, // съехаться с родственниками
rus_verbs:перекинуться{}, // перекинуться с коллегами парой слов
rus_verbs:советоваться{}, // советоваться с отчимом
rus_verbs:сравниться{}, // сравниться с лучшими
rus_verbs:знакомиться{}, // знакомиться с абитуриентами
rus_verbs:нырять{}, // нырять с аквалангом
rus_verbs:забавляться{}, // забавляться с куклой
rus_verbs:перекликаться{}, // перекликаться с другой статьей
rus_verbs:тренироваться{}, // тренироваться с партнершей
rus_verbs:поспорить{}, // поспорить с казночеем
инфинитив:сладить{ вид:соверш }, глагол:сладить{ вид:соверш }, // сладить с бычком
деепричастие:сладив{}, прилагательное:сладивший{ вид:соверш },
rus_verbs:примириться{}, // примириться с утратой
rus_verbs:раскланяться{}, // раскланяться с фрейлинами
rus_verbs:слечь{}, // слечь с ангиной
rus_verbs:соприкасаться{}, // соприкасаться со стеной
rus_verbs:смешать{}, // смешать с грязью
rus_verbs:пересекаться{}, // пересекаться с трассой
rus_verbs:путать{}, // путать с государственной шерстью
rus_verbs:поболтать{}, // поболтать с ученицами
rus_verbs:здороваться{}, // здороваться с профессором
rus_verbs:просчитаться{}, // просчитаться с покупкой
rus_verbs:сторожить{}, // сторожить с собакой
rus_verbs:обыскивать{}, // обыскивать с собаками
rus_verbs:переплетаться{}, // переплетаться с другой веткой
rus_verbs:обниматься{}, // обниматься с Ксюшей
rus_verbs:объединяться{}, // объединяться с конкурентами
rus_verbs:погорячиться{}, // погорячиться с покупкой
rus_verbs:мыться{}, // мыться с мылом
rus_verbs:свериться{}, // свериться с эталоном
rus_verbs:разделаться{}, // разделаться с кем-то
rus_verbs:чередоваться{}, // чередоваться с партнером
rus_verbs:налететь{}, // налететь с соратниками
rus_verbs:поспать{}, // поспать с включенным светом
rus_verbs:управиться{}, // управиться с собакой
rus_verbs:согрешить{}, // согрешить с замужней
rus_verbs:определиться{}, // определиться с победителем
rus_verbs:перемешаться{}, // перемешаться с гранулами
rus_verbs:затрудняться{}, // затрудняться с ответом
rus_verbs:обождать{}, // обождать со стартом
rus_verbs:фыркать{}, // фыркать с презрением
rus_verbs:засидеться{}, // засидеться с приятелем
rus_verbs:крепнуть{}, // крепнуть с годами
rus_verbs:пировать{}, // пировать с дружиной
rus_verbs:щебетать{}, // щебетать с сестричками
rus_verbs:маяться{}, // маяться с кашлем
rus_verbs:сближать{}, // сближать с центральным светилом
rus_verbs:меркнуть{}, // меркнуть с возрастом
rus_verbs:заспорить{}, // заспорить с оппонентами
rus_verbs:граничить{}, // граничить с Ливаном
rus_verbs:перестараться{}, // перестараться со стимуляторами
rus_verbs:объединить{}, // объединить с филиалом
rus_verbs:свыкнуться{}, // свыкнуться с утратой
rus_verbs:посоветоваться{}, // посоветоваться с адвокатами
rus_verbs:напутать{}, // напутать с ведомостями
rus_verbs:нагрянуть{}, // нагрянуть с обыском
rus_verbs:посовещаться{}, // посовещаться с судьей
rus_verbs:провернуть{}, // провернуть с друганом
rus_verbs:разделяться{}, // разделяться с сотрапезниками
rus_verbs:пересечься{}, // пересечься с второй колонной
rus_verbs:опережать{}, // опережать с большим запасом
rus_verbs:перепутаться{}, // перепутаться с другой линией
rus_verbs:соотноситься{}, // соотноситься с затратами
rus_verbs:смешивать{}, // смешивать с золой
rus_verbs:свидеться{}, // свидеться с тобой
rus_verbs:переспать{}, // переспать с графиней
rus_verbs:поладить{}, // поладить с соседями
rus_verbs:протащить{}, // протащить с собой
rus_verbs:разминуться{}, // разминуться с встречным потоком
rus_verbs:перемежаться{}, // перемежаться с успехами
rus_verbs:рассчитаться{}, // рассчитаться с кредиторами
rus_verbs:срастись{}, // срастись с телом
rus_verbs:знакомить{}, // знакомить с родителями
rus_verbs:поругаться{}, // поругаться с родителями
rus_verbs:совладать{}, // совладать с чувствами
rus_verbs:обручить{}, // обручить с богатой невестой
rus_verbs:сближаться{}, // сближаться с вражеским эсминцем
rus_verbs:замутить{}, // замутить с Ксюшей
rus_verbs:повозиться{}, // повозиться с настройкой
rus_verbs:торговаться{}, // торговаться с продавцами
rus_verbs:уединиться{}, // уединиться с девчонкой
rus_verbs:переборщить{}, // переборщить с добавкой
rus_verbs:ознакомить{}, // ознакомить с пожеланиями
rus_verbs:прочесывать{}, // прочесывать с собаками
rus_verbs:переписываться{}, // переписываться с корреспондентами
rus_verbs:повздорить{}, // повздорить с сержантом
rus_verbs:разлучить{}, // разлучить с семьей
rus_verbs:соседствовать{}, // соседствовать с цыганами
rus_verbs:застукать{}, // застукать с проститутками
rus_verbs:напуститься{}, // напуститься с кулаками
rus_verbs:сдружиться{}, // сдружиться с ребятами
rus_verbs:соперничать{}, // соперничать с параллельным классом
rus_verbs:прочесать{}, // прочесать с собаками
rus_verbs:кокетничать{}, // кокетничать с гимназистками
rus_verbs:мириться{}, // мириться с убытками
rus_verbs:оплошать{}, // оплошать с билетами
rus_verbs:отождествлять{}, // отождествлять с литературным героем
rus_verbs:хитрить{}, // хитрить с зарплатой
rus_verbs:провозиться{}, // провозиться с задачкой
rus_verbs:коротать{}, // коротать с друзьями
rus_verbs:соревноваться{}, // соревноваться с машиной
rus_verbs:уживаться{}, // уживаться с местными жителями
rus_verbs:отождествляться{}, // отождествляться с литературным героем
rus_verbs:сопоставить{}, // сопоставить с эталоном
rus_verbs:пьянствовать{}, // пьянствовать с друзьями
rus_verbs:залетать{}, // залетать с паленой водкой
rus_verbs:гастролировать{}, // гастролировать с новой цирковой программой
rus_verbs:запаздывать{}, // запаздывать с кормлением
rus_verbs:таскаться{}, // таскаться с сумками
rus_verbs:контрастировать{}, // контрастировать с туфлями
rus_verbs:сшибиться{}, // сшибиться с форвардом
rus_verbs:состязаться{}, // состязаться с лучшей командой
rus_verbs:затрудниться{}, // затрудниться с объяснением
rus_verbs:объясниться{}, // объясниться с пострадавшими
rus_verbs:разводиться{}, // разводиться со сварливой женой
rus_verbs:препираться{}, // препираться с адвокатами
rus_verbs:сосуществовать{}, // сосуществовать с крупными хищниками
rus_verbs:свестись{}, // свестись с нулевым счетом
rus_verbs:обговорить{}, // обговорить с директором
rus_verbs:обвенчаться{}, // обвенчаться с ведьмой
rus_verbs:экспериментировать{}, // экспериментировать с генами
rus_verbs:сверять{}, // сверять с таблицей
rus_verbs:сверяться{}, // свериться с таблицей
rus_verbs:сблизить{}, // сблизить с точкой
rus_verbs:гармонировать{}, // гармонировать с обоями
rus_verbs:перемешивать{}, // перемешивать с молоком
rus_verbs:трепаться{}, // трепаться с сослуживцами
rus_verbs:перемигиваться{}, // перемигиваться с соседкой
rus_verbs:разоткровенничаться{}, // разоткровенничаться с незнакомцем
rus_verbs:распить{}, // распить с собутыльниками
rus_verbs:скрестись{}, // скрестись с дикой лошадью
rus_verbs:передраться{}, // передраться с дворовыми собаками
rus_verbs:умыть{}, // умыть с мылом
rus_verbs:грызться{}, // грызться с соседями
rus_verbs:переругиваться{}, // переругиваться с соседями
rus_verbs:доиграться{}, // доиграться со спичками
rus_verbs:заладиться{}, // заладиться с подругой
rus_verbs:скрещиваться{}, // скрещиваться с дикими видами
rus_verbs:повидаться{}, // повидаться с дедушкой
rus_verbs:повоевать{}, // повоевать с орками
rus_verbs:сразиться{}, // сразиться с лучшим рыцарем
rus_verbs:кипятить{}, // кипятить с отбеливателем
rus_verbs:усердствовать{}, // усердствовать с наказанием
rus_verbs:схлестнуться{}, // схлестнуться с лучшим боксером
rus_verbs:пошептаться{}, // пошептаться с судьями
rus_verbs:сравняться{}, // сравняться с лучшими экземплярами
rus_verbs:церемониться{}, // церемониться с пьяницами
rus_verbs:консультироваться{}, // консультироваться со специалистами
rus_verbs:переусердствовать{}, // переусердствовать с наказанием
rus_verbs:проноситься{}, // проноситься с собой
rus_verbs:перемешать{}, // перемешать с гипсом
rus_verbs:темнить{}, // темнить с долгами
rus_verbs:сталкивать{}, // сталкивать с черной дырой
rus_verbs:увольнять{}, // увольнять с волчьим билетом
rus_verbs:заигрывать{}, // заигрывать с совершенно диким животным
rus_verbs:сопоставлять{}, // сопоставлять с эталонными образцами
rus_verbs:расторгнуть{}, // расторгнуть с нерасторопными поставщиками долгосрочный контракт
rus_verbs:созвониться{}, // созвониться с мамой
rus_verbs:спеться{}, // спеться с отъявленными хулиганами
rus_verbs:интриговать{}, // интриговать с придворными
rus_verbs:приобрести{}, // приобрести со скидкой
rus_verbs:задержаться{}, // задержаться со сдачей работы
rus_verbs:плавать{}, // плавать со спасательным кругом
rus_verbs:якшаться{}, // Не якшайся с врагами
инфинитив:ассоциировать{вид:соверш}, // читатели ассоциируют с собой героя книги
инфинитив:ассоциировать{вид:несоверш},
глагол:ассоциировать{вид:соверш}, // читатели ассоциируют с собой героя книги
глагол:ассоциировать{вид:несоверш},
//+прилагательное:ассоциировавший{вид:несоверш},
прилагательное:ассоциировавший{вид:соверш},
прилагательное:ассоциирующий{},
деепричастие:ассоциируя{},
деепричастие:ассоциировав{},
rus_verbs:ассоциироваться{}, // герой книги ассоциируется с реальным персонажем
rus_verbs:аттестовывать{}, // Они аттестовывают сотрудников с помощью наборра тестов
rus_verbs:аттестовываться{}, // Сотрудники аттестовываются с помощью набора тестов
//+инфинитив:аффилировать{вид:соверш}, // эти предприятия были аффилированы с олигархом
//+глагол:аффилировать{вид:соверш},
прилагательное:аффилированный{},
rus_verbs:баловаться{}, // мальчик баловался с молотком
rus_verbs:балясничать{}, // женщина балясничала с товарками
rus_verbs:богатеть{}, // Провинция богатеет от торговли с соседями
rus_verbs:бодаться{}, // теленок бодается с деревом
rus_verbs:боксировать{}, // Майкл дважды боксировал с ним
rus_verbs:брататься{}, // Солдаты братались с бойцами союзников
rus_verbs:вальсировать{}, // Мальчик вальсирует с девочкой
rus_verbs:вверстывать{}, // Дизайнер с трудом вверстывает блоки в страницу
rus_verbs:происходить{}, // Что происходит с мировой экономикой?
rus_verbs:произойти{}, // Что произошло с экономикой?
rus_verbs:взаимодействовать{}, // Электроны взаимодействуют с фотонами
rus_verbs:вздорить{}, // Эта женщина часто вздорила с соседями
rus_verbs:сойтись{}, // Мальчик сошелся с бандой хулиганов
rus_verbs:вобрать{}, // вобрать в себя лучшие методы борьбы с вредителями
rus_verbs:водиться{}, // Няня водится с детьми
rus_verbs:воевать{}, // Фермеры воевали с волками
rus_verbs:возиться{}, // Няня возится с детьми
rus_verbs:ворковать{}, // Голубь воркует с голубкой
rus_verbs:воссоединиться{}, // Дети воссоединились с семьей
rus_verbs:воссоединяться{}, // Дети воссоединяются с семьей
rus_verbs:вошкаться{}, // Не вошкайся с этой ерундой
rus_verbs:враждовать{}, // враждовать с соседями
rus_verbs:временить{}, // временить с выходом на пенсию
rus_verbs:расстаться{}, // я не могу расстаться с тобой
rus_verbs:выдирать{}, // выдирать с мясом
rus_verbs:выдираться{}, // выдираться с мясом
rus_verbs:вытворить{}, // вытворить что-либо с чем-либо
rus_verbs:вытворять{}, // вытворять что-либо с чем-либо
rus_verbs:сделать{}, // сделать с чем-то
rus_verbs:домыть{}, // домыть с мылом
rus_verbs:случиться{}, // случиться с кем-то
rus_verbs:остаться{}, // остаться с кем-то
rus_verbs:случать{}, // случать с породистым кобельком
rus_verbs:послать{}, // послать с весточкой
rus_verbs:работать{}, // работать с роботами
rus_verbs:провести{}, // провести с девчонками время
rus_verbs:заговорить{}, // заговорить с незнакомкой
rus_verbs:прошептать{}, // прошептать с придыханием
rus_verbs:читать{}, // читать с выражением
rus_verbs:слушать{}, // слушать с повышенным вниманием
rus_verbs:принести{}, // принести с собой
rus_verbs:спать{}, // спать с женщинами
rus_verbs:закончить{}, // закончить с приготовлениями
rus_verbs:помочь{}, // помочь с перестановкой
rus_verbs:уехать{}, // уехать с семьей
rus_verbs:случаться{}, // случаться с кем-то
rus_verbs:кутить{}, // кутить с проститутками
rus_verbs:разговаривать{}, // разговаривать с ребенком
rus_verbs:погодить{}, // погодить с ликвидацией
rus_verbs:считаться{}, // считаться с чужим мнением
rus_verbs:носить{}, // носить с собой
rus_verbs:хорошеть{}, // хорошеть с каждым днем
rus_verbs:приводить{}, // приводить с собой
rus_verbs:прыгнуть{}, // прыгнуть с парашютом
rus_verbs:петь{}, // петь с чувством
rus_verbs:сложить{}, // сложить с результатом
rus_verbs:познакомиться{}, // познакомиться с другими студентами
rus_verbs:обращаться{}, // обращаться с животными
rus_verbs:съесть{}, // съесть с хлебом
rus_verbs:ошибаться{}, // ошибаться с дозировкой
rus_verbs:столкнуться{}, // столкнуться с медведем
rus_verbs:справиться{}, // справиться с нуждой
rus_verbs:торопиться{}, // торопиться с ответом
rus_verbs:поздравлять{}, // поздравлять с победой
rus_verbs:объясняться{}, // объясняться с начальством
rus_verbs:пошутить{}, // пошутить с подругой
rus_verbs:поздороваться{}, // поздороваться с коллегами
rus_verbs:поступать{}, // Как поступать с таким поведением?
rus_verbs:определяться{}, // определяться с кандидатами
rus_verbs:связаться{}, // связаться с поставщиком
rus_verbs:спорить{}, // спорить с собеседником
rus_verbs:разобраться{}, // разобраться с делами
rus_verbs:ловить{}, // ловить с удочкой
rus_verbs:помедлить{}, // Кандидат помедлил с ответом на заданный вопрос
rus_verbs:шутить{}, // шутить с диким зверем
rus_verbs:разорвать{}, // разорвать с поставщиком контракт
rus_verbs:увезти{}, // увезти с собой
rus_verbs:унести{}, // унести с собой
rus_verbs:сотворить{}, // сотворить с собой что-то нехорошее
rus_verbs:складываться{}, // складываться с первым импульсом
rus_verbs:соглашаться{}, // соглашаться с предложенным договором
//rus_verbs:покончить{}, // покончить с развратом
rus_verbs:прихватить{}, // прихватить с собой
rus_verbs:похоронить{}, // похоронить с почестями
rus_verbs:связывать{}, // связывать с компанией свою судьбу
rus_verbs:совпадать{}, // совпадать с предсказанием
rus_verbs:танцевать{}, // танцевать с девушками
rus_verbs:поделиться{}, // поделиться с выжившими
rus_verbs:оставаться{}, // я не хотел оставаться с ним в одной комнате.
rus_verbs:беседовать{}, // преподаватель, беседующий со студентами
rus_verbs:бороться{}, // человек, борющийся со смертельной болезнью
rus_verbs:шептаться{}, // девочка, шепчущаяся с подругой
rus_verbs:сплетничать{}, // женщина, сплетничавшая с товарками
rus_verbs:поговорить{}, // поговорить с виновниками
rus_verbs:сказать{}, // сказать с трудом
rus_verbs:произнести{}, // произнести с трудом
rus_verbs:говорить{}, // говорить с акцентом
rus_verbs:произносить{}, // произносить с трудом
rus_verbs:встречаться{}, // кто с Антонио встречался?
rus_verbs:посидеть{}, // посидеть с друзьями
rus_verbs:расквитаться{}, // расквитаться с обидчиком
rus_verbs:поквитаться{}, // поквитаться с обидчиком
rus_verbs:ругаться{}, // ругаться с женой
rus_verbs:поскандалить{}, // поскандалить с женой
rus_verbs:потанцевать{}, // потанцевать с подругой
rus_verbs:скандалить{}, // скандалить с соседями
rus_verbs:разругаться{}, // разругаться с другом
rus_verbs:болтать{}, // болтать с подругами
rus_verbs:потрепаться{}, // потрепаться с соседкой
rus_verbs:войти{}, // войти с регистрацией
rus_verbs:входить{}, // входить с регистрацией
rus_verbs:возвращаться{}, // возвращаться с триумфом
rus_verbs:опоздать{}, // Он опоздал с подачей сочинения.
rus_verbs:молчать{}, // Он молчал с ледяным спокойствием.
rus_verbs:сражаться{}, // Он героически сражался с врагами.
rus_verbs:выходить{}, // Он всегда выходит с зонтиком.
rus_verbs:сличать{}, // сличать перевод с оригиналом
rus_verbs:начать{}, // я начал с товарищем спор о религии
rus_verbs:согласовать{}, // Маша согласовала с Петей дальнейшие поездки
rus_verbs:приходить{}, // Приходите с нею.
rus_verbs:жить{}, // кто с тобой жил?
rus_verbs:расходиться{}, // Маша расходится с Петей
rus_verbs:сцеплять{}, // сцеплять карабин с обвязкой
rus_verbs:торговать{}, // мы торгуем с ними нефтью
rus_verbs:уединяться{}, // уединяться с подругой в доме
rus_verbs:уладить{}, // уладить конфликт с соседями
rus_verbs:идти{}, // Я шел туда с тяжёлым сердцем.
rus_verbs:разделять{}, // Я разделяю с вами горе и радость.
rus_verbs:обратиться{}, // Я обратился к нему с просьбой о помощи.
rus_verbs:захватить{}, // Я не захватил с собой денег.
прилагательное:знакомый{}, // Я знаком с ними обоими.
rus_verbs:вести{}, // Я веду с ней переписку.
прилагательное:сопряженный{}, // Это сопряжено с большими трудностями.
прилагательное:связанный{причастие}, // Это дело связано с риском.
rus_verbs:поехать{}, // Хотите поехать со мной в театр?
rus_verbs:проснуться{}, // Утром я проснулся с ясной головой.
rus_verbs:лететь{}, // Самолёт летел со скоростью звука.
rus_verbs:играть{}, // С огнём играть опасно!
rus_verbs:поделать{}, // С ним ничего не поделаешь.
rus_verbs:стрястись{}, // С ней стряслось несчастье.
rus_verbs:смотреться{}, // Пьеса смотрится с удовольствием.
rus_verbs:смотреть{}, // Она смотрела на меня с явным неудовольствием.
rus_verbs:разойтись{}, // Она разошлась с мужем.
rus_verbs:пристать{}, // Она пристала ко мне с расспросами.
rus_verbs:посмотреть{}, // Она посмотрела на меня с удивлением.
rus_verbs:поступить{}, // Она плохо поступила с ним.
rus_verbs:выйти{}, // Она вышла с усталым и недовольным видом.
rus_verbs:взять{}, // Возьмите с собой только самое необходимое.
rus_verbs:наплакаться{}, // Наплачется она с ним.
rus_verbs:лежать{}, // Он лежит с воспалением лёгких.
rus_verbs:дышать{}, // дышащий с трудом
rus_verbs:брать{}, // брать с собой
rus_verbs:мчаться{}, // Автомобиль мчится с необычайной быстротой.
rus_verbs:упасть{}, // Ваза упала со звоном.
rus_verbs:вернуться{}, // мы вернулись вчера домой с полным лукошком
rus_verbs:сидеть{}, // Она сидит дома с ребенком
rus_verbs:встретиться{}, // встречаться с кем-либо
ГЛ_ИНФ(придти), прилагательное:пришедший{}, // пришедший с другом
ГЛ_ИНФ(постирать), прилагательное:постиранный{}, деепричастие:постирав{},
rus_verbs:мыть{}
}
fact гл_предл
{
if context { Гл_С_Твор предлог:с{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_С_Твор предлог:с{} *:*{падеж:твор} }
then return true
}
#endregion ТВОРИТЕЛЬНЫЙ
#region РОДИТЕЛЬНЫЙ
wordentry_set Гл_С_Род=
{
rus_verbs:УХОДИТЬ{}, // Но с базы не уходить.
rus_verbs:РВАНУТЬ{}, // Водитель прорычал проклятие и рванул машину с места. (РВАНУТЬ)
rus_verbs:ОХВАТИТЬ{}, // огонь охватил его со всех сторон (ОХВАТИТЬ)
rus_verbs:ЗАМЕТИТЬ{}, // Он понимал, что свет из тайника невозможно заметить с палубы (ЗАМЕТИТЬ/РАЗГЛЯДЕТЬ)
rus_verbs:РАЗГЛЯДЕТЬ{}, //
rus_verbs:СПЛАНИРОВАТЬ{}, // Птицы размером с орлицу, вероятно, не могли бы подняться в воздух, не спланировав с высокого утеса. (СПЛАНИРОВАТЬ)
rus_verbs:УМЕРЕТЬ{}, // Он умрет с голоду. (УМЕРЕТЬ)
rus_verbs:ВСПУГНУТЬ{}, // Оба упали с лязгом, вспугнувшим птиц с ближайших деревьев (ВСПУГНУТЬ)
rus_verbs:РЕВЕТЬ{}, // Время от времени какой-то ящер ревел с берега или самой реки. (РЕВЕТЬ/ЗАРЕВЕТЬ/ПРОРЕВЕТЬ/ЗАОРАТЬ/ПРООРАТЬ/ОРАТЬ/ПРОКРИЧАТЬ/ЗАКРИЧАТЬ/ВОПИТЬ/ЗАВОПИТЬ)
rus_verbs:ЗАРЕВЕТЬ{}, //
rus_verbs:ПРОРЕВЕТЬ{}, //
rus_verbs:ЗАОРАТЬ{}, //
rus_verbs:ПРООРАТЬ{}, //
rus_verbs:ОРАТЬ{}, //
rus_verbs:ЗАКРИЧАТЬ{},
rus_verbs:ВОПИТЬ{}, //
rus_verbs:ЗАВОПИТЬ{}, //
rus_verbs:СТАЩИТЬ{}, // Я видела как они стащили его с валуна и увели с собой. (СТАЩИТЬ/СТАСКИВАТЬ)
rus_verbs:СТАСКИВАТЬ{}, //
rus_verbs:ПРОВЫТЬ{}, // Призрак трубного зова провыл с другой стороны дверей. (ПРОВЫТЬ, ЗАВЫТЬ, ВЫТЬ)
rus_verbs:ЗАВЫТЬ{}, //
rus_verbs:ВЫТЬ{}, //
rus_verbs:СВЕТИТЬ{}, // Полуденное майское солнце ярко светило с голубых небес Аризоны. (СВЕТИТЬ)
rus_verbs:ОТСВЕЧИВАТЬ{}, // Солнце отсвечивало с белых лошадей, белых щитов и белых перьев и искрилось на наконечниках пик. (ОТСВЕЧИВАТЬ С, ИСКРИТЬСЯ НА)
rus_verbs:перегнать{}, // Скот нужно перегнать с этого пастбища на другое
rus_verbs:собирать{}, // мальчики начали собирать со столов посуду
rus_verbs:разглядывать{}, // ты ее со всех сторон разглядывал
rus_verbs:СЖИМАТЬ{}, // меня плотно сжимали со всех сторон (СЖИМАТЬ)
rus_verbs:СОБРАТЬСЯ{}, // со всего света собрались! (СОБРАТЬСЯ)
rus_verbs:ИЗГОНЯТЬ{}, // Вино в пакетах изгоняют с рынка (ИЗГОНЯТЬ)
rus_verbs:ВЛЮБИТЬСЯ{}, // влюбился в нее с первого взгляда (ВЛЮБИТЬСЯ)
rus_verbs:РАЗДАВАТЬСЯ{}, // теперь крик раздавался со всех сторон (РАЗДАВАТЬСЯ)
rus_verbs:ПОСМОТРЕТЬ{}, // Посмотрите на это с моей точки зрения (ПОСМОТРЕТЬ С род)
rus_verbs:СХОДИТЬ{}, // принимать участие во всех этих событиях - значит продолжать сходить с ума (СХОДИТЬ С род)
rus_verbs:РУХНУТЬ{}, // В Башкирии микроавтобус рухнул с моста (РУХНУТЬ С)
rus_verbs:УВОЛИТЬ{}, // рекомендовать уволить их с работы (УВОЛИТЬ С)
rus_verbs:КУПИТЬ{}, // еда , купленная с рук (КУПИТЬ С род)
rus_verbs:УБРАТЬ{}, // помочь убрать со стола? (УБРАТЬ С)
rus_verbs:ТЯНУТЬ{}, // с моря тянуло ветром (ТЯНУТЬ С)
rus_verbs:ПРИХОДИТЬ{}, // приходит с работы муж (ПРИХОДИТЬ С)
rus_verbs:ПРОПАСТЬ{}, // изображение пропало с экрана (ПРОПАСТЬ С)
rus_verbs:ПОТЯНУТЬ{}, // с балкона потянуло холодом (ПОТЯНУТЬ С род)
rus_verbs:РАЗДАТЬСЯ{}, // с палубы раздался свист (РАЗДАТЬСЯ С род)
rus_verbs:ЗАЙТИ{}, // зашел с другой стороны (ЗАЙТИ С род)
rus_verbs:НАЧАТЬ{}, // давай начнем с этого (НАЧАТЬ С род)
rus_verbs:УВЕСТИ{}, // дала увести с развалин (УВЕСТИ С род)
rus_verbs:ОПУСКАТЬСЯ{}, // с гор опускалась ночь (ОПУСКАТЬСЯ С)
rus_verbs:ВСКОЧИТЬ{}, // Тристан вскочил с места (ВСКОЧИТЬ С род)
rus_verbs:БРАТЬ{}, // беру с него пример (БРАТЬ С род)
rus_verbs:ПРИПОДНЯТЬСЯ{}, // голова приподнялась с плеча (ПРИПОДНЯТЬСЯ С род)
rus_verbs:ПОЯВИТЬСЯ{}, // всадники появились с востока (ПОЯВИТЬСЯ С род)
rus_verbs:НАЛЕТЕТЬ{}, // с моря налетел ветер (НАЛЕТЕТЬ С род)
rus_verbs:ВЗВИТЬСЯ{}, // Натан взвился с места (ВЗВИТЬСЯ С род)
rus_verbs:ПОДОБРАТЬ{}, // подобрал с земли копье (ПОДОБРАТЬ С)
rus_verbs:ДЕРНУТЬСЯ{}, // Кирилл дернулся с места (ДЕРНУТЬСЯ С род)
rus_verbs:ВОЗВРАЩАТЬСЯ{}, // они возвращались с реки (ВОЗВРАЩАТЬСЯ С род)
rus_verbs:ПЛЫТЬ{}, // плыли они с запада (ПЛЫТЬ С род)
rus_verbs:ЗНАТЬ{}, // одно знали с древности (ЗНАТЬ С)
rus_verbs:НАКЛОНИТЬСЯ{}, // всадник наклонился с лошади (НАКЛОНИТЬСЯ С)
rus_verbs:НАЧАТЬСЯ{}, // началось все со скуки (НАЧАТЬСЯ С)
прилагательное:ИЗВЕСТНЫЙ{}, // Культура его известна со времен глубокой древности (ИЗВЕСТНЫЙ С)
rus_verbs:СБИТЬ{}, // Порыв ветра сбил Ваньку с ног (ts СБИТЬ С)
rus_verbs:СОБИРАТЬСЯ{}, // они собираются сюда со всей равнины. (СОБИРАТЬСЯ С род)
rus_verbs:смыть{}, // Дождь должен смыть с листьев всю пыль. (СМЫТЬ С)
rus_verbs:привстать{}, // Мартин привстал со своего стула. (привстать с)
rus_verbs:спасть{}, // тяжесть спала с души. (спасть с)
rus_verbs:выглядеть{}, // так оно со стороны выглядело. (ВЫГЛЯДЕТЬ С)
rus_verbs:повернуть{}, // к вечеру они повернули с нее направо. (ПОВЕРНУТЬ С)
rus_verbs:ТЯНУТЬСЯ{}, // со стороны реки ко мне тянулись языки тумана. (ТЯНУТЬСЯ С)
rus_verbs:ВОЕВАТЬ{}, // Генерал воевал с юных лет. (ВОЕВАТЬ С чего-то)
rus_verbs:БОЛЕТЬ{}, // Голова болит с похмелья. (БОЛЕТЬ С)
rus_verbs:приближаться{}, // со стороны острова приближалась лодка.
rus_verbs:ПОТЯНУТЬСЯ{}, // со всех сторон к нему потянулись руки. (ПОТЯНУТЬСЯ С)
rus_verbs:пойти{}, // низкий гул пошел со стороны долины. (пошел с)
rus_verbs:зашевелиться{}, // со всех сторон зашевелились кусты. (зашевелиться с)
rus_verbs:МЧАТЬСЯ{}, // со стороны леса мчались всадники. (МЧАТЬСЯ С)
rus_verbs:БЕЖАТЬ{}, // люди бежали со всех ног. (БЕЖАТЬ С)
rus_verbs:СЛЫШАТЬСЯ{}, // шум слышался со стороны моря. (СЛЫШАТЬСЯ С)
rus_verbs:ЛЕТЕТЬ{}, // со стороны деревни летела птица. (ЛЕТЕТЬ С)
rus_verbs:ПЕРЕТЬ{}, // враги прут со всех сторон. (ПЕРЕТЬ С)
rus_verbs:ПОСЫПАТЬСЯ{}, // вопросы посыпались со всех сторон. (ПОСЫПАТЬСЯ С)
rus_verbs:ИДТИ{}, // угроза шла со стороны моря. (ИДТИ С + род.п.)
rus_verbs:ПОСЛЫШАТЬСЯ{}, // со стен послышались крики ужаса. (ПОСЛЫШАТЬСЯ С)
rus_verbs:ОБРУШИТЬСЯ{}, // звуки обрушились со всех сторон. (ОБРУШИТЬСЯ С)
rus_verbs:УДАРИТЬ{}, // голоса ударили со всех сторон. (УДАРИТЬ С)
rus_verbs:ПОКАЗАТЬСЯ{}, // со стороны деревни показались земляне. (ПОКАЗАТЬСЯ С)
rus_verbs:прыгать{}, // придется прыгать со второго этажа. (прыгать с)
rus_verbs:СТОЯТЬ{}, // со всех сторон стоял лес. (СТОЯТЬ С)
rus_verbs:доноситься{}, // шум со двора доносился чудовищный. (доноситься с)
rus_verbs:мешать{}, // мешать воду с мукой (мешать с)
rus_verbs:вестись{}, // Переговоры ведутся с позиции силы. (вестись с)
rus_verbs:вставать{}, // Он не встает с кровати. (вставать с)
rus_verbs:окружать{}, // зеленые щупальца окружали ее со всех сторон. (окружать с)
rus_verbs:причитаться{}, // С вас причитается 50 рублей.
rus_verbs:соскользнуть{}, // его острый клюв соскользнул с ее руки.
rus_verbs:сократить{}, // Его сократили со службы.
rus_verbs:поднять{}, // рука подняла с пола
rus_verbs:поднимать{},
rus_verbs:тащить{}, // тем временем другие пришельцы тащили со всех сторон камни.
rus_verbs:полететь{}, // Мальчик полетел с лестницы.
rus_verbs:литься{}, // вода льется с неба
rus_verbs:натечь{}, // натечь с сапог
rus_verbs:спрыгивать{}, // спрыгивать с движущегося трамвая
rus_verbs:съезжать{}, // съезжать с заявленной темы
rus_verbs:покатываться{}, // покатываться со смеху
rus_verbs:перескакивать{}, // перескакивать с одного примера на другой
rus_verbs:сдирать{}, // сдирать с тела кожу
rus_verbs:соскальзывать{}, // соскальзывать с крючка
rus_verbs:сметать{}, // сметать с прилавков
rus_verbs:кувыркнуться{}, // кувыркнуться со ступеньки
rus_verbs:прокаркать{}, // прокаркать с ветки
rus_verbs:стряхивать{}, // стряхивать с одежды
rus_verbs:сваливаться{}, // сваливаться с лестницы
rus_verbs:слизнуть{}, // слизнуть с лица
rus_verbs:доставляться{}, // доставляться с фермы
rus_verbs:обступать{}, // обступать с двух сторон
rus_verbs:повскакивать{}, // повскакивать с мест
rus_verbs:обозревать{}, // обозревать с вершины
rus_verbs:слинять{}, // слинять с урока
rus_verbs:смывать{}, // смывать с лица
rus_verbs:спихнуть{}, // спихнуть со стола
rus_verbs:обозреть{}, // обозреть с вершины
rus_verbs:накупить{}, // накупить с рук
rus_verbs:схлынуть{}, // схлынуть с берега
rus_verbs:спикировать{}, // спикировать с километровой высоты
rus_verbs:уползти{}, // уползти с поля боя
rus_verbs:сбиваться{}, // сбиваться с пути
rus_verbs:отлучиться{}, // отлучиться с поста
rus_verbs:сигануть{}, // сигануть с крыши
rus_verbs:сместить{}, // сместить с поста
rus_verbs:списать{}, // списать с оригинального устройства
инфинитив:слетать{ вид:несоверш }, глагол:слетать{ вид:несоверш }, // слетать с трассы
деепричастие:слетая{},
rus_verbs:напиваться{}, // напиваться с горя
rus_verbs:свесить{}, // свесить с крыши
rus_verbs:заполучить{}, // заполучить со склада
rus_verbs:спадать{}, // спадать с глаз
rus_verbs:стартовать{}, // стартовать с мыса
rus_verbs:спереть{}, // спереть со склада
rus_verbs:согнать{}, // согнать с живота
rus_verbs:скатываться{}, // скатываться со стога
rus_verbs:сняться{}, // сняться с выборов
rus_verbs:слезать{}, // слезать со стола
rus_verbs:деваться{}, // деваться с подводной лодки
rus_verbs:огласить{}, // огласить с трибуны
rus_verbs:красть{}, // красть со склада
rus_verbs:расширить{}, // расширить с торца
rus_verbs:угадывать{}, // угадывать с полуслова
rus_verbs:оскорбить{}, // оскорбить со сцены
rus_verbs:срывать{}, // срывать с головы
rus_verbs:сшибить{}, // сшибить с коня
rus_verbs:сбивать{}, // сбивать с одежды
rus_verbs:содрать{}, // содрать с посетителей
rus_verbs:столкнуть{}, // столкнуть с горы
rus_verbs:отряхнуть{}, // отряхнуть с одежды
rus_verbs:сбрасывать{}, // сбрасывать с борта
rus_verbs:расстреливать{}, // расстреливать с борта вертолета
rus_verbs:придти{}, // мать скоро придет с работы
rus_verbs:съехать{}, // Миша съехал с горки
rus_verbs:свисать{}, // свисать с веток
rus_verbs:стянуть{}, // стянуть с кровати
rus_verbs:скинуть{}, // скинуть снег с плеча
rus_verbs:загреметь{}, // загреметь со стула
rus_verbs:сыпаться{}, // сыпаться с неба
rus_verbs:стряхнуть{}, // стряхнуть с головы
rus_verbs:сползти{}, // сползти со стула
rus_verbs:стереть{}, // стереть с экрана
rus_verbs:прогнать{}, // прогнать с фермы
rus_verbs:смахнуть{}, // смахнуть со стола
rus_verbs:спускать{}, // спускать с поводка
rus_verbs:деться{}, // деться с подводной лодки
rus_verbs:сдернуть{}, // сдернуть с себя
rus_verbs:сдвинуться{}, // сдвинуться с места
rus_verbs:слететь{}, // слететь с катушек
rus_verbs:обступить{}, // обступить со всех сторон
rus_verbs:снести{}, // снести с плеч
инфинитив:сбегать{ вид:несоверш }, глагол:сбегать{ вид:несоверш }, // сбегать с уроков
деепричастие:сбегая{}, прилагательное:сбегающий{},
// прилагательное:сбегавший{ вид:несоверш },
rus_verbs:запить{}, // запить с горя
rus_verbs:рубануть{}, // рубануть с плеча
rus_verbs:чертыхнуться{}, // чертыхнуться с досады
rus_verbs:срываться{}, // срываться с цепи
rus_verbs:смыться{}, // смыться с уроков
rus_verbs:похитить{}, // похитить со склада
rus_verbs:смести{}, // смести со своего пути
rus_verbs:отгружать{}, // отгружать со склада
rus_verbs:отгрузить{}, // отгрузить со склада
rus_verbs:бросаться{}, // Дети бросались в воду с моста
rus_verbs:броситься{}, // самоубийца бросился с моста в воду
rus_verbs:взимать{}, // Билетер взимает плату с каждого посетителя
rus_verbs:взиматься{}, // Плата взимается с любого посетителя
rus_verbs:взыскать{}, // Приставы взыскали долг с бедолаги
rus_verbs:взыскивать{}, // Приставы взыскивают с бедолаги все долги
rus_verbs:взыскиваться{}, // Долги взыскиваются с алиментщиков
rus_verbs:вспархивать{}, // вспархивать с цветка
rus_verbs:вспорхнуть{}, // вспорхнуть с ветки
rus_verbs:выбросить{}, // выбросить что-то с балкона
rus_verbs:выводить{}, // выводить с одежды пятна
rus_verbs:снять{}, // снять с головы
rus_verbs:начинать{}, // начинать с эскиза
rus_verbs:двинуться{}, // двинуться с места
rus_verbs:начинаться{}, // начинаться с гардероба
rus_verbs:стечь{}, // стечь с крыши
rus_verbs:слезть{}, // слезть с кучи
rus_verbs:спуститься{}, // спуститься с крыши
rus_verbs:сойти{}, // сойти с пьедестала
rus_verbs:свернуть{}, // свернуть с пути
rus_verbs:сорвать{}, // сорвать с цепи
rus_verbs:сорваться{}, // сорваться с поводка
rus_verbs:тронуться{}, // тронуться с места
rus_verbs:угадать{}, // угадать с первой попытки
rus_verbs:спустить{}, // спустить с лестницы
rus_verbs:соскочить{}, // соскочить с крючка
rus_verbs:сдвинуть{}, // сдвинуть с места
rus_verbs:подниматься{}, // туман, поднимающийся с болота
rus_verbs:подняться{}, // туман, поднявшийся с болота
rus_verbs:валить{}, // Резкий порывистый ветер валит прохожих с ног.
rus_verbs:свалить{}, // Резкий порывистый ветер свалит тебя с ног.
rus_verbs:донестись{}, // С улицы донесся шум дождя.
rus_verbs:опасть{}, // Опавшие с дерева листья.
rus_verbs:махнуть{}, // Он махнул с берега в воду.
rus_verbs:исчезнуть{}, // исчезнуть с экрана
rus_verbs:свалиться{}, // свалиться со сцены
rus_verbs:упасть{}, // упасть с дерева
rus_verbs:вернуться{}, // Он ещё не вернулся с работы.
rus_verbs:сдувать{}, // сдувать пух с одуванчиков
rus_verbs:свергать{}, // свергать царя с трона
rus_verbs:сбиться{}, // сбиться с пути
rus_verbs:стирать{}, // стирать тряпкой надпись с доски
rus_verbs:убирать{}, // убирать мусор c пола
rus_verbs:удалять{}, // удалять игрока с поля
rus_verbs:окружить{}, // Япония окружена со всех сторон морями.
rus_verbs:снимать{}, // Я снимаю с себя всякую ответственность за его поведение.
глагол:писаться{ aux stress="пис^аться" }, // Собственные имена пишутся с большой буквы.
прилагательное:спокойный{}, // С этой стороны я спокоен.
rus_verbs:спросить{}, // С тебя за всё спросят.
rus_verbs:течь{}, // С него течёт пот.
rus_verbs:дуть{}, // С моря дует ветер.
rus_verbs:капать{}, // С его лица капали крупные капли пота.
rus_verbs:опустить{}, // Она опустила ребёнка с рук на пол.
rus_verbs:спрыгнуть{}, // Она легко спрыгнула с коня.
rus_verbs:встать{}, // Все встали со стульев.
rus_verbs:сбросить{}, // Войдя в комнату, он сбросил с себя пальто.
rus_verbs:взять{}, // Возьми книгу с полки.
rus_verbs:спускаться{}, // Мы спускались с горы.
rus_verbs:уйти{}, // Он нашёл себе заместителя и ушёл со службы.
rus_verbs:порхать{}, // Бабочка порхает с цветка на цветок.
rus_verbs:отправляться{}, // Ваш поезд отправляется со второй платформы.
rus_verbs:двигаться{}, // Он не двигался с места.
rus_verbs:отходить{}, // мой поезд отходит с первого пути
rus_verbs:попасть{}, // Майкл попал в кольцо с десятиметровой дистанции
rus_verbs:падать{}, // снег падает с ветвей
rus_verbs:скрыться{} // Ее водитель, бросив машину, скрылся с места происшествия.
}
fact гл_предл
{
if context { Гл_С_Род предлог:с{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_С_Род предлог:с{} *:*{падеж:род} }
then return true
}
fact гл_предл
{
if context { Гл_С_Род предлог:с{} *:*{падеж:парт} }
then return true
}
#endregion РОДИТЕЛЬНЫЙ
fact гл_предл
{
if context { * предлог:с{} *:*{ падеж:твор } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:с{} *:*{ падеж:род } }
then return false,-4
}
fact гл_предл
{
if context { * предлог:с{} * }
then return false,-5
}
#endregion Предлог_С
/*
#region Предлог_ПОД
// -------------- ПРЕДЛОГ 'ПОД' -----------------------
fact гл_предл
{
if context { * предлог:под{} @regex("[a-z]+[0-9]*") }
then return true
}
// ПОД+вин.п. не может присоединяться к существительным, поэтому
// он присоединяется к любым глаголам.
fact гл_предл
{
if context { * предлог:под{} *:*{ падеж:вин } }
then return true
}
wordentry_set Гл_ПОД_твор=
{
rus_verbs:извиваться{}, // извивалась под его длинными усами
rus_verbs:РАСПРОСТРАНЯТЬСЯ{}, // Под густым ковром травы и плотным сплетением корней (РАСПРОСТРАНЯТЬСЯ)
rus_verbs:БРОСИТЬ{}, // чтобы ты его под деревом бросил? (БРОСИТЬ)
rus_verbs:БИТЬСЯ{}, // под моей щекой сильно билось его сердце (БИТЬСЯ)
rus_verbs:ОПУСТИТЬСЯ{}, // глаза его опустились под ее желтым взглядом (ОПУСТИТЬСЯ)
rus_verbs:ВЗДЫМАТЬСЯ{}, // его грудь судорожно вздымалась под ее рукой (ВЗДЫМАТЬСЯ)
rus_verbs:ПРОМЧАТЬСЯ{}, // Она промчалась под ними и исчезла за изгибом горы. (ПРОМЧАТЬСЯ)
rus_verbs:всплыть{}, // Наконец он всплыл под нависавшей кормой, так и не отыскав того, что хотел. (всплыть)
rus_verbs:КОНЧАТЬСЯ{}, // Он почти вертикально уходит в реку и кончается глубоко под водой. (КОНЧАТЬСЯ)
rus_verbs:ПОЛЗТИ{}, // Там они ползли под спутанным терновником и сквозь переплетавшиеся кусты (ПОЛЗТИ)
rus_verbs:ПРОХОДИТЬ{}, // Вольф проходил под гигантскими ветвями деревьев и мхов, свисавших с ветвей зелеными водопадами. (ПРОХОДИТЬ, ПРОПОЛЗТИ, ПРОПОЛЗАТЬ)
rus_verbs:ПРОПОЛЗТИ{}, //
rus_verbs:ПРОПОЛЗАТЬ{}, //
rus_verbs:ИМЕТЬ{}, // Эти предположения не имеют под собой никакой почвы (ИМЕТЬ)
rus_verbs:НОСИТЬ{}, // она носит под сердцем ребенка (НОСИТЬ)
rus_verbs:ПАСТЬ{}, // Рим пал под натиском варваров (ПАСТЬ)
rus_verbs:УТОНУТЬ{}, // Выступавшие старческие вены снова утонули под гладкой твердой плотью. (УТОНУТЬ)
rus_verbs:ВАЛЯТЬСЯ{}, // Под его кривыми серыми ветвями и пестрыми коричнево-зелеными листьями валялись пустые ореховые скорлупки и сердцевины плодов. (ВАЛЯТЬСЯ)
rus_verbs:вздрогнуть{}, // она вздрогнула под его взглядом
rus_verbs:иметься{}, // у каждого под рукой имелся арбалет
rus_verbs:ЖДАТЬ{}, // Сашка уже ждал под дождем (ЖДАТЬ)
rus_verbs:НОЧЕВАТЬ{}, // мне приходилось ночевать под открытым небом (НОЧЕВАТЬ)
rus_verbs:УЗНАТЬ{}, // вы должны узнать меня под этим именем (УЗНАТЬ)
rus_verbs:ЗАДЕРЖИВАТЬСЯ{}, // мне нельзя задерживаться под землей! (ЗАДЕРЖИВАТЬСЯ)
rus_verbs:ПОГИБНУТЬ{}, // под их копытами погибли целые армии! (ПОГИБНУТЬ)
rus_verbs:РАЗДАВАТЬСЯ{}, // под ногами у меня раздавался сухой хруст (РАЗДАВАТЬСЯ)
rus_verbs:КРУЖИТЬСЯ{}, // поверхность планеты кружилась у него под ногами (КРУЖИТЬСЯ)
rus_verbs:ВИСЕТЬ{}, // под глазами у него висели тяжелые складки кожи (ВИСЕТЬ)
rus_verbs:содрогнуться{}, // содрогнулся под ногами каменный пол (СОДРОГНУТЬСЯ)
rus_verbs:СОБИРАТЬСЯ{}, // темнота уже собиралась под деревьями (СОБИРАТЬСЯ)
rus_verbs:УПАСТЬ{}, // толстяк упал под градом ударов (УПАСТЬ)
rus_verbs:ДВИНУТЬСЯ{}, // лодка двинулась под водой (ДВИНУТЬСЯ)
rus_verbs:ЦАРИТЬ{}, // под его крышей царила холодная зима (ЦАРИТЬ)
rus_verbs:ПРОВАЛИТЬСЯ{}, // под копытами его лошади провалился мост (ПРОВАЛИТЬСЯ ПОД твор)
rus_verbs:ЗАДРОЖАТЬ{}, // земля задрожала под ногами (ЗАДРОЖАТЬ)
rus_verbs:НАХМУРИТЬСЯ{}, // государь нахмурился под маской (НАХМУРИТЬСЯ)
rus_verbs:РАБОТАТЬ{}, // работать под угрозой нельзя (РАБОТАТЬ)
rus_verbs:ШЕВЕЛЬНУТЬСЯ{}, // под ногой шевельнулся камень (ШЕВЕЛЬНУТЬСЯ)
rus_verbs:ВИДЕТЬ{}, // видел тебя под камнем. (ВИДЕТЬ)
rus_verbs:ОСТАТЬСЯ{}, // второе осталось под водой (ОСТАТЬСЯ)
rus_verbs:КИПЕТЬ{}, // вода кипела под копытами (КИПЕТЬ)
rus_verbs:СИДЕТЬ{}, // может сидит под деревом (СИДЕТЬ)
rus_verbs:МЕЛЬКНУТЬ{}, // под нами мелькнуло море (МЕЛЬКНУТЬ)
rus_verbs:ПОСЛЫШАТЬСЯ{}, // под окном послышался шум (ПОСЛЫШАТЬСЯ)
rus_verbs:ТЯНУТЬСЯ{}, // под нами тянулись облака (ТЯНУТЬСЯ)
rus_verbs:ДРОЖАТЬ{}, // земля дрожала под ним (ДРОЖАТЬ)
rus_verbs:ПРИЙТИСЬ{}, // хуже пришлось под землей (ПРИЙТИСЬ)
rus_verbs:ГОРЕТЬ{}, // лампа горела под потолком (ГОРЕТЬ)
rus_verbs:ПОЛОЖИТЬ{}, // положил под деревом плащ (ПОЛОЖИТЬ)
rus_verbs:ЗАГОРЕТЬСЯ{}, // под деревьями загорелся костер (ЗАГОРЕТЬСЯ)
rus_verbs:ПРОНОСИТЬСЯ{}, // под нами проносились крыши (ПРОНОСИТЬСЯ)
rus_verbs:ПОТЯНУТЬСЯ{}, // под кораблем потянулись горы (ПОТЯНУТЬСЯ)
rus_verbs:БЕЖАТЬ{}, // беги под серой стеной ночи (БЕЖАТЬ)
rus_verbs:РАЗДАТЬСЯ{}, // под окном раздалось тяжелое дыхание (РАЗДАТЬСЯ)
rus_verbs:ВСПЫХНУТЬ{}, // под потолком вспыхнула яркая лампа (ВСПЫХНУТЬ)
rus_verbs:СМОТРЕТЬ{}, // просто смотрите под другим углом (СМОТРЕТЬ ПОД)
rus_verbs:ДУТЬ{}, // теперь под деревьями дул ветерок (ДУТЬ)
rus_verbs:СКРЫТЬСЯ{}, // оно быстро скрылось под водой (СКРЫТЬСЯ ПОД)
rus_verbs:ЩЕЛКНУТЬ{}, // далеко под ними щелкнул выстрел (ЩЕЛКНУТЬ)
rus_verbs:ТРЕЩАТЬ{}, // осколки стекла трещали под ногами (ТРЕЩАТЬ)
rus_verbs:РАСПОЛАГАТЬСЯ{}, // под ними располагались разноцветные скамьи (РАСПОЛАГАТЬСЯ)
rus_verbs:ВЫСТУПИТЬ{}, // под ногтями выступили капельки крови (ВЫСТУПИТЬ)
rus_verbs:НАСТУПИТЬ{}, // под куполом базы наступила тишина (НАСТУПИТЬ)
rus_verbs:ОСТАНОВИТЬСЯ{}, // повозка остановилась под самым окном (ОСТАНОВИТЬСЯ)
rus_verbs:РАСТАЯТЬ{}, // магазин растаял под ночным дождем (РАСТАЯТЬ)
rus_verbs:ДВИГАТЬСЯ{}, // под водой двигалось нечто огромное (ДВИГАТЬСЯ)
rus_verbs:БЫТЬ{}, // под снегом могут быть трещины (БЫТЬ)
rus_verbs:ЗИЯТЬ{}, // под ней зияла ужасная рана (ЗИЯТЬ)
rus_verbs:ЗАЗВОНИТЬ{}, // под рукой водителя зазвонил телефон (ЗАЗВОНИТЬ)
rus_verbs:ПОКАЗАТЬСЯ{}, // внезапно под ними показалась вода (ПОКАЗАТЬСЯ)
rus_verbs:ЗАМЕРЕТЬ{}, // эхо замерло под высоким потолком (ЗАМЕРЕТЬ)
rus_verbs:ПОЙТИ{}, // затем под кораблем пошла пустыня (ПОЙТИ)
rus_verbs:ДЕЙСТВОВАТЬ{}, // боги всегда действуют под маской (ДЕЙСТВОВАТЬ)
rus_verbs:БЛЕСТЕТЬ{}, // мокрый мех блестел под луной (БЛЕСТЕТЬ)
rus_verbs:ЛЕТЕТЬ{}, // под ним летела серая земля (ЛЕТЕТЬ)
rus_verbs:СОГНУТЬСЯ{}, // содрогнулся под ногами каменный пол (СОГНУТЬСЯ)
rus_verbs:КИВНУТЬ{}, // четвертый слегка кивнул под капюшоном (КИВНУТЬ)
rus_verbs:УМЕРЕТЬ{}, // колдун умер под грудой каменных глыб (УМЕРЕТЬ)
rus_verbs:ОКАЗЫВАТЬСЯ{}, // внезапно под ногами оказывается знакомая тропинка (ОКАЗЫВАТЬСЯ)
rus_verbs:ИСЧЕЗАТЬ{}, // серая лента дороги исчезала под воротами (ИСЧЕЗАТЬ)
rus_verbs:СВЕРКНУТЬ{}, // голубые глаза сверкнули под густыми бровями (СВЕРКНУТЬ)
rus_verbs:СИЯТЬ{}, // под ним сияла белая пелена облаков (СИЯТЬ)
rus_verbs:ПРОНЕСТИСЬ{}, // тихий смех пронесся под куполом зала (ПРОНЕСТИСЬ)
rus_verbs:СКОЛЬЗИТЬ{}, // обломки судна медленно скользили под ними (СКОЛЬЗИТЬ)
rus_verbs:ВЗДУТЬСЯ{}, // под серой кожей вздулись шары мускулов (ВЗДУТЬСЯ)
rus_verbs:ПРОЙТИ{}, // обломок отлично пройдет под колесами слева (ПРОЙТИ)
rus_verbs:РАЗВЕВАТЬСЯ{}, // светлые волосы развевались под дыханием ветра (РАЗВЕВАТЬСЯ)
rus_verbs:СВЕРКАТЬ{}, // глаза огнем сверкали под темными бровями (СВЕРКАТЬ)
rus_verbs:КАЗАТЬСЯ{}, // деревянный док казался очень твердым под моими ногами (КАЗАТЬСЯ)
rus_verbs:ПОСТАВИТЬ{}, // четвертый маг торопливо поставил под зеркалом широкую чашу (ПОСТАВИТЬ)
rus_verbs:ОСТАВАТЬСЯ{}, // запасы остаются под давлением (ОСТАВАТЬСЯ ПОД)
rus_verbs:ПЕТЬ{}, // просто мы под землей любим петь. (ПЕТЬ ПОД)
rus_verbs:ПОЯВИТЬСЯ{}, // под их крыльями внезапно появился дым. (ПОЯВИТЬСЯ ПОД)
rus_verbs:ОКАЗАТЬСЯ{}, // мы снова оказались под солнцем. (ОКАЗАТЬСЯ ПОД)
rus_verbs:ПОДХОДИТЬ{}, // мы подходили под другим углом? (ПОДХОДИТЬ ПОД)
rus_verbs:СКРЫВАТЬСЯ{}, // кто под ней скрывается? (СКРЫВАТЬСЯ ПОД)
rus_verbs:ХЛЮПАТЬ{}, // под ногами Аллы хлюпала грязь (ХЛЮПАТЬ ПОД)
rus_verbs:ШАГАТЬ{}, // их отряд весело шагал под дождем этой музыки. (ШАГАТЬ ПОД)
rus_verbs:ТЕЧЬ{}, // под ее поверхностью медленно текла ярость. (ТЕЧЬ ПОД твор)
rus_verbs:ОЧУТИТЬСЯ{}, // мы очутились под стенами замка. (ОЧУТИТЬСЯ ПОД)
rus_verbs:ПОБЛЕСКИВАТЬ{}, // их латы поблескивали под солнцем. (ПОБЛЕСКИВАТЬ ПОД)
rus_verbs:ДРАТЬСЯ{}, // под столами дрались за кости псы. (ДРАТЬСЯ ПОД)
rus_verbs:КАЧНУТЬСЯ{}, // палуба качнулась у нас под ногами. (КАЧНУЛАСЬ ПОД)
rus_verbs:ПРИСЕСТЬ{}, // конь даже присел под тяжелым телом. (ПРИСЕСТЬ ПОД)
rus_verbs:ЖИТЬ{}, // они живут под землей. (ЖИТЬ ПОД)
rus_verbs:ОБНАРУЖИТЬ{}, // вы можете обнаружить ее под водой? (ОБНАРУЖИТЬ ПОД)
rus_verbs:ПЛЫТЬ{}, // Орёл плывёт под облаками. (ПЛЫТЬ ПОД)
rus_verbs:ИСЧЕЗНУТЬ{}, // потом они исчезли под водой. (ИСЧЕЗНУТЬ ПОД)
rus_verbs:держать{}, // оружие все держали под рукой. (держать ПОД)
rus_verbs:ВСТРЕТИТЬСЯ{}, // они встретились под водой. (ВСТРЕТИТЬСЯ ПОД)
rus_verbs:уснуть{}, // Миша уснет под одеялом
rus_verbs:пошевелиться{}, // пошевелиться под одеялом
rus_verbs:задохнуться{}, // задохнуться под слоем снега
rus_verbs:потечь{}, // потечь под избыточным давлением
rus_verbs:уцелеть{}, // уцелеть под завалами
rus_verbs:мерцать{}, // мерцать под лучами софитов
rus_verbs:поискать{}, // поискать под кроватью
rus_verbs:гудеть{}, // гудеть под нагрузкой
rus_verbs:посидеть{}, // посидеть под навесом
rus_verbs:укрыться{}, // укрыться под навесом
rus_verbs:утихнуть{}, // утихнуть под одеялом
rus_verbs:заскрипеть{}, // заскрипеть под тяжестью
rus_verbs:шелохнуться{}, // шелохнуться под одеялом
инфинитив:срезать{ вид:несоверш }, глагол:срезать{ вид:несоверш }, // срезать под корень
деепричастие:срезав{}, прилагательное:срезающий{ вид:несоверш },
инфинитив:срезать{ вид:соверш }, глагол:срезать{ вид:соверш },
деепричастие:срезая{}, прилагательное:срезавший{ вид:соверш },
rus_verbs:пониматься{}, // пониматься под успехом
rus_verbs:подразумеваться{}, // подразумеваться под правильным решением
rus_verbs:промокнуть{}, // промокнуть под проливным дождем
rus_verbs:засосать{}, // засосать под ложечкой
rus_verbs:подписаться{}, // подписаться под воззванием
rus_verbs:укрываться{}, // укрываться под навесом
rus_verbs:запыхтеть{}, // запыхтеть под одеялом
rus_verbs:мокнуть{}, // мокнуть под лождем
rus_verbs:сгибаться{}, // сгибаться под тяжестью снега
rus_verbs:намокнуть{}, // намокнуть под дождем
rus_verbs:подписываться{}, // подписываться под обращением
rus_verbs:тарахтеть{}, // тарахтеть под окнами
инфинитив:находиться{вид:несоверш}, глагол:находиться{вид:несоверш}, // Она уже несколько лет находится под наблюдением врача.
деепричастие:находясь{}, прилагательное:находившийся{вид:несоверш}, прилагательное:находящийся{},
rus_verbs:лежать{}, // лежать под капельницей
rus_verbs:вымокать{}, // вымокать под дождём
rus_verbs:вымокнуть{}, // вымокнуть под дождём
rus_verbs:проворчать{}, // проворчать под нос
rus_verbs:хмыкнуть{}, // хмыкнуть под нос
rus_verbs:отыскать{}, // отыскать под кроватью
rus_verbs:дрогнуть{}, // дрогнуть под ударами
rus_verbs:проявляться{}, // проявляться под нагрузкой
rus_verbs:сдержать{}, // сдержать под контролем
rus_verbs:ложиться{}, // ложиться под клиента
rus_verbs:таять{}, // таять под весенним солнцем
rus_verbs:покатиться{}, // покатиться под откос
rus_verbs:лечь{}, // он лег под навесом
rus_verbs:идти{}, // идти под дождем
прилагательное:известный{}, // Он известен под этим именем.
rus_verbs:стоять{}, // Ящик стоит под столом.
rus_verbs:отступить{}, // Враг отступил под ударами наших войск.
rus_verbs:царапаться{}, // Мышь царапается под полом.
rus_verbs:спать{}, // заяц спокойно спал у себя под кустом
rus_verbs:загорать{}, // мы загораем под солнцем
ГЛ_ИНФ(мыть), // мыть руки под струёй воды
ГЛ_ИНФ(закопать),
ГЛ_ИНФ(спрятать),
ГЛ_ИНФ(прятать),
ГЛ_ИНФ(перепрятать)
}
fact гл_предл
{
if context { Гл_ПОД_твор предлог:под{} *:*{ падеж:твор } }
then return true
}
// для глаголов вне списка - запрещаем.
fact гл_предл
{
if context { * предлог:под{} *:*{ падеж:твор } }
then return false,-10
}
fact гл_предл
{
if context { * предлог:под{} *:*{} }
then return false,-11
}
#endregion Предлог_ПОД
*/
#region Предлог_ОБ
// -------------- ПРЕДЛОГ 'ОБ' -----------------------
wordentry_set Гл_ОБ_предл=
{
rus_verbs:СВИДЕТЕЛЬСТВОВАТЬ{}, // Об их присутствии свидетельствовало лишь тусклое пурпурное пятно, проступавшее на камне. (СВИДЕТЕЛЬСТВОВАТЬ)
rus_verbs:ЗАДУМАТЬСЯ{}, // Промышленные гиганты задумались об экологии (ЗАДУМАТЬСЯ)
rus_verbs:СПРОСИТЬ{}, // Он спросил нескольких из пляжников об их кажущейся всеобщей юности. (СПРОСИТЬ)
rus_verbs:спрашивать{}, // как ты можешь еще спрашивать у меня об этом?
rus_verbs:забывать{}, // Мы не можем забывать об их участи.
rus_verbs:ГАДАТЬ{}, // теперь об этом можно лишь гадать (ГАДАТЬ)
rus_verbs:ПОВЕДАТЬ{}, // Градоначальник , выступая с обзором основных городских событий , поведал об этом депутатам (ПОВЕДАТЬ ОБ)
rus_verbs:СООБЩИТЬ{}, // Иран сообщил МАГАТЭ об ускорении обогащения урана (СООБЩИТЬ)
rus_verbs:ЗАЯВИТЬ{}, // Об их успешном окончании заявил генеральный директор (ЗАЯВИТЬ ОБ)
rus_verbs:слышать{}, // даже они слышали об этом человеке. (СЛЫШАТЬ ОБ)
rus_verbs:ДОЛОЖИТЬ{}, // вернувшиеся разведчики доложили об увиденном (ДОЛОЖИТЬ ОБ)
rus_verbs:ПОГОВОРИТЬ{}, // давай поговорим об этом. (ПОГОВОРИТЬ ОБ)
rus_verbs:ДОГАДАТЬСЯ{}, // об остальном нетрудно догадаться. (ДОГАДАТЬСЯ ОБ)
rus_verbs:ПОЗАБОТИТЬСЯ{}, // обещал обо всем позаботиться. (ПОЗАБОТИТЬСЯ ОБ)
rus_verbs:ПОЗАБЫТЬ{}, // Шура позабыл обо всем. (ПОЗАБЫТЬ ОБ)
rus_verbs:вспоминать{}, // Впоследствии он не раз вспоминал об этом приключении. (вспоминать об)
rus_verbs:сообщать{}, // Газета сообщает об открытии сессии парламента. (сообщать об)
rus_verbs:просить{}, // мы просили об отсрочке платежей (просить ОБ)
rus_verbs:ПЕТЬ{}, // эта же девушка пела обо всем совершенно открыто. (ПЕТЬ ОБ)
rus_verbs:сказать{}, // ты скажешь об этом капитану? (сказать ОБ)
rus_verbs:знать{}, // бы хотелось знать как можно больше об этом районе.
rus_verbs:кричать{}, // Все газеты кричат об этом событии.
rus_verbs:советоваться{}, // Она обо всём советуется с матерью.
rus_verbs:говориться{}, // об остальном говорилось легко.
rus_verbs:подумать{}, // нужно крепко обо всем подумать.
rus_verbs:напомнить{}, // черный дым напомнил об опасности.
rus_verbs:забыть{}, // забудь об этой роскоши.
rus_verbs:думать{}, // приходится обо всем думать самой.
rus_verbs:отрапортовать{}, // отрапортовать об успехах
rus_verbs:информировать{}, // информировать об изменениях
rus_verbs:оповестить{}, // оповестить об отказе
rus_verbs:убиваться{}, // убиваться об стену
rus_verbs:расшибить{}, // расшибить об стену
rus_verbs:заговорить{}, // заговорить об оплате
rus_verbs:отозваться{}, // Он отозвался об этой книге с большой похвалой.
rus_verbs:попросить{}, // попросить об услуге
rus_verbs:объявить{}, // объявить об отставке
rus_verbs:предупредить{}, // предупредить об аварии
rus_verbs:предупреждать{}, // предупреждать об опасности
rus_verbs:твердить{}, // твердить об обязанностях
rus_verbs:заявлять{}, // заявлять об экспериментальном подтверждении
rus_verbs:рассуждать{}, // рассуждать об абстрактных идеях
rus_verbs:говорить{}, // Не говорите об этом в присутствии третьих лиц.
rus_verbs:читать{}, // он читал об этом в журнале
rus_verbs:прочитать{}, // он читал об этом в учебнике
rus_verbs:узнать{}, // он узнал об этом из фильмов
rus_verbs:рассказать{}, // рассказать об экзаменах
rus_verbs:рассказывать{},
rus_verbs:договориться{}, // договориться об оплате
rus_verbs:договариваться{}, // договариваться об обмене
rus_verbs:болтать{}, // Не болтай об этом!
rus_verbs:проболтаться{}, // Не проболтайся об этом!
rus_verbs:заботиться{}, // кто заботится об урегулировании
rus_verbs:беспокоиться{}, // вы беспокоитесь об обороне
rus_verbs:помнить{}, // всем советую об этом помнить
rus_verbs:мечтать{} // Мечтать об успехе
}
fact гл_предл
{
if context { Гл_ОБ_предл предлог:об{} *:*{ падеж:предл } }
then return true
}
fact гл_предл
{
if context { * предлог:о{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { * предлог:об{} @regex("[a-z]+[0-9]*") }
then return true
}
// остальные глаголы не могут связываться
fact гл_предл
{
if context { * предлог:об{} *:*{ падеж:предл } }
then return false, -4
}
wordentry_set Гл_ОБ_вин=
{
rus_verbs:СЛОМАТЬ{}, // потом об колено сломал (СЛОМАТЬ)
rus_verbs:разбить{}, // ты разбил щеку об угол ящика. (РАЗБИТЬ ОБ)
rus_verbs:опереться{}, // Он опёрся об стену.
rus_verbs:опираться{},
rus_verbs:постучать{}, // постучал лбом об пол.
rus_verbs:удариться{}, // бутылка глухо ударилась об землю.
rus_verbs:убиваться{}, // убиваться об стену
rus_verbs:расшибить{}, // расшибить об стену
rus_verbs:царапаться{} // Днище лодки царапалось обо что-то.
}
fact гл_предл
{
if context { Гл_ОБ_вин предлог:об{} *:*{ падеж:вин } }
then return true
}
fact гл_предл
{
if context { * предлог:об{} *:*{ падеж:вин } }
then return false,-4
}
fact гл_предл
{
if context { * предлог:об{} *:*{} }
then return false,-5
}
#endregion Предлог_ОБ
#region Предлог_О
// ------------------- С ПРЕДЛОГОМ 'О' ----------------------
wordentry_set Гл_О_Вин={
rus_verbs:шмякнуть{}, // Ей хотелось шмякнуть ими о стену.
rus_verbs:болтать{}, // Болтали чаще всего о пустяках.
rus_verbs:шваркнуть{}, // Она шваркнула трубкой о рычаг.
rus_verbs:опираться{}, // Мать приподнялась, с трудом опираясь о стол.
rus_verbs:бахнуться{}, // Бахнуться головой о стол.
rus_verbs:ВЫТЕРЕТЬ{}, // Вытащи нож и вытри его о траву. (ВЫТЕРЕТЬ/ВЫТИРАТЬ)
rus_verbs:ВЫТИРАТЬ{}, //
rus_verbs:РАЗБИТЬСЯ{}, // Прибой накатился и с шумом разбился о белый песок. (РАЗБИТЬСЯ)
rus_verbs:СТУКНУТЬ{}, // Сердце его глухо стукнуло о грудную кость (СТУКНУТЬ)
rus_verbs:ЛЯЗГНУТЬ{}, // Он кинулся наземь, покатился, и копье лязгнуло о стену. (ЛЯЗГНУТЬ/ЛЯЗГАТЬ)
rus_verbs:ЛЯЗГАТЬ{}, //
rus_verbs:звенеть{}, // стрелы уже звенели о прутья клетки
rus_verbs:ЩЕЛКНУТЬ{}, // камень щелкнул о скалу (ЩЕЛКНУТЬ)
rus_verbs:БИТЬ{}, // волна бьет о берег (БИТЬ)
rus_verbs:ЗАЗВЕНЕТЬ{}, // зазвенели мечи о щиты (ЗАЗВЕНЕТЬ)
rus_verbs:колотиться{}, // сердце его колотилось о ребра
rus_verbs:стучать{}, // глухо стучали о щиты рукояти мечей.
rus_verbs:биться{}, // биться головой о стену? (биться о)
rus_verbs:ударить{}, // вода ударила его о стену коридора. (ударила о)
rus_verbs:разбиваться{}, // волны разбивались о скалу
rus_verbs:разбивать{}, // Разбивает голову о прутья клетки.
rus_verbs:облокотиться{}, // облокотиться о стену
rus_verbs:точить{}, // точить о точильный камень
rus_verbs:спотыкаться{}, // спотыкаться о спрятавшийся в траве пень
rus_verbs:потереться{}, // потереться о дерево
rus_verbs:ушибиться{}, // ушибиться о дерево
rus_verbs:тереться{}, // тереться о ствол
rus_verbs:шмякнуться{}, // шмякнуться о землю
rus_verbs:убиваться{}, // убиваться об стену
rus_verbs:расшибить{}, // расшибить об стену
rus_verbs:тереть{}, // тереть о камень
rus_verbs:потереть{}, // потереть о колено
rus_verbs:удариться{}, // удариться о край
rus_verbs:споткнуться{}, // споткнуться о камень
rus_verbs:запнуться{}, // запнуться о камень
rus_verbs:запинаться{}, // запинаться о камни
rus_verbs:ударяться{}, // ударяться о бортик
rus_verbs:стукнуться{}, // стукнуться о бортик
rus_verbs:стукаться{}, // стукаться о бортик
rus_verbs:опереться{}, // Он опёрся локтями о стол.
rus_verbs:плескаться{} // Вода плещется о берег.
}
fact гл_предл
{
if context { Гл_О_Вин предлог:о{} *:*{ падеж:вин } }
then return true
}
fact гл_предл
{
if context { * предлог:о{} *:*{ падеж:вин } }
then return false,-5
}
wordentry_set Гл_О_предл={
rus_verbs:КРИЧАТЬ{}, // она кричала о смерти! (КРИЧАТЬ)
rus_verbs:РАССПРОСИТЬ{}, // Я расспросил о нем нескольких горожан. (РАССПРОСИТЬ/РАССПРАШИВАТЬ)
rus_verbs:РАССПРАШИВАТЬ{}, //
rus_verbs:слушать{}, // ты будешь слушать о них?
rus_verbs:вспоминать{}, // вспоминать о том разговоре ему было неприятно
rus_verbs:МОЛЧАТЬ{}, // О чём молчат девушки (МОЛЧАТЬ)
rus_verbs:ПЛАКАТЬ{}, // она плакала о себе (ПЛАКАТЬ)
rus_verbs:сложить{}, // о вас сложены легенды
rus_verbs:ВОЛНОВАТЬСЯ{}, // Я волнуюсь о том, что что-то серьёзно пошло не так (ВОЛНОВАТЬСЯ О)
rus_verbs:УПОМЯНУТЬ{}, // упомянул о намерении команды приобрести несколько новых футболистов (УПОМЯНУТЬ О)
rus_verbs:ОТЧИТЫВАТЬСЯ{}, // Судебные приставы продолжают отчитываться о борьбе с неплательщиками (ОТЧИТЫВАТЬСЯ О)
rus_verbs:ДОЛОЖИТЬ{}, // провести тщательное расследование взрыва в маршрутном такси во Владикавказе и доложить о результатах (ДОЛОЖИТЬ О)
rus_verbs:ПРОБОЛТАТЬ{}, // правительство страны больше проболтало о военной реформе (ПРОБОЛТАТЬ О)
rus_verbs:ЗАБОТИТЬСЯ{}, // Четверть россиян заботятся о здоровье путем просмотра телевизора (ЗАБОТИТЬСЯ О)
rus_verbs:ИРОНИЗИРОВАТЬ{}, // Вы иронизируете о ностальгии по тем временем (ИРОНИЗИРОВАТЬ О)
rus_verbs:СИГНАЛИЗИРОВАТЬ{}, // Кризис цен на продукты питания сигнализирует о неминуемой гиперинфляции (СИГНАЛИЗИРОВАТЬ О)
rus_verbs:СПРОСИТЬ{}, // Он спросил о моём здоровье. (СПРОСИТЬ О)
rus_verbs:НАПОМНИТЬ{}, // больной зуб опять напомнил о себе. (НАПОМНИТЬ О)
rus_verbs:осведомиться{}, // офицер осведомился о цели визита
rus_verbs:объявить{}, // В газете объявили о конкурсе. (объявить о)
rus_verbs:ПРЕДСТОЯТЬ{}, // о чем предстоит разговор? (ПРЕДСТОЯТЬ О)
rus_verbs:объявлять{}, // объявлять о всеобщей забастовке (объявлять о)
rus_verbs:зайти{}, // Разговор зашёл о политике.
rus_verbs:порассказать{}, // порассказать о своих путешествиях
инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть о неразделенной любви
деепричастие:спев{}, прилагательное:спевший{ вид:соверш },
прилагательное:спетый{},
rus_verbs:напеть{},
rus_verbs:разговаривать{}, // разговаривать с другом о жизни
rus_verbs:рассуждать{}, // рассуждать об абстрактных идеях
//rus_verbs:заботиться{}, // заботиться о престарелых родителях
rus_verbs:раздумывать{}, // раздумывать о новой работе
rus_verbs:договариваться{}, // договариваться о сумме компенсации
rus_verbs:молить{}, // молить о пощаде
rus_verbs:отзываться{}, // отзываться о книге
rus_verbs:подумывать{}, // подумывать о новом подходе
rus_verbs:поговаривать{}, // поговаривать о загадочном звере
rus_verbs:обмолвиться{}, // обмолвиться о проклятии
rus_verbs:условиться{}, // условиться о поддержке
rus_verbs:призадуматься{}, // призадуматься о последствиях
rus_verbs:известить{}, // известить о поступлении
rus_verbs:отрапортовать{}, // отрапортовать об успехах
rus_verbs:напевать{}, // напевать о любви
rus_verbs:помышлять{}, // помышлять о новом деле
rus_verbs:переговорить{}, // переговорить о правилах
rus_verbs:повествовать{}, // повествовать о событиях
rus_verbs:слыхивать{}, // слыхивать о чудище
rus_verbs:потолковать{}, // потолковать о планах
rus_verbs:проговориться{}, // проговориться о планах
rus_verbs:умолчать{}, // умолчать о штрафах
rus_verbs:хлопотать{}, // хлопотать о премии
rus_verbs:уведомить{}, // уведомить о поступлении
rus_verbs:горевать{}, // горевать о потере
rus_verbs:запамятовать{}, // запамятовать о важном мероприятии
rus_verbs:заикнуться{}, // заикнуться о прибавке
rus_verbs:информировать{}, // информировать о событиях
rus_verbs:проболтаться{}, // проболтаться о кладе
rus_verbs:поразмыслить{}, // поразмыслить о судьбе
rus_verbs:заикаться{}, // заикаться о деньгах
rus_verbs:оповестить{}, // оповестить об отказе
rus_verbs:печься{}, // печься о всеобщем благе
rus_verbs:разглагольствовать{}, // разглагольствовать о правах
rus_verbs:размечтаться{}, // размечтаться о будущем
rus_verbs:лепетать{}, // лепетать о невиновности
rus_verbs:грезить{}, // грезить о большой и чистой любви
rus_verbs:залепетать{}, // залепетать о сокровищах
rus_verbs:пронюхать{}, // пронюхать о бесплатной одежде
rus_verbs:протрубить{}, // протрубить о победе
rus_verbs:извещать{}, // извещать о поступлении
rus_verbs:трубить{}, // трубить о поимке разбойников
rus_verbs:осведомляться{}, // осведомляться о судьбе
rus_verbs:поразмышлять{}, // поразмышлять о неизбежном
rus_verbs:слагать{}, // слагать о подвигах викингов
rus_verbs:ходатайствовать{}, // ходатайствовать о выделении материальной помощи
rus_verbs:побеспокоиться{}, // побеспокоиться о правильном стимулировании
rus_verbs:закидывать{}, // закидывать сообщениями об ошибках
rus_verbs:базарить{}, // пацаны базарили о телках
rus_verbs:балагурить{}, // мужики балагурили о новом председателе
rus_verbs:балакать{}, // мужики балакали о новом председателе
rus_verbs:беспокоиться{}, // Она беспокоится о детях
rus_verbs:рассказать{}, // Кумир рассказал о криминале в Москве
rus_verbs:возмечтать{}, // возмечтать о счастливом мире
rus_verbs:вопить{}, // Кто-то вопил о несправедливости
rus_verbs:сказать{}, // сказать что-то новое о ком-то
rus_verbs:знать{}, // знать о ком-то что-то пикантное
rus_verbs:подумать{}, // подумать о чём-то
rus_verbs:думать{}, // думать о чём-то
rus_verbs:узнать{}, // узнать о происшествии
rus_verbs:помнить{}, // помнить о задании
rus_verbs:просить{}, // просить о коде доступа
rus_verbs:забыть{}, // забыть о своих обязанностях
rus_verbs:сообщить{}, // сообщить о заложенной мине
rus_verbs:заявить{}, // заявить о пропаже
rus_verbs:задуматься{}, // задуматься о смерти
rus_verbs:спрашивать{}, // спрашивать о поступлении товара
rus_verbs:догадаться{}, // догадаться о причинах
rus_verbs:договориться{}, // договориться о собеседовании
rus_verbs:мечтать{}, // мечтать о сцене
rus_verbs:поговорить{}, // поговорить о наболевшем
rus_verbs:размышлять{}, // размышлять о насущном
rus_verbs:напоминать{}, // напоминать о себе
rus_verbs:пожалеть{}, // пожалеть о содеянном
rus_verbs:ныть{}, // ныть о прибавке
rus_verbs:сообщать{}, // сообщать о победе
rus_verbs:догадываться{}, // догадываться о первопричине
rus_verbs:поведать{}, // поведать о тайнах
rus_verbs:умолять{}, // умолять о пощаде
rus_verbs:сожалеть{}, // сожалеть о случившемся
rus_verbs:жалеть{}, // жалеть о случившемся
rus_verbs:забывать{}, // забывать о случившемся
rus_verbs:упоминать{}, // упоминать о предках
rus_verbs:позабыть{}, // позабыть о своем обещании
rus_verbs:запеть{}, // запеть о любви
rus_verbs:скорбеть{}, // скорбеть о усопшем
rus_verbs:задумываться{}, // задумываться о смене работы
rus_verbs:позаботиться{}, // позаботиться о престарелых родителях
rus_verbs:докладывать{}, // докладывать о планах строительства целлюлозно-бумажного комбината
rus_verbs:попросить{}, // попросить о замене
rus_verbs:предупредить{}, // предупредить о замене
rus_verbs:предупреждать{}, // предупреждать о замене
rus_verbs:твердить{}, // твердить о замене
rus_verbs:заявлять{}, // заявлять о подлоге
rus_verbs:петь{}, // певица, поющая о лете
rus_verbs:проинформировать{}, // проинформировать о переговорах
rus_verbs:порассказывать{}, // порассказывать о событиях
rus_verbs:послушать{}, // послушать о новинках
rus_verbs:заговорить{}, // заговорить о плате
rus_verbs:отозваться{}, // Он отозвался о книге с большой похвалой.
rus_verbs:оставить{}, // Он оставил о себе печальную память.
rus_verbs:свидетельствовать{}, // страшно исхудавшее тело свидетельствовало о долгих лишениях
rus_verbs:спорить{}, // они спорили о законе
глагол:написать{ aux stress="напис^ать" }, инфинитив:написать{ aux stress="напис^ать" }, // Он написал о том, что видел во время путешествия.
глагол:писать{ aux stress="пис^ать" }, инфинитив:писать{ aux stress="пис^ать" }, // Он писал о том, что видел во время путешествия.
rus_verbs:прочитать{}, // Я прочитал о тебе
rus_verbs:услышать{}, // Я услышал о нем
rus_verbs:помечтать{}, // Девочки помечтали о принце
rus_verbs:слышать{}, // Мальчик слышал о приведениях
rus_verbs:вспомнить{}, // Девочки вспомнили о завтраке
rus_verbs:грустить{}, // Я грущу о тебе
rus_verbs:осведомить{}, // о последних достижениях науки
rus_verbs:рассказывать{}, // Антонио рассказывает о работе
rus_verbs:говорить{}, // говорим о трех больших псах
rus_verbs:идти{} // Вопрос идёт о войне.
}
fact гл_предл
{
if context { Гл_О_предл предлог:о{} *:*{ падеж:предл } }
then return true
}
// Мы поделились впечатлениями о выставке.
// ^^^^^^^^^^ ^^^^^^^^^^
fact гл_предл
{
if context { * предлог:о{} *:*{ падеж:предл } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:о{} *:*{} }
then return false,-5
}
#endregion Предлог_О
#region Предлог_ПО
// ------------------- С ПРЕДЛОГОМ 'ПО' ----------------------
// для этих глаголов - запрещаем связывание с ПО+дат.п.
wordentry_set Глаг_ПО_Дат_Запр=
{
rus_verbs:предпринять{}, // предпринять шаги по стимулированию продаж
rus_verbs:увлечь{}, // увлечь в прогулку по парку
rus_verbs:закончить{},
rus_verbs:мочь{},
rus_verbs:хотеть{}
}
fact гл_предл
{
if context { Глаг_ПО_Дат_Запр предлог:по{} *:*{ падеж:дат } }
then return false,-10
}
// По умолчанию разрешаем связывание в паттернах типа
// Я иду по шоссе
fact гл_предл
{
if context { * предлог:по{} *:*{ падеж:дат } }
then return true
}
wordentry_set Глаг_ПО_Вин=
{
rus_verbs:ВОЙТИ{}, // лезвие вошло по рукоять (ВОЙТИ)
rus_verbs:иметь{}, // все месяцы имели по тридцать дней. (ИМЕТЬ ПО)
rus_verbs:материализоваться{}, // материализоваться по другую сторону барьера
rus_verbs:засадить{}, // засадить по рукоятку
rus_verbs:увязнуть{} // увязнуть по колено
}
fact гл_предл
{
if context { Глаг_ПО_Вин предлог:по{} *:*{ падеж:вин } }
then return true
}
// для остальных падежей запрещаем.
fact гл_предл
{
if context { * предлог:по{} *:*{ падеж:вин } }
then return false,-5
}
#endregion Предлог_ПО
#region Предлог_К
// ------------------- С ПРЕДЛОГОМ 'К' ----------------------
wordentry_set Гл_К_Дат={
rus_verbs:заявиться{}, // Сразу же после обеда к нам заявилась Юлия Михайловна.
rus_verbs:приставлять{} , // Приставляет дуло пистолета к виску.
прилагательное:НЕПРИГОДНЫЙ{}, // большинство компьютеров из этой партии оказались непригодными к эксплуатации (НЕПРИГОДНЫЙ)
rus_verbs:СБЕГАТЬСЯ{}, // Они чуяли воду и сбегались к ней отовсюду. (СБЕГАТЬСЯ)
rus_verbs:СБЕЖАТЬСЯ{}, // К бетонной скамье начали сбегаться люди. (СБЕГАТЬСЯ/СБЕЖАТЬСЯ)
rus_verbs:ПРИТИРАТЬСЯ{}, // Менее стойких водителей буквально сметало на другую полосу, и они впритык притирались к другим машинам. (ПРИТИРАТЬСЯ)
rus_verbs:РУХНУТЬ{}, // а потом ты без чувств рухнул к моим ногам (РУХНУТЬ)
rus_verbs:ПЕРЕНЕСТИ{}, // Они перенесли мясо к ручью и поджарили его на костре. (ПЕРЕНЕСТИ)
rus_verbs:ЗАВЕСТИ{}, // как путь мой завел меня к нему? (ЗАВЕСТИ)
rus_verbs:НАГРЯНУТЬ{}, // ФБР нагрянуло с обыском к сестре бостонских террористов (НАГРЯНУТЬ)
rus_verbs:ПРИСЛОНЯТЬСЯ{}, // Рабы ложились на пол, прислонялись к стене и спали. (ПРИСЛОНЯТЬСЯ,ПРИНОРАВЛИВАТЬСЯ,ПРИНОРОВИТЬСЯ)
rus_verbs:ПРИНОРАВЛИВАТЬСЯ{}, //
rus_verbs:ПРИНОРОВИТЬСЯ{}, //
rus_verbs:СПЛАНИРОВАТЬ{}, // Вскоре она остановила свое падение и спланировала к ним. (СПЛАНИРОВАТЬ,СПИКИРОВАТЬ,РУХНУТЬ)
rus_verbs:СПИКИРОВАТЬ{}, //
rus_verbs:ЗАБРАТЬСЯ{}, // Поэтому он забрался ко мне в квартиру с имевшимся у него полумесяцем. (ЗАБРАТЬСЯ К, В, С)
rus_verbs:ПРОТЯГИВАТЬ{}, // Оно протягивало свои длинные руки к молодому человеку, стоявшему на плоской вершине валуна. (ПРОТЯГИВАТЬ/ПРОТЯНУТЬ/ТЯНУТЬ)
rus_verbs:ПРОТЯНУТЬ{}, //
rus_verbs:ТЯНУТЬ{}, //
rus_verbs:ПЕРЕБИРАТЬСЯ{}, // Ее губы медленно перебирались к его уху. (ПЕРЕБИРАТЬСЯ,ПЕРЕБРАТЬСЯ,ПЕРЕБАЗИРОВАТЬСЯ,ПЕРЕМЕСТИТЬСЯ,ПЕРЕМЕЩАТЬСЯ)
rus_verbs:ПЕРЕБРАТЬСЯ{}, // ,,,
rus_verbs:ПЕРЕБАЗИРОВАТЬСЯ{}, //
rus_verbs:ПЕРЕМЕСТИТЬСЯ{}, //
rus_verbs:ПЕРЕМЕЩАТЬСЯ{}, //
rus_verbs:ТРОНУТЬСЯ{}, // Он отвернулся от нее и тронулся к пляжу. (ТРОНУТЬСЯ)
rus_verbs:ПРИСТАВИТЬ{}, // Он поднял одну из них и приставил верхний конец к краю шахты в потолке.
rus_verbs:ПРОБИТЬСЯ{}, // Отряд с невероятными приключениями, пытается пробиться к своему полку, попадает в плен и другие передряги (ПРОБИТЬСЯ)
rus_verbs:хотеть{},
rus_verbs:СДЕЛАТЬ{}, // Сделайте всё к понедельнику (СДЕЛАТЬ)
rus_verbs:ИСПЫТЫВАТЬ{}, // она испытывает ко мне только отвращение (ИСПЫТЫВАТЬ)
rus_verbs:ОБЯЗЫВАТЬ{}, // Это меня ни к чему не обязывает (ОБЯЗЫВАТЬ)
rus_verbs:КАРАБКАТЬСЯ{}, // карабкаться по горе от подножия к вершине (КАРАБКАТЬСЯ)
rus_verbs:СТОЯТЬ{}, // мужчина стоял ко мне спиной (СТОЯТЬ)
rus_verbs:ПОДАТЬСЯ{}, // наконец люк подался ко мне (ПОДАТЬСЯ)
rus_verbs:ПРИРАВНЯТЬ{}, // Усилия нельзя приравнять к результату (ПРИРАВНЯТЬ)
rus_verbs:ПРИРАВНИВАТЬ{}, // Усилия нельзя приравнивать к результату (ПРИРАВНИВАТЬ)
rus_verbs:ВОЗЛОЖИТЬ{}, // Путин в Пскове возложил цветы к памятнику воинам-десантникам, погибшим в Чечне (ВОЗЛОЖИТЬ)
rus_verbs:запустить{}, // Индия запустит к Марсу свой космический аппарат в 2013 г
rus_verbs:ПРИСТЫКОВАТЬСЯ{}, // Роботизированный российский грузовой космический корабль пристыковался к МКС (ПРИСТЫКОВАТЬСЯ)
rus_verbs:ПРИМАЗАТЬСЯ{}, // К челябинскому метеориту примазалась таинственная слизь (ПРИМАЗАТЬСЯ)
rus_verbs:ПОПРОСИТЬ{}, // Попросите Лизу к телефону (ПОПРОСИТЬ К)
rus_verbs:ПРОЕХАТЬ{}, // Порой школьные автобусы просто не имеют возможности проехать к некоторым населенным пунктам из-за бездорожья (ПРОЕХАТЬ К)
rus_verbs:ПОДЦЕПЛЯТЬСЯ{}, // Вагоны с пассажирами подцепляются к составу (ПОДЦЕПЛЯТЬСЯ К)
rus_verbs:ПРИЗВАТЬ{}, // Президент Афганистана призвал талибов к прямому диалогу (ПРИЗВАТЬ К)
rus_verbs:ПРЕОБРАЗИТЬСЯ{}, // Культовый столичный отель преобразился к юбилею (ПРЕОБРАЗИТЬСЯ К)
прилагательное:ЧУВСТВИТЕЛЬНЫЙ{}, // нейроны одного комплекса чувствительны к разным веществам (ЧУВСТВИТЕЛЬНЫЙ К)
безлич_глагол:нужно{}, // нам нужно к воротам (НУЖНО К)
rus_verbs:БРОСИТЬ{}, // огромный клюв бросил это мясо к моим ногам (БРОСИТЬ К)
rus_verbs:ЗАКОНЧИТЬ{}, // к пяти утра техники закончили (ЗАКОНЧИТЬ К)
rus_verbs:НЕСТИ{}, // к берегу нас несет! (НЕСТИ К)
rus_verbs:ПРОДВИГАТЬСЯ{}, // племена медленно продвигались к востоку (ПРОДВИГАТЬСЯ К)
rus_verbs:ОПУСКАТЬСЯ{}, // деревья опускались к самой воде (ОПУСКАТЬСЯ К)
rus_verbs:СТЕМНЕТЬ{}, // к тому времени стемнело (СТЕМНЕЛО К)
rus_verbs:ОТСКОЧИТЬ{}, // после отскочил к окну (ОТСКОЧИТЬ К)
rus_verbs:ДЕРЖАТЬСЯ{}, // к солнцу держались спинами (ДЕРЖАТЬСЯ К)
rus_verbs:КАЧНУТЬСЯ{}, // толпа качнулась к ступеням (КАЧНУТЬСЯ К)
rus_verbs:ВОЙТИ{}, // Андрей вошел к себе (ВОЙТИ К)
rus_verbs:ВЫБРАТЬСЯ{}, // мы выбрались к окну (ВЫБРАТЬСЯ К)
rus_verbs:ПРОВЕСТИ{}, // провел к стене спальни (ПРОВЕСТИ К)
rus_verbs:ВЕРНУТЬСЯ{}, // давай вернемся к делу (ВЕРНУТЬСЯ К)
rus_verbs:ВОЗВРАТИТЬСЯ{}, // Среди евреев, живших в диаспоре, всегда было распространено сильное стремление возвратиться к Сиону (ВОЗВРАТИТЬСЯ К)
rus_verbs:ПРИЛЕГАТЬ{}, // Задняя поверхность хрусталика прилегает к стекловидному телу (ПРИЛЕГАТЬ К)
rus_verbs:ПЕРЕНЕСТИСЬ{}, // мысленно Алёна перенеслась к заливу (ПЕРЕНЕСТИСЬ К)
rus_verbs:ПРОБИВАТЬСЯ{}, // сквозь болото к берегу пробивался ручей. (ПРОБИВАТЬСЯ К)
rus_verbs:ПЕРЕВЕСТИ{}, // необходимо срочно перевести стадо к воде. (ПЕРЕВЕСТИ К)
rus_verbs:ПРИЛЕТЕТЬ{}, // зачем ты прилетел к нам? (ПРИЛЕТЕТЬ К)
rus_verbs:ДОБАВИТЬ{}, // добавить ли ее к остальным? (ДОБАВИТЬ К)
rus_verbs:ПРИГОТОВИТЬ{}, // Матвей приготовил лук к бою. (ПРИГОТОВИТЬ К)
rus_verbs:РВАНУТЬ{}, // человек рванул ее к себе. (РВАНУТЬ К)
rus_verbs:ТАЩИТЬ{}, // они тащили меня к двери. (ТАЩИТЬ К)
глагол:быть{}, // к тебе есть вопросы.
прилагательное:равнодушный{}, // Он равнодушен к музыке.
rus_verbs:ПОЖАЛОВАТЬ{}, // скандально известный певец пожаловал к нам на передачу (ПОЖАЛОВАТЬ К)
rus_verbs:ПЕРЕСЕСТЬ{}, // Ольга пересела к Антону (ПЕРЕСЕСТЬ К)
инфинитив:СБЕГАТЬ{ вид:соверш }, глагол:СБЕГАТЬ{ вид:соверш }, // сбегай к Борису (СБЕГАТЬ К)
rus_verbs:ПЕРЕХОДИТЬ{}, // право хода переходит к Адаму (ПЕРЕХОДИТЬ К)
rus_verbs:прижаться{}, // она прижалась щекой к его шее. (прижаться+к)
rus_verbs:ПОДСКОЧИТЬ{}, // солдат быстро подскочил ко мне. (ПОДСКОЧИТЬ К)
rus_verbs:ПРОБРАТЬСЯ{}, // нужно пробраться к реке. (ПРОБРАТЬСЯ К)
rus_verbs:ГОТОВИТЬ{}, // нас готовили к этому. (ГОТОВИТЬ К)
rus_verbs:ТЕЧЬ{}, // река текла к морю. (ТЕЧЬ К)
rus_verbs:ОТШАТНУТЬСЯ{}, // епископ отшатнулся к стене. (ОТШАТНУТЬСЯ К)
rus_verbs:БРАТЬ{}, // брали бы к себе. (БРАТЬ К)
rus_verbs:СКОЛЬЗНУТЬ{}, // ковер скользнул к пещере. (СКОЛЬЗНУТЬ К)
rus_verbs:присохнуть{}, // Грязь присохла к одежде. (присохнуть к)
rus_verbs:просить{}, // Директор просит вас к себе. (просить к)
rus_verbs:вызывать{}, // шеф вызывал к себе. (вызывать к)
rus_verbs:присесть{}, // старик присел к огню. (присесть к)
rus_verbs:НАКЛОНИТЬСЯ{}, // Ричард наклонился к брату. (НАКЛОНИТЬСЯ К)
rus_verbs:выбираться{}, // будем выбираться к дороге. (выбираться к)
rus_verbs:отвернуться{}, // Виктор отвернулся к стене. (отвернуться к)
rus_verbs:СТИХНУТЬ{}, // огонь стих к полудню. (СТИХНУТЬ К)
rus_verbs:УПАСТЬ{}, // нож упал к ногам. (УПАСТЬ К)
rus_verbs:СЕСТЬ{}, // молча сел к огню. (СЕСТЬ К)
rus_verbs:ХЛЫНУТЬ{}, // народ хлынул к стенам. (ХЛЫНУТЬ К)
rus_verbs:покатиться{}, // они черной волной покатились ко мне. (покатиться к)
rus_verbs:ОБРАТИТЬ{}, // она обратила к нему свое бледное лицо. (ОБРАТИТЬ К)
rus_verbs:СКЛОНИТЬ{}, // Джон слегка склонил голову к плечу. (СКЛОНИТЬ К)
rus_verbs:СВЕРНУТЬ{}, // дорожка резко свернула к южной стене. (СВЕРНУТЬ К)
rus_verbs:ЗАВЕРНУТЬ{}, // Он завернул к нам по пути к месту службы. (ЗАВЕРНУТЬ К)
rus_verbs:подходить{}, // цвет подходил ей к лицу.
rus_verbs:БРЕСТИ{}, // Ричард покорно брел к отцу. (БРЕСТИ К)
rus_verbs:ПОПАСТЬ{}, // хочешь попасть к нему? (ПОПАСТЬ К)
rus_verbs:ПОДНЯТЬ{}, // Мартин поднял ружье к плечу. (ПОДНЯТЬ К)
rus_verbs:ПОТЕРЯТЬ{}, // просто потеряла к нему интерес. (ПОТЕРЯТЬ К)
rus_verbs:РАЗВЕРНУТЬСЯ{}, // они сразу развернулись ко мне. (РАЗВЕРНУТЬСЯ К)
rus_verbs:ПОВЕРНУТЬ{}, // мальчик повернул к ним голову. (ПОВЕРНУТЬ К)
rus_verbs:вызвать{}, // или вызвать к жизни? (вызвать к)
rus_verbs:ВЫХОДИТЬ{}, // их земли выходят к морю. (ВЫХОДИТЬ К)
rus_verbs:ЕХАТЬ{}, // мы долго ехали к вам. (ЕХАТЬ К)
rus_verbs:опуститься{}, // Алиса опустилась к самому дну. (опуститься к)
rus_verbs:подняться{}, // они молча поднялись к себе. (подняться к)
rus_verbs:ДВИНУТЬСЯ{}, // толстяк тяжело двинулся к ним. (ДВИНУТЬСЯ К)
rus_verbs:ПОПЯТИТЬСЯ{}, // ведьмак осторожно попятился к лошади. (ПОПЯТИТЬСЯ К)
rus_verbs:РИНУТЬСЯ{}, // мышелов ринулся к черной стене. (РИНУТЬСЯ К)
rus_verbs:ТОЛКНУТЬ{}, // к этому толкнул ее ты. (ТОЛКНУТЬ К)
rus_verbs:отпрыгнуть{}, // Вадим поспешно отпрыгнул к борту. (отпрыгнуть к)
rus_verbs:отступить{}, // мы поспешно отступили к стене. (отступить к)
rus_verbs:ЗАБРАТЬ{}, // мы забрали их к себе. (ЗАБРАТЬ к)
rus_verbs:ВЗЯТЬ{}, // потом возьму тебя к себе. (ВЗЯТЬ К)
rus_verbs:лежать{}, // наш путь лежал к ним. (лежать к)
rus_verbs:поползти{}, // ее рука поползла к оружию. (поползти к)
rus_verbs:требовать{}, // вас требует к себе император. (требовать к)
rus_verbs:поехать{}, // ты должен поехать к нему. (поехать к)
rus_verbs:тянуться{}, // мордой животное тянулось к земле. (тянуться к)
rus_verbs:ЖДАТЬ{}, // жди их завтра к утру. (ЖДАТЬ К)
rus_verbs:ПОЛЕТЕТЬ{}, // они стремительно полетели к земле. (ПОЛЕТЕТЬ К)
rus_verbs:подойти{}, // помоги мне подойти к столу. (подойти к)
rus_verbs:РАЗВЕРНУТЬ{}, // мужик развернул к нему коня. (РАЗВЕРНУТЬ К)
rus_verbs:ПРИВЕЗТИ{}, // нас привезли прямо к королю. (ПРИВЕЗТИ К)
rus_verbs:отпрянуть{}, // незнакомец отпрянул к стене. (отпрянуть к)
rus_verbs:побежать{}, // Cергей побежал к двери. (побежать к)
rus_verbs:отбросить{}, // сильный удар отбросил его к стене. (отбросить к)
rus_verbs:ВЫНУДИТЬ{}, // они вынудили меня к сотрудничеству (ВЫНУДИТЬ К)
rus_verbs:подтянуть{}, // он подтянул к себе стул и сел на него (подтянуть к)
rus_verbs:сойти{}, // по узкой тропинке путники сошли к реке. (сойти к)
rus_verbs:являться{}, // по ночам к нему являлись призраки. (являться к)
rus_verbs:ГНАТЬ{}, // ледяной ветер гнал их к югу. (ГНАТЬ К)
rus_verbs:ВЫВЕСТИ{}, // она вывела нас точно к месту. (ВЫВЕСТИ К)
rus_verbs:выехать{}, // почти сразу мы выехали к реке.
rus_verbs:пододвигаться{}, // пододвигайся к окну
rus_verbs:броситься{}, // большая часть защитников стен бросилась к воротам.
rus_verbs:представить{}, // Его представили к ордену.
rus_verbs:двигаться{}, // между тем чудище неторопливо двигалось к берегу.
rus_verbs:выскочить{}, // тем временем они выскочили к реке.
rus_verbs:выйти{}, // тем временем они вышли к лестнице.
rus_verbs:потянуть{}, // Мальчик схватил верёвку и потянул её к себе.
rus_verbs:приложить{}, // приложить к детали повышенное усилие
rus_verbs:пройти{}, // пройти к стойке регистрации (стойка регистрации - проверить проверку)
rus_verbs:отнестись{}, // отнестись к животным с сочуствием
rus_verbs:привязать{}, // привязать за лапу веревкой к колышку, воткнутому в землю
rus_verbs:прыгать{}, // прыгать к хозяину на стол
rus_verbs:приглашать{}, // приглашать к доктору
rus_verbs:рваться{}, // Чужие люди рвутся к власти
rus_verbs:понестись{}, // понестись к обрыву
rus_verbs:питать{}, // питать привязанность к алкоголю
rus_verbs:заехать{}, // Коля заехал к Оле
rus_verbs:переехать{}, // переехать к родителям
rus_verbs:ползти{}, // ползти к дороге
rus_verbs:сводиться{}, // сводиться к элементарному действию
rus_verbs:добавлять{}, // добавлять к общей сумме
rus_verbs:подбросить{}, // подбросить к потолку
rus_verbs:призывать{}, // призывать к спокойствию
rus_verbs:пробираться{}, // пробираться к партизанам
rus_verbs:отвезти{}, // отвезти к родителям
rus_verbs:применяться{}, // применяться к уравнению
rus_verbs:сходиться{}, // сходиться к точному решению
rus_verbs:допускать{}, // допускать к сдаче зачета
rus_verbs:свести{}, // свести к нулю
rus_verbs:придвинуть{}, // придвинуть к мальчику
rus_verbs:подготовить{}, // подготовить к печати
rus_verbs:подобраться{}, // подобраться к оленю
rus_verbs:заторопиться{}, // заторопиться к выходу
rus_verbs:пристать{}, // пристать к берегу
rus_verbs:поманить{}, // поманить к себе
rus_verbs:припасть{}, // припасть к алтарю
rus_verbs:притащить{}, // притащить к себе домой
rus_verbs:прижимать{}, // прижимать к груди
rus_verbs:подсесть{}, // подсесть к симпатичной девочке
rus_verbs:придвинуться{}, // придвинуться к окну
rus_verbs:отпускать{}, // отпускать к другу
rus_verbs:пригнуться{}, // пригнуться к земле
rus_verbs:пристроиться{}, // пристроиться к колонне
rus_verbs:сгрести{}, // сгрести к себе
rus_verbs:удрать{}, // удрать к цыганам
rus_verbs:прибавиться{}, // прибавиться к общей сумме
rus_verbs:присмотреться{}, // присмотреться к покупке
rus_verbs:подкатить{}, // подкатить к трюму
rus_verbs:клонить{}, // клонить ко сну
rus_verbs:проследовать{}, // проследовать к выходу
rus_verbs:пододвинуть{}, // пододвинуть к себе
rus_verbs:применять{}, // применять к сотрудникам
rus_verbs:прильнуть{}, // прильнуть к экранам
rus_verbs:подвинуть{}, // подвинуть к себе
rus_verbs:примчаться{}, // примчаться к папе
rus_verbs:подкрасться{}, // подкрасться к жертве
rus_verbs:привязаться{}, // привязаться к собаке
rus_verbs:забирать{}, // забирать к себе
rus_verbs:прорваться{}, // прорваться к кассе
rus_verbs:прикасаться{}, // прикасаться к коже
rus_verbs:уносить{}, // уносить к себе
rus_verbs:подтянуться{}, // подтянуться к месту
rus_verbs:привозить{}, // привозить к ветеринару
rus_verbs:подползти{}, // подползти к зайцу
rus_verbs:приблизить{}, // приблизить к глазам
rus_verbs:применить{}, // применить к уравнению простое преобразование
rus_verbs:приглядеться{}, // приглядеться к изображению
rus_verbs:приложиться{}, // приложиться к ручке
rus_verbs:приставать{}, // приставать к девчонкам
rus_verbs:запрещаться{}, // запрещаться к показу
rus_verbs:прибегать{}, // прибегать к насилию
rus_verbs:побудить{}, // побудить к действиям
rus_verbs:притягивать{}, // притягивать к себе
rus_verbs:пристроить{}, // пристроить к полезному делу
rus_verbs:приговорить{}, // приговорить к смерти
rus_verbs:склоняться{}, // склоняться к прекращению разработки
rus_verbs:подъезжать{}, // подъезжать к вокзалу
rus_verbs:привалиться{}, // привалиться к забору
rus_verbs:наклоняться{}, // наклоняться к щенку
rus_verbs:подоспеть{}, // подоспеть к обеду
rus_verbs:прилипнуть{}, // прилипнуть к окну
rus_verbs:приволочь{}, // приволочь к себе
rus_verbs:устремляться{}, // устремляться к вершине
rus_verbs:откатиться{}, // откатиться к исходным позициям
rus_verbs:побуждать{}, // побуждать к действиям
rus_verbs:прискакать{}, // прискакать к кормежке
rus_verbs:присматриваться{}, // присматриваться к новичку
rus_verbs:прижиматься{}, // прижиматься к борту
rus_verbs:жаться{}, // жаться к огню
rus_verbs:передвинуть{}, // передвинуть к окну
rus_verbs:допускаться{}, // допускаться к экзаменам
rus_verbs:прикрепить{}, // прикрепить к корпусу
rus_verbs:отправлять{}, // отправлять к специалистам
rus_verbs:перебежать{}, // перебежать к врагам
rus_verbs:притронуться{}, // притронуться к реликвии
rus_verbs:заспешить{}, // заспешить к семье
rus_verbs:ревновать{}, // ревновать к сопернице
rus_verbs:подступить{}, // подступить к горлу
rus_verbs:уводить{}, // уводить к ветеринару
rus_verbs:побросать{}, // побросать к ногам
rus_verbs:подаваться{}, // подаваться к ужину
rus_verbs:приписывать{}, // приписывать к достижениям
rus_verbs:относить{}, // относить к растениям
rus_verbs:принюхаться{}, // принюхаться к ароматам
rus_verbs:подтащить{}, // подтащить к себе
rus_verbs:прислонить{}, // прислонить к стене
rus_verbs:подплыть{}, // подплыть к бую
rus_verbs:опаздывать{}, // опаздывать к стилисту
rus_verbs:примкнуть{}, // примкнуть к деомнстрантам
rus_verbs:стекаться{}, // стекаются к стенам тюрьмы
rus_verbs:подготовиться{}, // подготовиться к марафону
rus_verbs:приглядываться{}, // приглядываться к новичку
rus_verbs:присоединяться{}, // присоединяться к сообществу
rus_verbs:клониться{}, // клониться ко сну
rus_verbs:привыкать{}, // привыкать к хорошему
rus_verbs:принудить{}, // принудить к миру
rus_verbs:уплыть{}, // уплыть к далекому берегу
rus_verbs:утащить{}, // утащить к детенышам
rus_verbs:приплыть{}, // приплыть к финишу
rus_verbs:подбегать{}, // подбегать к хозяину
rus_verbs:лишаться{}, // лишаться средств к существованию
rus_verbs:приступать{}, // приступать к операции
rus_verbs:пробуждать{}, // пробуждать лекцией интерес к математике
rus_verbs:подключить{}, // подключить к трубе
rus_verbs:подключиться{}, // подключиться к сети
rus_verbs:прилить{}, // прилить к лицу
rus_verbs:стучаться{}, // стучаться к соседям
rus_verbs:пристегнуть{}, // пристегнуть к креслу
rus_verbs:присоединить{}, // присоединить к сети
rus_verbs:отбежать{}, // отбежать к противоположной стене
rus_verbs:подвезти{}, // подвезти к набережной
rus_verbs:прибегнуть{}, // прибегнуть к хитрости
rus_verbs:приучить{}, // приучить к туалету
rus_verbs:подталкивать{}, // подталкивать к выходу
rus_verbs:прорываться{}, // прорываться к выходу
rus_verbs:увозить{}, // увозить к ветеринару
rus_verbs:засеменить{}, // засеменить к выходу
rus_verbs:крепиться{}, // крепиться к потолку
rus_verbs:прибрать{}, // прибрать к рукам
rus_verbs:пристраститься{}, // пристраститься к наркотикам
rus_verbs:поспеть{}, // поспеть к обеду
rus_verbs:привязывать{}, // привязывать к дереву
rus_verbs:прилагать{}, // прилагать к документам
rus_verbs:переправить{}, // переправить к дедушке
rus_verbs:подогнать{}, // подогнать к воротам
rus_verbs:тяготеть{}, // тяготеть к социализму
rus_verbs:подбираться{}, // подбираться к оленю
rus_verbs:подступать{}, // подступать к горлу
rus_verbs:примыкать{}, // примыкать к первому элементу
rus_verbs:приладить{}, // приладить к велосипеду
rus_verbs:подбрасывать{}, // подбрасывать к потолку
rus_verbs:перевозить{}, // перевозить к новому месту дислокации
rus_verbs:усаживаться{}, // усаживаться к окну
rus_verbs:приближать{}, // приближать к глазам
rus_verbs:попроситься{}, // попроситься к бабушке
rus_verbs:прибить{}, // прибить к доске
rus_verbs:перетащить{}, // перетащить к себе
rus_verbs:прицепить{}, // прицепить к паровозу
rus_verbs:прикладывать{}, // прикладывать к ране
rus_verbs:устареть{}, // устареть к началу войны
rus_verbs:причалить{}, // причалить к пристани
rus_verbs:приспособиться{}, // приспособиться к опозданиям
rus_verbs:принуждать{}, // принуждать к миру
rus_verbs:соваться{}, // соваться к директору
rus_verbs:протолкаться{}, // протолкаться к прилавку
rus_verbs:приковать{}, // приковать к батарее
rus_verbs:подкрадываться{}, // подкрадываться к суслику
rus_verbs:подсадить{}, // подсадить к арестонту
rus_verbs:прикатить{}, // прикатить к финишу
rus_verbs:протащить{}, // протащить к владыке
rus_verbs:сужаться{}, // сужаться к основанию
rus_verbs:присовокупить{}, // присовокупить к пожеланиям
rus_verbs:пригвоздить{}, // пригвоздить к доске
rus_verbs:отсылать{}, // отсылать к первоисточнику
rus_verbs:изготовиться{}, // изготовиться к прыжку
rus_verbs:прилагаться{}, // прилагаться к покупке
rus_verbs:прицепиться{}, // прицепиться к вагону
rus_verbs:примешиваться{}, // примешиваться к вину
rus_verbs:переселить{}, // переселить к старшекурсникам
rus_verbs:затрусить{}, // затрусить к выходе
rus_verbs:приспособить{}, // приспособить к обогреву
rus_verbs:примериться{}, // примериться к аппарату
rus_verbs:прибавляться{}, // прибавляться к пенсии
rus_verbs:подкатиться{}, // подкатиться к воротам
rus_verbs:стягивать{}, // стягивать к границе
rus_verbs:дописать{}, // дописать к роману
rus_verbs:подпустить{}, // подпустить к корове
rus_verbs:склонять{}, // склонять к сотрудничеству
rus_verbs:припечатать{}, // припечатать к стене
rus_verbs:охладеть{}, // охладеть к музыке
rus_verbs:пришить{}, // пришить к шинели
rus_verbs:принюхиваться{}, // принюхиваться к ветру
rus_verbs:подрулить{}, // подрулить к барышне
rus_verbs:наведаться{}, // наведаться к оракулу
rus_verbs:клеиться{}, // клеиться к конверту
rus_verbs:перетянуть{}, // перетянуть к себе
rus_verbs:переметнуться{}, // переметнуться к конкурентам
rus_verbs:липнуть{}, // липнуть к сокурсницам
rus_verbs:поковырять{}, // поковырять к выходу
rus_verbs:подпускать{}, // подпускать к пульту управления
rus_verbs:присосаться{}, // присосаться к источнику
rus_verbs:приклеить{}, // приклеить к стеклу
rus_verbs:подтягивать{}, // подтягивать к себе
rus_verbs:подкатывать{}, // подкатывать к даме
rus_verbs:притрагиваться{}, // притрагиваться к опухоли
rus_verbs:слетаться{}, // слетаться к водопою
rus_verbs:хаживать{}, // хаживать к батюшке
rus_verbs:привлекаться{}, // привлекаться к административной ответственности
rus_verbs:подзывать{}, // подзывать к себе
rus_verbs:прикладываться{}, // прикладываться к иконе
rus_verbs:подтягиваться{}, // подтягиваться к парламенту
rus_verbs:прилепить{}, // прилепить к стенке холодильника
rus_verbs:пододвинуться{}, // пододвинуться к экрану
rus_verbs:приползти{}, // приползти к дереву
rus_verbs:запаздывать{}, // запаздывать к обеду
rus_verbs:припереть{}, // припереть к стене
rus_verbs:нагибаться{}, // нагибаться к цветку
инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять к воротам
деепричастие:сгоняв{},
rus_verbs:поковылять{}, // поковылять к выходу
rus_verbs:привалить{}, // привалить к столбу
rus_verbs:отпроситься{}, // отпроситься к родителям
rus_verbs:приспосабливаться{}, // приспосабливаться к новым условиям
rus_verbs:прилипать{}, // прилипать к рукам
rus_verbs:подсоединить{}, // подсоединить к приборам
rus_verbs:приливать{}, // приливать к голове
rus_verbs:подселить{}, // подселить к другим новичкам
rus_verbs:прилепиться{}, // прилепиться к шкуре
rus_verbs:подлетать{}, // подлетать к пункту назначения
rus_verbs:пристегнуться{}, // пристегнуться к креслу ремнями
rus_verbs:прибиться{}, // прибиться к стае, улетающей на юг
rus_verbs:льнуть{}, // льнуть к заботливому хозяину
rus_verbs:привязываться{}, // привязываться к любящему хозяину
rus_verbs:приклеиться{}, // приклеиться к спине
rus_verbs:стягиваться{}, // стягиваться к сенату
rus_verbs:подготавливать{}, // подготавливать к выходу на арену
rus_verbs:приглашаться{}, // приглашаться к доктору
rus_verbs:причислять{}, // причислять к отличникам
rus_verbs:приколоть{}, // приколоть к лацкану
rus_verbs:наклонять{}, // наклонять к горизонту
rus_verbs:припадать{}, // припадать к первоисточнику
rus_verbs:приобщиться{}, // приобщиться к культурному наследию
rus_verbs:придираться{}, // придираться к мелким ошибкам
rus_verbs:приучать{}, // приучать к лотку
rus_verbs:промотать{}, // промотать к началу
rus_verbs:прихлынуть{}, // прихлынуть к голове
rus_verbs:пришвартоваться{}, // пришвартоваться к первому пирсу
rus_verbs:прикрутить{}, // прикрутить к велосипеду
rus_verbs:подплывать{}, // подплывать к лодке
rus_verbs:приравниваться{}, // приравниваться к побегу
rus_verbs:подстрекать{}, // подстрекать к вооруженной борьбе с оккупантами
rus_verbs:изготовляться{}, // изготовляться к прыжку из стратосферы
rus_verbs:приткнуться{}, // приткнуться к первой группе туристов
rus_verbs:приручить{}, // приручить котика к лотку
rus_verbs:приковывать{}, // приковывать к себе все внимание прессы
rus_verbs:приготовляться{}, // приготовляться к первому экзамену
rus_verbs:остыть{}, // Вода остынет к утру.
rus_verbs:приехать{}, // Он приедет к концу будущей недели.
rus_verbs:подсаживаться{},
rus_verbs:успевать{}, // успевать к стилисту
rus_verbs:привлекать{}, // привлекать к себе внимание
прилагательное:устойчивый{}, // переводить в устойчивую к перегреву форму
rus_verbs:прийтись{}, // прийтись ко двору
инфинитив:адаптировать{вид:несоверш}, // машина была адаптирована к условиям крайнего севера
инфинитив:адаптировать{вид:соверш},
глагол:адаптировать{вид:несоверш},
глагол:адаптировать{вид:соверш},
деепричастие:адаптировав{},
деепричастие:адаптируя{},
прилагательное:адаптирующий{},
прилагательное:адаптировавший{ вид:соверш },
//+прилагательное:адаптировавший{ вид:несоверш },
прилагательное:адаптированный{},
инфинитив:адаптироваться{вид:соверш}, // тело адаптировалось к условиям суровой зимы
инфинитив:адаптироваться{вид:несоверш},
глагол:адаптироваться{вид:соверш},
глагол:адаптироваться{вид:несоверш},
деепричастие:адаптировавшись{},
деепричастие:адаптируясь{},
прилагательное:адаптировавшийся{вид:соверш},
//+прилагательное:адаптировавшийся{вид:несоверш},
прилагательное:адаптирующийся{},
rus_verbs:апеллировать{}, // оратор апеллировал к патриотизму своих слушателей
rus_verbs:близиться{}, // Шторм близится к побережью
rus_verbs:доставить{}, // Эскиз ракеты, способной доставить корабль к Луне
rus_verbs:буксировать{}, // Буксир буксирует танкер к месту стоянки
rus_verbs:причислить{}, // Мы причислили его к числу экспертов
rus_verbs:вести{}, // Наша партия ведет народ к процветанию
rus_verbs:взывать{}, // Учителя взывают к совести хулигана
rus_verbs:воззвать{}, // воззвать соплеменников к оружию
rus_verbs:возревновать{}, // возревновать к поклонникам
rus_verbs:воспылать{}, // Коля воспылал к Оле страстной любовью
rus_verbs:восходить{}, // восходить к вершине
rus_verbs:восшествовать{}, // восшествовать к вершине
rus_verbs:успеть{}, // успеть к обеду
rus_verbs:повернуться{}, // повернуться к кому-то
rus_verbs:обратиться{}, // обратиться к охраннику
rus_verbs:звать{}, // звать к столу
rus_verbs:отправиться{}, // отправиться к парикмахеру
rus_verbs:обернуться{}, // обернуться к зовущему
rus_verbs:явиться{}, // явиться к следователю
rus_verbs:уехать{}, // уехать к родне
rus_verbs:прибыть{}, // прибыть к перекличке
rus_verbs:привыкнуть{}, // привыкнуть к голоду
rus_verbs:уходить{}, // уходить к цыганам
rus_verbs:привести{}, // привести к себе
rus_verbs:шагнуть{}, // шагнуть к славе
rus_verbs:относиться{}, // относиться к прежним периодам
rus_verbs:подослать{}, // подослать к врагам
rus_verbs:поспешить{}, // поспешить к обеду
rus_verbs:зайти{}, // зайти к подруге
rus_verbs:позвать{}, // позвать к себе
rus_verbs:потянуться{}, // потянуться к рычагам
rus_verbs:пускать{}, // пускать к себе
rus_verbs:отвести{}, // отвести к врачу
rus_verbs:приблизиться{}, // приблизиться к решению задачи
rus_verbs:прижать{}, // прижать к стене
rus_verbs:отправить{}, // отправить к доктору
rus_verbs:падать{}, // падать к многолетним минимумам
rus_verbs:полезть{}, // полезть к дерущимся
rus_verbs:лезть{}, // Ты сама ко мне лезла!
rus_verbs:направить{}, // направить к майору
rus_verbs:приводить{}, // приводить к дантисту
rus_verbs:кинуться{}, // кинуться к двери
rus_verbs:поднести{}, // поднести к глазам
rus_verbs:подниматься{}, // подниматься к себе
rus_verbs:прибавить{}, // прибавить к результату
rus_verbs:зашагать{}, // зашагать к выходу
rus_verbs:склониться{}, // склониться к земле
rus_verbs:стремиться{}, // стремиться к вершине
rus_verbs:лететь{}, // лететь к родственникам
rus_verbs:ездить{}, // ездить к любовнице
rus_verbs:приближаться{}, // приближаться к финише
rus_verbs:помчаться{}, // помчаться к стоматологу
rus_verbs:прислушаться{}, // прислушаться к происходящему
rus_verbs:изменить{}, // изменить к лучшему собственную жизнь
rus_verbs:проявить{}, // проявить к погибшим сострадание
rus_verbs:подбежать{}, // подбежать к упавшему
rus_verbs:терять{}, // терять к партнерам доверие
rus_verbs:пропустить{}, // пропустить к певцу
rus_verbs:подвести{}, // подвести к глазам
rus_verbs:меняться{}, // меняться к лучшему
rus_verbs:заходить{}, // заходить к другу
rus_verbs:рвануться{}, // рвануться к воде
rus_verbs:привлечь{}, // привлечь к себе внимание
rus_verbs:присоединиться{}, // присоединиться к сети
rus_verbs:приезжать{}, // приезжать к дедушке
rus_verbs:дернуться{}, // дернуться к борту
rus_verbs:подъехать{}, // подъехать к воротам
rus_verbs:готовиться{}, // готовиться к дождю
rus_verbs:убежать{}, // убежать к маме
rus_verbs:поднимать{}, // поднимать к источнику сигнала
rus_verbs:отослать{}, // отослать к руководителю
rus_verbs:приготовиться{}, // приготовиться к худшему
rus_verbs:приступить{}, // приступить к выполнению обязанностей
rus_verbs:метнуться{}, // метнуться к фонтану
rus_verbs:прислушиваться{}, // прислушиваться к голосу разума
rus_verbs:побрести{}, // побрести к выходу
rus_verbs:мчаться{}, // мчаться к успеху
rus_verbs:нестись{}, // нестись к обрыву
rus_verbs:попадать{}, // попадать к хорошему костоправу
rus_verbs:опоздать{}, // опоздать к психотерапевту
rus_verbs:посылать{}, // посылать к доктору
rus_verbs:поплыть{}, // поплыть к берегу
rus_verbs:подтолкнуть{}, // подтолкнуть к активной работе
rus_verbs:отнести{}, // отнести животное к ветеринару
rus_verbs:прислониться{}, // прислониться к стволу
rus_verbs:наклонить{}, // наклонить к миске с молоком
rus_verbs:прикоснуться{}, // прикоснуться к поверхности
rus_verbs:увезти{}, // увезти к бабушке
rus_verbs:заканчиваться{}, // заканчиваться к концу путешествия
rus_verbs:подозвать{}, // подозвать к себе
rus_verbs:улететь{}, // улететь к теплым берегам
rus_verbs:ложиться{}, // ложиться к мужу
rus_verbs:убираться{}, // убираться к чертовой бабушке
rus_verbs:класть{}, // класть к другим документам
rus_verbs:доставлять{}, // доставлять к подъезду
rus_verbs:поворачиваться{}, // поворачиваться к источнику шума
rus_verbs:заглядывать{}, // заглядывать к любовнице
rus_verbs:занести{}, // занести к заказчикам
rus_verbs:прибежать{}, // прибежать к папе
rus_verbs:притянуть{}, // притянуть к причалу
rus_verbs:переводить{}, // переводить в устойчивую к перегреву форму
rus_verbs:подать{}, // он подал лимузин к подъезду
rus_verbs:подавать{}, // она подавала соус к мясу
rus_verbs:приобщаться{}, // приобщаться к культуре
прилагательное:неспособный{}, // Наша дочка неспособна к учению.
прилагательное:неприспособленный{}, // Эти устройства неприспособлены к работе в жару
прилагательное:предназначенный{}, // Старый дом предназначен к сносу.
прилагательное:внимательный{}, // Она всегда внимательна к гостям.
прилагательное:назначенный{}, // Дело назначено к докладу.
прилагательное:разрешенный{}, // Эта книга разрешена к печати.
прилагательное:снисходительный{}, // Этот учитель снисходителен к ученикам.
прилагательное:готовый{}, // Я готов к экзаменам.
прилагательное:требовательный{}, // Он очень требователен к себе.
прилагательное:жадный{}, // Он жаден к деньгам.
прилагательное:глухой{}, // Он глух к моей просьбе.
прилагательное:добрый{}, // Он добр к детям.
rus_verbs:проявлять{}, // Он всегда проявлял живой интерес к нашим делам.
rus_verbs:плыть{}, // Пароход плыл к берегу.
rus_verbs:пойти{}, // я пошел к доктору
rus_verbs:придти{}, // придти к выводу
rus_verbs:заглянуть{}, // Я заглянул к вам мимоходом.
rus_verbs:принадлежать{}, // Это существо принадлежит к разряду растений.
rus_verbs:подготавливаться{}, // Ученики подготавливаются к экзаменам.
rus_verbs:спускаться{}, // Улица круто спускается к реке.
rus_verbs:спуститься{}, // Мы спустились к реке.
rus_verbs:пустить{}, // пускать ко дну
rus_verbs:приговаривать{}, // Мы приговариваем тебя к пожизненному веселью!
rus_verbs:отойти{}, // Дом отошёл к племяннику.
rus_verbs:отходить{}, // Коля отходил ко сну.
rus_verbs:приходить{}, // местные жители к нему приходили лечиться
rus_verbs:кидаться{}, // не кидайся к столу
rus_verbs:ходить{}, // Она простудилась и сегодня ходила к врачу.
rus_verbs:закончиться{}, // Собрание закончилось к вечеру.
rus_verbs:послать{}, // Они выбрали своих депутатов и послали их к заведующему.
rus_verbs:направиться{}, // Мы сошли на берег и направились к городу.
rus_verbs:направляться{},
rus_verbs:свестись{}, // Всё свелось к нулю.
rus_verbs:прислать{}, // Пришлите кого-нибудь к ней.
rus_verbs:присылать{}, // Он присылал к должнику своих головорезов
rus_verbs:подлететь{}, // Самолёт подлетел к лесу.
rus_verbs:возвращаться{}, // он возвращается к старой работе
глагол:находиться{ вид:несоверш }, инфинитив:находиться{ вид:несоверш }, деепричастие:находясь{},
прилагательное:находившийся{}, прилагательное:находящийся{}, // Япония находится к востоку от Китая.
rus_verbs:возвращать{}, // возвращать к жизни
rus_verbs:располагать{}, // Атмосфера располагает к работе.
rus_verbs:возвратить{}, // Колокольный звон возвратил меня к прошлому.
rus_verbs:поступить{}, // К нам поступила жалоба.
rus_verbs:поступать{}, // К нам поступают жалобы.
rus_verbs:прыгнуть{}, // Белка прыгнула к дереву
rus_verbs:торопиться{}, // пассажиры торопятся к выходу
rus_verbs:поторопиться{}, // поторопитесь к выходу
rus_verbs:вернуть{}, // вернуть к активной жизни
rus_verbs:припирать{}, // припирать к стенке
rus_verbs:проваливать{}, // Проваливай ко всем чертям!
rus_verbs:вбежать{}, // Коля вбежал ко мне
rus_verbs:вбегать{}, // Коля вбегал ко мне
глагол:забегать{ вид:несоверш }, // Коля забегал ко мне
rus_verbs:постучаться{}, // Коля постучался ко мне.
rus_verbs:повести{}, // Спросил я озорного Антонио и повел его к дому
rus_verbs:понести{}, // Мы понесли кота к ветеринару
rus_verbs:принести{}, // Я принес кота к ветеринару
rus_verbs:устремиться{}, // Мы устремились к ручью.
rus_verbs:подводить{}, // Учитель подводил детей к аквариуму
rus_verbs:следовать{}, // Я получил приказ следовать к месту нового назначения.
rus_verbs:пригласить{}, // Я пригласил к себе товарищей.
rus_verbs:собираться{}, // Я собираюсь к тебе в гости.
rus_verbs:собраться{}, // Маша собралась к дантисту
rus_verbs:сходить{}, // Я схожу к врачу.
rus_verbs:идти{}, // Маша уверенно шла к Пете
rus_verbs:измениться{}, // Основные индексы рынка акций РФ почти не изменились к закрытию.
rus_verbs:отыграть{}, // Российский рынок акций отыграл падение к закрытию.
rus_verbs:заканчивать{}, // Заканчивайте к обеду
rus_verbs:обращаться{}, // Обращайтесь ко мне в любое время
rus_verbs:окончить{}, //
rus_verbs:дозвониться{}, // Я не мог к вам дозвониться.
глагол:прийти{}, инфинитив:прийти{}, // Антонио пришел к Элеонор
rus_verbs:уйти{}, // Антонио ушел к Элеонор
rus_verbs:бежать{}, // Антонио бежит к Элеонор
rus_verbs:спешить{}, // Антонио спешит к Элеонор
rus_verbs:скакать{}, // Антонио скачет к Элеонор
rus_verbs:красться{}, // Антонио крадётся к Элеонор
rus_verbs:поскакать{}, // беглецы поскакали к холмам
rus_verbs:перейти{} // Антонио перешел к Элеонор
}
fact гл_предл
{
if context { Гл_К_Дат предлог:к{} *:*{ падеж:дат } }
then return true
}
fact гл_предл
{
if context { Гл_К_Дат предлог:к{} @regex("[a-z]+[0-9]*") }
then return true
}
// для остальных падежей запрещаем.
fact гл_предл
{
if context { * предлог:к{} *:*{} }
then return false,-5
}
#endregion Предлог_К
#region Предлог_ДЛЯ
// ------------------- С ПРЕДЛОГОМ 'ДЛЯ' ----------------------
wordentry_set Гл_ДЛЯ_Род={
частица:нет{}, // для меня нет других путей.
частица:нету{},
rus_verbs:ЗАДЕРЖАТЬ{}, // полиция может задержать их для выяснения всех обстоятельств и дальнейшего опознания. (ЗАДЕРЖАТЬ)
rus_verbs:ДЕЛАТЬСЯ{}, // это делалось для людей (ДЕЛАТЬСЯ)
rus_verbs:обернуться{}, // обернулась для греческого рынка труда банкротствами предприятий и масштабными сокращениями (обернуться)
rus_verbs:ПРЕДНАЗНАЧАТЬСЯ{}, // Скорее всего тяжелый клинок вообще не предназначался для бросков (ПРЕДНАЗНАЧАТЬСЯ)
rus_verbs:ПОЛУЧИТЬ{}, // ты можешь получить его для нас? (ПОЛУЧИТЬ)
rus_verbs:ПРИДУМАТЬ{}, // Ваш босс уже придумал для нас веселенькую смерть. (ПРИДУМАТЬ)
rus_verbs:оказаться{}, // это оказалось для них тяжелой задачей
rus_verbs:ГОВОРИТЬ{}, // теперь она говорила для нас обоих (ГОВОРИТЬ)
rus_verbs:ОСВОБОДИТЬ{}, // освободить ее для тебя? (ОСВОБОДИТЬ)
rus_verbs:работать{}, // Мы работаем для тех, кто ценит удобство
rus_verbs:СТАТЬ{}, // кем она станет для него? (СТАТЬ)
rus_verbs:ЯВИТЬСЯ{}, // вы для этого явились сюда? (ЯВИТЬСЯ)
rus_verbs:ПОТЕРЯТЬ{}, // жизнь потеряла для меня всякий смысл (ПОТЕРЯТЬ)
rus_verbs:УТРАТИТЬ{}, // мой мир утратил для меня всякое подобие смысла (УТРАТИТЬ)
rus_verbs:ДОСТАТЬ{}, // ты должен достать ее для меня! (ДОСТАТЬ)
rus_verbs:БРАТЬ{}, // некоторые берут для себя (БРАТЬ)
rus_verbs:ИМЕТЬ{}, // имею для вас новость (ИМЕТЬ)
rus_verbs:ЖДАТЬ{}, // тебя ждут для разговора (ЖДАТЬ)
rus_verbs:ПРОПАСТЬ{}, // совсем пропал для мира (ПРОПАСТЬ)
rus_verbs:ПОДНЯТЬ{}, // нас подняли для охоты (ПОДНЯТЬ)
rus_verbs:ОСТАНОВИТЬСЯ{}, // время остановилось для нее (ОСТАНОВИТЬСЯ)
rus_verbs:НАЧИНАТЬСЯ{}, // для него начинается новая жизнь (НАЧИНАТЬСЯ)
rus_verbs:КОНЧИТЬСЯ{}, // кончились для него эти игрушки (КОНЧИТЬСЯ)
rus_verbs:НАСТАТЬ{}, // для него настало время действовать (НАСТАТЬ)
rus_verbs:СТРОИТЬ{}, // для молодых строили новый дом (СТРОИТЬ)
rus_verbs:ВЗЯТЬ{}, // возьми для защиты этот меч (ВЗЯТЬ)
rus_verbs:ВЫЯСНИТЬ{}, // попытаюсь выяснить для вас всю цепочку (ВЫЯСНИТЬ)
rus_verbs:ПРИГОТОВИТЬ{}, // давай попробуем приготовить для них сюрприз (ПРИГОТОВИТЬ)
rus_verbs:ПОДХОДИТЬ{}, // берег моря мертвых подходил для этого идеально (ПОДХОДИТЬ)
rus_verbs:ОСТАТЬСЯ{}, // внешний вид этих тварей остался для нас загадкой (ОСТАТЬСЯ)
rus_verbs:ПРИВЕЗТИ{}, // для меня привезли пиво (ПРИВЕЗТИ)
прилагательное:ХАРАКТЕРНЫЙ{}, // Для всей территории края характерен умеренный континентальный климат (ХАРАКТЕРНЫЙ)
rus_verbs:ПРИВЕСТИ{}, // для меня белую лошадь привели (ПРИВЕСТИ ДЛЯ)
rus_verbs:ДЕРЖАТЬ{}, // их держат для суда (ДЕРЖАТЬ ДЛЯ)
rus_verbs:ПРЕДОСТАВИТЬ{}, // вьетнамец предоставил для мигрантов места проживания в ряде вологодских общежитий (ПРЕДОСТАВИТЬ ДЛЯ)
rus_verbs:ПРИДУМЫВАТЬ{}, // придумывая для этого разнообразные причины (ПРИДУМЫВАТЬ ДЛЯ)
rus_verbs:оставить{}, // или вообще решили оставить планету для себя
rus_verbs:оставлять{},
rus_verbs:ВОССТАНОВИТЬ{}, // как ты можешь восстановить это для меня? (ВОССТАНОВИТЬ ДЛЯ)
rus_verbs:ТАНЦЕВАТЬ{}, // а вы танцевали для меня танец семи покрывал (ТАНЦЕВАТЬ ДЛЯ)
rus_verbs:ДАТЬ{}, // твой принц дал мне это для тебя! (ДАТЬ ДЛЯ)
rus_verbs:ВОСПОЛЬЗОВАТЬСЯ{}, // мужчина из лагеря решил воспользоваться для передвижения рекой (ВОСПОЛЬЗОВАТЬСЯ ДЛЯ)
rus_verbs:СЛУЖИТЬ{}, // они служили для разговоров (СЛУЖИТЬ ДЛЯ)
rus_verbs:ИСПОЛЬЗОВАТЬСЯ{}, // Для вычисления радиуса поражения ядерных взрывов используется формула (ИСПОЛЬЗОВАТЬСЯ ДЛЯ)
rus_verbs:ПРИМЕНЯТЬСЯ{}, // Применяется для изготовления алкогольных коктейлей (ПРИМЕНЯТЬСЯ ДЛЯ)
rus_verbs:СОВЕРШАТЬСЯ{}, // Для этого совершался специальный магический обряд (СОВЕРШАТЬСЯ ДЛЯ)
rus_verbs:ПРИМЕНИТЬ{}, // а здесь попробуем применить ее для других целей. (ПРИМЕНИТЬ ДЛЯ)
rus_verbs:ПОЗВАТЬ{}, // ты позвал меня для настоящей работы. (ПОЗВАТЬ ДЛЯ)
rus_verbs:НАЧАТЬСЯ{}, // очередной денек начался для Любки неудачно (НАЧАТЬСЯ ДЛЯ)
rus_verbs:ПОСТАВИТЬ{}, // вас здесь для красоты поставили? (ПОСТАВИТЬ ДЛЯ)
rus_verbs:умереть{}, // или умерла для всяких чувств? (умереть для)
rus_verbs:ВЫБРАТЬ{}, // ты сам выбрал для себя этот путь. (ВЫБРАТЬ ДЛЯ)
rus_verbs:ОТМЕТИТЬ{}, // тот же отметил для себя другое. (ОТМЕТИТЬ ДЛЯ)
rus_verbs:УСТРОИТЬ{}, // мы хотим устроить для них школу. (УСТРОИТЬ ДЛЯ)
rus_verbs:БЫТЬ{}, // у меня есть для тебя работа. (БЫТЬ ДЛЯ)
rus_verbs:ВЫЙТИ{}, // для всего нашего поколения так вышло. (ВЫЙТИ ДЛЯ)
прилагательное:ВАЖНЫЙ{}, // именно твое мнение для нас крайне важно. (ВАЖНЫЙ ДЛЯ)
прилагательное:НУЖНЫЙ{}, // для любого племени нужна прежде всего сила. (НУЖЕН ДЛЯ)
прилагательное:ДОРОГОЙ{}, // эти места были дороги для них обоих. (ДОРОГОЙ ДЛЯ)
rus_verbs:НАСТУПИТЬ{}, // теперь для больших людей наступило время действий. (НАСТУПИТЬ ДЛЯ)
rus_verbs:ДАВАТЬ{}, // старый пень давал для этого хороший огонь. (ДАВАТЬ ДЛЯ)
rus_verbs:ГОДИТЬСЯ{}, // доброе старое время годится лишь для воспоминаний. (ГОДИТЬСЯ ДЛЯ)
rus_verbs:ТЕРЯТЬ{}, // время просто теряет для вас всякое значение. (ТЕРЯТЬ ДЛЯ)
rus_verbs:ЖЕНИТЬСЯ{}, // настало время жениться для пользы твоего клана. (ЖЕНИТЬСЯ ДЛЯ)
rus_verbs:СУЩЕСТВОВАТЬ{}, // весь мир перестал существовать для них обоих. (СУЩЕСТВОВАТЬ ДЛЯ)
rus_verbs:ЖИТЬ{}, // жить для себя или жить для них. (ЖИТЬ ДЛЯ)
rus_verbs:открыть{}, // двери моего дома всегда открыты для вас. (ОТКРЫТЫЙ ДЛЯ)
rus_verbs:закрыть{}, // этот мир будет закрыт для них. (ЗАКРЫТЫЙ ДЛЯ)
rus_verbs:ТРЕБОВАТЬСЯ{}, // для этого требуется огромное количество энергии. (ТРЕБОВАТЬСЯ ДЛЯ)
rus_verbs:РАЗОРВАТЬ{}, // Алексей разорвал для этого свою рубаху. (РАЗОРВАТЬ ДЛЯ)
rus_verbs:ПОДОЙТИ{}, // вполне подойдет для начала нашей экспедиции. (ПОДОЙТИ ДЛЯ)
прилагательное:опасный{}, // сильный холод опасен для открытой раны. (ОПАСЕН ДЛЯ)
rus_verbs:ПРИЙТИ{}, // для вас пришло очень важное сообщение. (ПРИЙТИ ДЛЯ)
rus_verbs:вывести{}, // мы специально вывели этих животных для мяса.
rus_verbs:убрать{}, // В вагонах метро для комфорта пассажиров уберут сиденья (УБРАТЬ В, ДЛЯ)
rus_verbs:оставаться{}, // механизм этого воздействия остается для меня загадкой. (остается для)
rus_verbs:ЯВЛЯТЬСЯ{}, // Чай является для китайцев обычным ежедневным напитком (ЯВЛЯТЬСЯ ДЛЯ)
rus_verbs:ПРИМЕНЯТЬ{}, // Для оценок будущих изменений климата применяют модели общей циркуляции атмосферы. (ПРИМЕНЯТЬ ДЛЯ)
rus_verbs:ПОВТОРЯТЬ{}, // повторяю для Пети (ПОВТОРЯТЬ ДЛЯ)
rus_verbs:УПОТРЕБЛЯТЬ{}, // Краски, употребляемые для живописи (УПОТРЕБЛЯТЬ ДЛЯ)
rus_verbs:ВВЕСТИ{}, // Для злостных нарушителей предложили ввести повышенные штрафы (ВВЕСТИ ДЛЯ)
rus_verbs:найтись{}, // у вас найдется для него работа?
rus_verbs:заниматься{}, // они занимаются этим для развлечения. (заниматься для)
rus_verbs:заехать{}, // Коля заехал для обсуждения проекта
rus_verbs:созреть{}, // созреть для побега
rus_verbs:наметить{}, // наметить для проверки
rus_verbs:уяснить{}, // уяснить для себя
rus_verbs:нанимать{}, // нанимать для разовой работы
rus_verbs:приспособить{}, // приспособить для удовольствия
rus_verbs:облюбовать{}, // облюбовать для посиделок
rus_verbs:прояснить{}, // прояснить для себя
rus_verbs:задействовать{}, // задействовать для патрулирования
rus_verbs:приготовлять{}, // приготовлять для проверки
инфинитив:использовать{ вид:соверш }, // использовать для достижения цели
инфинитив:использовать{ вид:несоверш },
глагол:использовать{ вид:соверш },
глагол:использовать{ вид:несоверш },
прилагательное:использованный{},
деепричастие:используя{},
деепричастие:использовав{},
rus_verbs:напрячься{}, // напрячься для решительного рывка
rus_verbs:одобрить{}, // одобрить для использования
rus_verbs:одобрять{}, // одобрять для использования
rus_verbs:пригодиться{}, // пригодиться для тестирования
rus_verbs:готовить{}, // готовить для выхода в свет
rus_verbs:отобрать{}, // отобрать для участия в конкурсе
rus_verbs:потребоваться{}, // потребоваться для подтверждения
rus_verbs:пояснить{}, // пояснить для слушателей
rus_verbs:пояснять{}, // пояснить для экзаменаторов
rus_verbs:понадобиться{}, // понадобиться для обоснования
инфинитив:адаптировать{вид:несоверш}, // машина была адаптирована для условий крайнего севера
инфинитив:адаптировать{вид:соверш},
глагол:адаптировать{вид:несоверш},
глагол:адаптировать{вид:соверш},
деепричастие:адаптировав{},
деепричастие:адаптируя{},
прилагательное:адаптирующий{},
прилагательное:адаптировавший{ вид:соверш },
//+прилагательное:адаптировавший{ вид:несоверш },
прилагательное:адаптированный{},
rus_verbs:найти{}, // Папа нашел для детей няню
прилагательное:вредный{}, // Это вредно для здоровья.
прилагательное:полезный{}, // Прогулки полезны для здоровья.
прилагательное:обязательный{}, // Этот пункт обязателен для исполнения
прилагательное:бесполезный{}, // Это лекарство бесполезно для него
прилагательное:необходимый{}, // Это лекарство необходимо для выздоровления
rus_verbs:создать{}, // Он не создан для этого дела.
прилагательное:сложный{}, // задача сложна для младших школьников
прилагательное:несложный{},
прилагательное:лёгкий{},
прилагательное:сложноватый{},
rus_verbs:становиться{},
rus_verbs:представлять{}, // Это не представляет для меня интереса.
rus_verbs:значить{}, // Я рос в деревне и хорошо знал, что для деревенской жизни значат пруд или речка
rus_verbs:пройти{}, // День прошёл спокойно для него.
rus_verbs:проходить{},
rus_verbs:высадиться{}, // большой злой пират и его отчаянные помощники высадились на необитаемом острове для поиска зарытых сокровищ
rus_verbs:высаживаться{},
rus_verbs:прибавлять{}, // Он любит прибавлять для красного словца.
rus_verbs:прибавить{},
rus_verbs:составить{}, // Ряд тригонометрических таблиц был составлен для астрономических расчётов.
rus_verbs:составлять{},
rus_verbs:стараться{}, // Я старался для вас
rus_verbs:постараться{}, // Я постарался для вас
rus_verbs:сохраниться{}, // Старик хорошо сохранился для своего возраста.
rus_verbs:собраться{}, // собраться для обсуждения
rus_verbs:собираться{}, // собираться для обсуждения
rus_verbs:уполномочивать{},
rus_verbs:уполномочить{}, // его уполномочили для ведения переговоров
rus_verbs:принести{}, // Я принёс эту книгу для вас.
rus_verbs:делать{}, // Я это делаю для удовольствия.
rus_verbs:сделать{}, // Я сделаю это для удовольствия.
rus_verbs:подготовить{}, // я подготовил для друзей сюрприз
rus_verbs:подготавливать{}, // я подготавливаю для гостей новый сюрприз
rus_verbs:закупить{}, // Руководство района обещало закупить новые комбайны для нашего села
rus_verbs:купить{}, // Руководство района обещало купить новые комбайны для нашего села
rus_verbs:прибыть{} // они прибыли для участия
}
fact гл_предл
{
if context { Гл_ДЛЯ_Род предлог:для{} *:*{ падеж:род } }
then return true
}
fact гл_предл
{
if context { Гл_ДЛЯ_Род предлог:для{} @regex("[a-z]+[0-9]*") }
then return true
}
// для остальных падежей запрещаем.
fact гл_предл
{
if context { * предлог:для{} *:*{} }
then return false,-4
}
#endregion Предлог_ДЛЯ
#region Предлог_ОТ
// попробуем иную стратегию - запретить связывание с ОТ для отдельных глаголов, разрешив для всех остальных.
wordentry_set Глаг_ОТ_Род_Запр=
{
rus_verbs:наслаждаться{}, // свободой от обязательств
rus_verbs:насладиться{},
rus_verbs:мочь{}, // Он не мог удержаться от смеха.
// rus_verbs:хотеть{},
rus_verbs:желать{},
rus_verbs:чувствовать{}, // все время от времени чувствуют его.
rus_verbs:планировать{},
rus_verbs:приняться{} // мы принялись обниматься от радости.
}
fact гл_предл
{
if context { Глаг_ОТ_Род_Запр предлог:от{} * }
then return false
}
#endregion Предлог_ОТ
#region Предлог_БЕЗ
/*
// запретить связывание с БЕЗ для отдельных глаголов, разрешив для всех остальных.
wordentry_set Глаг_БЕЗ_Род_Запр=
{
rus_verbs:мочь{}, // Он мог читать часами без отдыха.
rus_verbs:хотеть{},
rus_verbs:желать{},
rus_verbs:планировать{},
rus_verbs:приняться{}
}
fact гл_предл
{
if context { Глаг_БЕЗ_Род_Запр предлог:без{} * }
then return false
}
*/
#endregion Предлог_БЕЗ
#region Предлог_КРОМЕ
fact гл_предл
{
if context { * ПредлогДляВсе * }
then return false,-5
}
#endregion Предлог_КРОМЕ
// ------------------------------------
// По умолчанию разрешаем все остальные сочетания.
fact гл_предл
{
if context { * * * }
then return true
}
| подслушивать в классе
| rus_verbs:подслушивать{}, | 5,481,670 | [
1,
145,
128,
145,
127,
145,
117,
146,
228,
145,
124,
146,
230,
146,
235,
145,
121,
145,
115,
145,
113,
146,
229,
146,
239,
225,
145,
115,
225,
145,
123,
145,
124,
145,
113,
146,
228,
146,
228,
145,
118,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
436,
407,
67,
502,
2038,
30,
145,
128,
145,
127,
145,
117,
146,
228,
145,
124,
146,
230,
146,
235,
145,
121,
145,
115,
145,
113,
146,
229,
146,
239,
2916,
16,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
require(c >= a, "add: +");
return c;
}
/**
* @dev Returns the addition of two unsigned integers, reverting with custom message on overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot underflow.
*/
function sub(uint a, uint b) internal pure returns (uint) {
return sub(a, b, "sub: -");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot underflow.
*/
function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
require(b <= a, errorMessage);
uint 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(uint a, uint b) internal pure returns (uint) {
// 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;
}
uint c = a * b;
require(c / a == b, "mul: *");
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
// 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;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
/**
* @dev Returns the integer division of two unsigned integers.
* Reverts on division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint a, uint b) internal pure returns (uint) {
return div(a, b, "div: /");
}
/**
* @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(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
// 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(uint a, uint b) internal pure returns (uint) {
return mod(a, b, "mod: %");
}
/**
* @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(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
require(b != 0, errorMessage);
return a % b;
}
}
interface IChainLinkFeed {
function latestAnswer() external view returns (int256);
}
interface IUniswapV2Oracle {
function consult(address tokenIn, uint amountIn, address tokenOut) external view returns (uint amountOut);
}
contract Keep3rV1Helper {
using SafeMath for uint;
IChainLinkFeed public constant FASTGAS = IChainLinkFeed(0x169E633A2D1E6c10dD91238Ba11c4A708dfEF37C);
IUniswapV2Oracle public constant UNIQUOTE = IUniswapV2Oracle(0x127a2975c4E1c75f1ed4757a861bbd42523DB035);
address constant WETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
address constant KP3R = address(0x1cEB5cB57C4D4E2b2433641b95Dd330A33185A44);
function quote(uint spent) public view returns (uint) {
return UNIQUOTE.consult(WETH, spent, KP3R);
}
function quoteGas(uint gasUsed) external view returns (uint) {
return gasUsed.mul(uint(FASTGAS.latestAnswer()));
}
function getQuoteLimit(uint gasUsed) external view returns (uint) {
return quote(gasUsed.mul(uint(FASTGAS.latestAnswer())));
}
} | * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). Counterpart to Solidity's `-` operator. Requirements: - Subtraction cannot underflow./ | function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
| 92,745 | [
1,
1356,
326,
720,
25693,
434,
2795,
9088,
12321,
16,
15226,
310,
598,
1679,
883,
603,
3613,
2426,
261,
13723,
326,
563,
353,
6092,
2934,
9354,
2680,
358,
348,
7953,
560,
1807,
1375,
17,
68,
3726,
18,
29076,
30,
300,
2592,
25693,
2780,
3613,
2426,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
720,
12,
11890,
279,
16,
2254,
324,
16,
533,
3778,
9324,
13,
2713,
16618,
1135,
261,
11890,
13,
288,
203,
3639,
2583,
12,
70,
1648,
279,
16,
9324,
1769,
203,
3639,
2254,
276,
273,
279,
300,
324,
31,
203,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/3/0xcFB7F34f74BbAD94c81D96e816DfCA86501C195e/sources/browser/test.sol | If a contract has a zero balance and supports the token give them some token | function airDrop() hasNoBalance supportsToken public{
tokenBalance[msg.sender] += 20;
}
| 14,262,051 | [
1,
2047,
279,
6835,
711,
279,
3634,
11013,
471,
6146,
326,
1147,
8492,
2182,
2690,
1147,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
225,
445,
23350,
7544,
1435,
711,
2279,
13937,
6146,
1345,
225,
1071,
95,
203,
565,
1147,
13937,
63,
3576,
18,
15330,
65,
1011,
4200,
31,
203,
225,
289,
203,
21281,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x19b683A2F45012318d9B2aE1280d68d3eC54D663/sources/contracts/LimitOrderWithSwapManager.sol | @notice Collect earned token from an limit order @param recipient address to benefit @param orderIdx idx of limit order @return earn amount of token collected during this calling (not all earned token of this order) | function collect(
address recipient,
uint256 orderIdx
) external notPause checkActive(orderIdx) returns (uint128 earn) {
if (recipient == address(0)) {
recipient = address(this);
}
LimOrder storage order = addr2ActiveOrder[msg.sender][orderIdx];
address pool = poolAddrs[order.poolId];
bool noRemain = (order.sellingRemain == 0);
if (order.sellingRemain > 0) {
noRemain = (order.initSellingAmount / order.sellingRemain > 100000);
}
bool sellXEarnY = order.sellXEarnY;
if (earn > 0) {
IiZiSwapPool(pool).collectLimOrder(recipient, order.pt, 0, earn, sellXEarnY);
}
if (noRemain) {
PoolMeta memory poolMeta = poolMetas[order.poolId];
emit Finish(
sellXEarnY? poolMeta.tokenX : poolMeta.tokenY,
sellXEarnY? poolMeta.tokenY : poolMeta.tokenX,
poolMeta.fee,
order.pt,
order.initSellingAmount,
order.earn
);
order.active = false;
}
}
| 11,551,284 | [
1,
10808,
425,
1303,
329,
1147,
628,
392,
1800,
1353,
225,
8027,
1758,
358,
27641,
7216,
225,
1353,
4223,
2067,
434,
1800,
1353,
327,
425,
1303,
3844,
434,
1147,
12230,
4982,
333,
4440,
261,
902,
777,
425,
1303,
329,
1147,
434,
333,
1353,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
3274,
12,
203,
3639,
1758,
8027,
16,
203,
3639,
2254,
5034,
1353,
4223,
203,
565,
262,
3903,
486,
19205,
866,
3896,
12,
1019,
4223,
13,
1135,
261,
11890,
10392,
425,
1303,
13,
288,
203,
3639,
309,
261,
20367,
422,
1758,
12,
20,
3719,
288,
203,
5411,
8027,
273,
1758,
12,
2211,
1769,
203,
3639,
289,
203,
3639,
511,
381,
2448,
2502,
1353,
273,
3091,
22,
3896,
2448,
63,
3576,
18,
15330,
6362,
1019,
4223,
15533,
203,
3639,
1758,
2845,
273,
2845,
13811,
63,
1019,
18,
6011,
548,
15533,
203,
203,
3639,
1426,
1158,
1933,
530,
273,
261,
1019,
18,
87,
1165,
310,
1933,
530,
422,
374,
1769,
203,
3639,
309,
261,
1019,
18,
87,
1165,
310,
1933,
530,
405,
374,
13,
288,
203,
5411,
1158,
1933,
530,
273,
261,
1019,
18,
2738,
55,
1165,
310,
6275,
342,
1353,
18,
87,
1165,
310,
1933,
530,
405,
25259,
1769,
203,
3639,
289,
203,
203,
3639,
1426,
357,
80,
60,
41,
1303,
61,
273,
1353,
18,
87,
1165,
60,
41,
1303,
61,
31,
203,
203,
3639,
309,
261,
73,
1303,
405,
374,
13,
288,
203,
5411,
467,
77,
62,
77,
12521,
2864,
12,
6011,
2934,
14676,
48,
381,
2448,
12,
20367,
16,
1353,
18,
337,
16,
374,
16,
425,
1303,
16,
357,
80,
60,
41,
1303,
61,
1769,
203,
3639,
289,
203,
540,
203,
3639,
309,
261,
2135,
1933,
530,
13,
288,
203,
5411,
8828,
2781,
3778,
2845,
2781,
273,
2845,
30853,
63,
1019,
18,
6011,
548,
15533,
203,
5411,
3626,
18560,
12,
203,
7734,
2
] |
//Address: 0x86a635eccefffa70ff8a6db29da9c8db288e40d0
//Contract name: TokenAEur
//Balance: 0 Ether
//Verification Date: 6/11/2018
//Transacion Count: 8
// CODE STARTS HERE
pragma solidity 0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
require(a == 0 || c / a == b, "mul overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "div by 0"); // Solidity automatically throws for div by 0 but require to emit reason
uint256 c = a / b;
// require(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) {
require(b <= a, "sub underflow");
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "add overflow");
return c;
}
function roundedDiv(uint a, uint b) internal pure returns (uint256) {
require(b > 0, "div by 0"); // Solidity automatically throws for div by 0 but require to emit reason
uint256 z = a / b;
if (a % b >= b / 2) {
z++; // no need for safe add b/c it can happen only if we divided the input
}
return z;
}
}
/*
Generic contract to authorise calls to certain functions only from a given address.
The address authorised must be a contract (multisig or not, depending on the permission), except for local test
deployment works as:
1. contract deployer account deploys contracts
2. constructor grants "PermissionGranter" permission to deployer account
3. deployer account executes initial setup (no multiSig)
4. deployer account grants PermissionGranter permission for the MultiSig contract
(e.g. StabilityBoardProxy or PreTokenProxy)
5. deployer account revokes its own PermissionGranter permission
*/
contract Restricted {
// NB: using bytes32 rather than the string type because it's cheaper gas-wise:
mapping (address => mapping (bytes32 => bool)) public permissions;
event PermissionGranted(address indexed agent, bytes32 grantedPermission);
event PermissionRevoked(address indexed agent, bytes32 revokedPermission);
modifier restrict(bytes32 requiredPermission) {
require(permissions[msg.sender][requiredPermission], "msg.sender must have permission");
_;
}
constructor(address permissionGranterContract) public {
require(permissionGranterContract != address(0), "permissionGranterContract must be set");
permissions[permissionGranterContract]["PermissionGranter"] = true;
emit PermissionGranted(permissionGranterContract, "PermissionGranter");
}
function grantPermission(address agent, bytes32 requiredPermission) public {
require(permissions[msg.sender]["PermissionGranter"],
"msg.sender must have PermissionGranter permission");
permissions[agent][requiredPermission] = true;
emit PermissionGranted(agent, requiredPermission);
}
function grantMultiplePermissions(address agent, bytes32[] requiredPermissions) public {
require(permissions[msg.sender]["PermissionGranter"],
"msg.sender must have PermissionGranter permission");
uint256 length = requiredPermissions.length;
for (uint256 i = 0; i < length; i++) {
grantPermission(agent, requiredPermissions[i]);
}
}
function revokePermission(address agent, bytes32 requiredPermission) public {
require(permissions[msg.sender]["PermissionGranter"],
"msg.sender must have PermissionGranter permission");
permissions[agent][requiredPermission] = false;
emit PermissionRevoked(agent, requiredPermission);
}
function revokeMultiplePermissions(address agent, bytes32[] requiredPermissions) public {
uint256 length = requiredPermissions.length;
for (uint256 i = 0; i < length; i++) {
revokePermission(agent, requiredPermissions[i]);
}
}
}
/**
* @title Eliptic curve signature operations
*
* @dev Based on https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/ECRecovery.sol
*
* TODO Remove this library once solidity supports passing a signature to ecrecover.
* See https://github.com/ethereum/solidity/issues/864
*
*/
library ECRecovery {
/**
* @dev Recover signer address from a message by using their signature
* @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
* @param sig bytes signature, the signature is generated using web3.eth.sign()
*/
function recover(bytes32 hash, bytes sig)
internal
pure
returns (address)
{
bytes32 r;
bytes32 s;
uint8 v;
// Check the signature length
if (sig.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solium-disable-next-line security/no-inline-assembly
assembly {
r := mload(add(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) {
return (address(0));
} else {
// solium-disable-next-line arg-overflow
return ecrecover(hash, v, r, s);
}
}
/**
* toEthSignedMessageHash
* @dev prefix a bytes32 value with "\x19Ethereum Signed Message:"
* @dev and hash the result
*/
function toEthSignedMessageHash(bytes32 hash)
internal
pure
returns (bytes32)
{
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
interface ERC20Interface {
event Approval(address indexed _owner, address indexed _spender, uint _value);
event Transfer(address indexed from, address indexed to, uint amount);
function transfer(address to, uint value) external returns (bool); // solhint-disable-line no-simple-event-func-name
function transferFrom(address from, address to, uint value) external returns (bool);
function approve(address spender, uint value) external returns (bool);
function balanceOf(address who) external view returns (uint);
function allowance(address _owner, address _spender) external view returns (uint remaining);
}
interface TokenReceiver {
function transferNotification(address from, uint256 amount, uint data) external;
}
contract AugmintTokenInterface is Restricted, ERC20Interface {
using SafeMath for uint256;
string public name;
string public symbol;
bytes32 public peggedSymbol;
uint8 public decimals;
uint public totalSupply;
mapping(address => uint256) public balances; // Balances for each account
mapping(address => mapping (address => uint256)) public allowed; // allowances added with approve()
address public stabilityBoardProxy;
TransferFeeInterface public feeAccount;
mapping(bytes32 => bool) public delegatedTxHashesUsed; // record txHashes used by delegatedTransfer
event TransferFeesChanged(uint transferFeePt, uint transferFeeMin, uint transferFeeMax);
event Transfer(address indexed from, address indexed to, uint amount);
event AugmintTransfer(address indexed from, address indexed to, uint amount, string narrative, uint fee);
event TokenIssued(uint amount);
event TokenBurned(uint amount);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function transfer(address to, uint value) external returns (bool); // solhint-disable-line no-simple-event-func-name
function transferFrom(address from, address to, uint value) external returns (bool);
function approve(address spender, uint value) external returns (bool);
function delegatedTransfer(address from, address to, uint amount, string narrative,
uint maxExecutorFeeInToken, /* client provided max fee for executing the tx */
bytes32 nonce, /* random nonce generated by client */
/* ^^^^ end of signed data ^^^^ */
bytes signature,
uint requestedExecutorFeeInToken /* the executor can decide to request lower fee */
) external;
function delegatedTransferAndNotify(address from, TokenReceiver target, uint amount, uint data,
uint maxExecutorFeeInToken, /* client provided max fee for executing the tx */
bytes32 nonce, /* random nonce generated by client */
/* ^^^^ end of signed data ^^^^ */
bytes signature,
uint requestedExecutorFeeInToken /* the executor can decide to request lower fee */
) external;
function increaseApproval(address spender, uint addedValue) external returns (bool);
function decreaseApproval(address spender, uint subtractedValue) external returns (bool);
function issueTo(address to, uint amount) external; // restrict it to "MonetarySupervisor" in impl.;
function burn(uint amount) external;
function transferAndNotify(TokenReceiver target, uint amount, uint data) external;
function transferWithNarrative(address to, uint256 amount, string narrative) external;
function transferFromWithNarrative(address from, address to, uint256 amount, string narrative) external;
function allowance(address owner, address spender) external view returns (uint256 remaining);
function balanceOf(address who) external view returns (uint);
}
interface TransferFeeInterface {
function calculateTransferFee(address from, address to, uint amount) external view returns (uint256 fee);
}
contract AugmintToken is AugmintTokenInterface {
event FeeAccountChanged(TransferFeeInterface newFeeAccount);
constructor(address permissionGranterContract, string _name, string _symbol, bytes32 _peggedSymbol, uint8 _decimals, TransferFeeInterface _feeAccount)
public Restricted(permissionGranterContract) {
require(_feeAccount != address(0), "feeAccount must be set");
require(bytes(_name).length > 0, "name must be set");
require(bytes(_symbol).length > 0, "symbol must be set");
name = _name;
symbol = _symbol;
peggedSymbol = _peggedSymbol;
decimals = _decimals;
feeAccount = _feeAccount;
}
function transfer(address to, uint256 amount) external returns (bool) {
_transfer(msg.sender, to, amount, "");
return true;
}
/* Transfers based on an offline signed transfer instruction. */
function delegatedTransfer(address from, address to, uint amount, string narrative,
uint maxExecutorFeeInToken, /* client provided max fee for executing the tx */
bytes32 nonce, /* random nonce generated by client */
/* ^^^^ end of signed data ^^^^ */
bytes signature,
uint requestedExecutorFeeInToken /* the executor can decide to request lower fee */
)
external {
bytes32 txHash = keccak256(abi.encodePacked(this, from, to, amount, narrative, maxExecutorFeeInToken, nonce));
_checkHashAndTransferExecutorFee(txHash, signature, from, maxExecutorFeeInToken, requestedExecutorFeeInToken);
_transfer(from, to, amount, narrative);
}
function approve(address _spender, uint256 amount) external returns (bool) {
require(_spender != 0x0, "spender must be set");
allowed[msg.sender][_spender] = amount;
emit Approval(msg.sender, _spender, amount);
return true;
}
/**
ERC20 transferFrom attack protection: https://github.com/DecentLabs/dcm-poc/issues/57
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)
Based on MonolithDAO Token.sol */
function increaseApproval(address _spender, uint _addedValue) external returns (bool) {
return _increaseApproval(msg.sender, _spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) external 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;
}
function transferFrom(address from, address to, uint256 amount) external returns (bool) {
_transferFrom(from, to, amount, "");
return true;
}
// Issue tokens. See MonetarySupervisor but as a rule of thumb issueTo is only allowed:
// - on new loan (by trusted Lender contracts)
// - when converting old tokens using MonetarySupervisor
// - strictly to reserve by Stability Board (via MonetarySupervisor)
function issueTo(address to, uint amount) external restrict("MonetarySupervisor") {
balances[to] = balances[to].add(amount);
totalSupply = totalSupply.add(amount);
emit Transfer(0x0, to, amount);
emit AugmintTransfer(0x0, to, amount, "", 0);
}
// Burn tokens. Anyone can burn from its own account. YOLO.
// Used by to burn from Augmint reserve or by Lender contract after loan repayment
function burn(uint amount) external {
require(balances[msg.sender] >= amount, "balance must be >= amount");
balances[msg.sender] = balances[msg.sender].sub(amount);
totalSupply = totalSupply.sub(amount);
emit Transfer(msg.sender, 0x0, amount);
emit AugmintTransfer(msg.sender, 0x0, amount, "", 0);
}
/* to upgrade feeAccount (eg. for fee calculation changes) */
function setFeeAccount(TransferFeeInterface newFeeAccount) external restrict("StabilityBoard") {
feeAccount = newFeeAccount;
emit FeeAccountChanged(newFeeAccount);
}
/* transferAndNotify can be used by contracts which require tokens to have only 1 tx (instead of approve + call)
Eg. repay loan, lock funds, token sell order on exchange
Reverts on failue:
- transfer fails
- if transferNotification fails (callee must revert on failure)
- if targetContract is an account or targetContract doesn't have neither transferNotification or fallback fx
TODO: make data param generic bytes (see receiver code attempt in Locker.transferNotification)
*/
function transferAndNotify(TokenReceiver target, uint amount, uint data) external {
_transfer(msg.sender, target, amount, "");
target.transferNotification(msg.sender, amount, data);
}
/* transferAndNotify based on an instruction signed offline */
function delegatedTransferAndNotify(address from, TokenReceiver target, uint amount, uint data,
uint maxExecutorFeeInToken, /* client provided max fee for executing the tx */
bytes32 nonce, /* random nonce generated by client */
/* ^^^^ end of signed data ^^^^ */
bytes signature,
uint requestedExecutorFeeInToken /* the executor can decide to request lower fee */
)
external {
bytes32 txHash = keccak256(abi.encodePacked(this, from, target, amount, data, maxExecutorFeeInToken, nonce));
_checkHashAndTransferExecutorFee(txHash, signature, from, maxExecutorFeeInToken, requestedExecutorFeeInToken);
_transfer(from, target, amount, "");
target.transferNotification(from, amount, data);
}
function transferWithNarrative(address to, uint256 amount, string narrative) external {
_transfer(msg.sender, to, amount, narrative);
}
function transferFromWithNarrative(address from, address to, uint256 amount, string narrative) external {
_transferFrom(from, to, amount, narrative);
}
function balanceOf(address _owner) external view returns (uint256 balance) {
return balances[_owner];
}
function allowance(address _owner, address _spender) external view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function _checkHashAndTransferExecutorFee(bytes32 txHash, bytes signature, address signer,
uint maxExecutorFeeInToken, uint requestedExecutorFeeInToken) private {
require(requestedExecutorFeeInToken <= maxExecutorFeeInToken, "requestedExecutorFee must be <= maxExecutorFee");
require(!delegatedTxHashesUsed[txHash], "txHash already used");
delegatedTxHashesUsed[txHash] = true;
address recovered = ECRecovery.recover(ECRecovery.toEthSignedMessageHash(txHash), signature);
require(recovered == signer, "invalid signature");
_transfer(signer, msg.sender, requestedExecutorFeeInToken, "Delegated transfer fee", 0);
}
function _increaseApproval(address _approver, address _spender, uint _addedValue) private returns (bool) {
allowed[_approver][_spender] = allowed[_approver][_spender].add(_addedValue);
emit Approval(_approver, _spender, allowed[_approver][_spender]);
}
function _transferFrom(address from, address to, uint256 amount, string narrative) private {
require(balances[from] >= amount, "balance must >= amount");
require(allowed[from][msg.sender] >= amount, "allowance must be >= amount");
// don't allow 0 transferFrom if no approval:
require(allowed[from][msg.sender] > 0, "allowance must be >= 0 even with 0 amount");
/* NB: fee is deducted from owner. It can result that transferFrom of amount x to fail
when x + fee is not availale on owner balance */
_transfer(from, to, amount, narrative);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(amount);
}
function _transfer(address from, address to, uint transferAmount, string narrative) private {
uint fee = feeAccount.calculateTransferFee(from, to, transferAmount);
_transfer(from, to, transferAmount, narrative, fee);
}
function _transfer(address from, address to, uint transferAmount, string narrative, uint fee) private {
require(to != 0x0, "to must be set");
uint amountWithFee = transferAmount.add(fee);
// to emit proper reason instead of failing on from.sub()
require(balances[from] >= amountWithFee, "balance must be >= amount + transfer fee");
if (fee > 0) {
balances[feeAccount] = balances[feeAccount].add(fee);
emit Transfer(from, feeAccount, fee);
}
balances[from] = balances[from].sub(amountWithFee);
balances[to] = balances[to].add(transferAmount);
emit Transfer(from, to, transferAmount);
emit AugmintTransfer(from, to, transferAmount, narrative, fee);
}
}
/* Augmint Crypto Euro token (A-EUR) implementation */
contract TokenAEur is AugmintToken {
constructor(address _permissionGranterContract, TransferFeeInterface _feeAccount)
public AugmintToken(_permissionGranterContract, "Augmint Crypto Euro", "AEUR", "EUR", 2, _feeAccount)
{} // solhint-disable-line no-empty-blocks
}
| Burn tokens. Anyone can burn from its own account. YOLO. Used by to burn from Augmint reserve or by Lender contract after loan repayment | function burn(uint amount) external {
require(balances[msg.sender] >= amount, "balance must be >= amount");
balances[msg.sender] = balances[msg.sender].sub(amount);
totalSupply = totalSupply.sub(amount);
emit Transfer(msg.sender, 0x0, amount);
emit AugmintTransfer(msg.sender, 0x0, amount, "", 0);
}
| 924,002 | [
1,
38,
321,
2430,
18,
5502,
476,
848,
18305,
628,
2097,
4953,
2236,
18,
1624,
51,
1502,
18,
10286,
635,
358,
18305,
628,
432,
637,
81,
474,
20501,
578,
635,
511,
2345,
6835,
1839,
28183,
2071,
2955,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
18305,
12,
11890,
3844,
13,
3903,
288,
203,
3639,
2583,
12,
70,
26488,
63,
3576,
18,
15330,
65,
1545,
3844,
16,
315,
12296,
1297,
506,
1545,
3844,
8863,
203,
3639,
324,
26488,
63,
3576,
18,
15330,
65,
273,
324,
26488,
63,
3576,
18,
15330,
8009,
1717,
12,
8949,
1769,
203,
3639,
2078,
3088,
1283,
273,
2078,
3088,
1283,
18,
1717,
12,
8949,
1769,
203,
3639,
3626,
12279,
12,
3576,
18,
15330,
16,
374,
92,
20,
16,
3844,
1769,
203,
3639,
3626,
432,
637,
81,
474,
5912,
12,
3576,
18,
15330,
16,
374,
92,
20,
16,
3844,
16,
23453,
374,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/42/0xA2Fd943F260633023a7139C5E3eD522521918Bd4/sources/ERC20PresetMinterPauserUpgradeSafe.sol | * @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 {
bool private initialized;
bool private initializing;
pragma solidity >=0.4.24 <0.7.0;
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;
}
}
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;
}
}
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;
}
}
function isConstructor() private view returns (bool) {
address self = address(this);
uint256 cs;
return cs == 0;
}
assembly { cs := extcodesize(self) }
uint256[50] private ______gap;
}
| 3,335,425 | [
1,
4435,
6934,
225,
9705,
6835,
358,
2865,
12562,
4186,
18,
2974,
999,
518,
16,
1453,
326,
3885,
598,
279,
445,
716,
711,
326,
1375,
22181,
68,
9606,
18,
9744,
30,
25448,
19874,
16,
12562,
4186,
1297,
506,
10036,
8187,
18,
1220,
10294,
3937,
358,
7286,
310,
392,
10188,
6934,
6835,
16,
487,
5492,
487,
27147,
392,
10188,
6934,
6835,
3970,
16334,
18,
9744,
30,
5203,
1399,
598,
16334,
16,
11297,
7671,
1297,
506,
9830,
358,
486,
4356,
279,
982,
12562,
13605,
16,
578,
3387,
716,
777,
2172,
8426,
854,
27959,
16,
2724,
333,
353,
486,
443,
2390,
598,
6635,
487,
598,
19874,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
16351,
10188,
6934,
288,
203,
203,
225,
1426,
3238,
6454,
31,
203,
203,
225,
1426,
3238,
22584,
31,
203,
203,
683,
9454,
18035,
560,
1545,
20,
18,
24,
18,
3247,
411,
20,
18,
27,
18,
20,
31,
203,
225,
9606,
12562,
1435,
288,
203,
565,
2583,
12,
6769,
6894,
747,
353,
6293,
1435,
747,
401,
13227,
16,
315,
8924,
791,
711,
1818,
2118,
6454,
8863,
203,
203,
565,
1426,
353,
27046,
1477,
273,
401,
6769,
6894,
31,
203,
565,
309,
261,
291,
27046,
1477,
13,
288,
203,
1377,
22584,
273,
638,
31,
203,
1377,
6454,
273,
638,
31,
203,
565,
289,
203,
203,
565,
389,
31,
203,
203,
565,
309,
261,
291,
27046,
1477,
13,
288,
203,
1377,
22584,
273,
629,
31,
203,
565,
289,
203,
225,
289,
203,
203,
225,
9606,
12562,
1435,
288,
203,
565,
2583,
12,
6769,
6894,
747,
353,
6293,
1435,
747,
401,
13227,
16,
315,
8924,
791,
711,
1818,
2118,
6454,
8863,
203,
203,
565,
1426,
353,
27046,
1477,
273,
401,
6769,
6894,
31,
203,
565,
309,
261,
291,
27046,
1477,
13,
288,
203,
1377,
22584,
273,
638,
31,
203,
1377,
6454,
273,
638,
31,
203,
565,
289,
203,
203,
565,
389,
31,
203,
203,
565,
309,
261,
291,
27046,
1477,
13,
288,
203,
1377,
22584,
273,
629,
31,
203,
565,
289,
203,
225,
289,
203,
203,
225,
9606,
12562,
1435,
288,
203,
565,
2583,
12,
6769,
6894,
747,
353,
6293,
1435,
747,
401,
13227,
16,
315,
8924,
791,
711,
1818,
2118,
6454,
8863,
203,
203,
565,
1426,
353,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^ 0.8.0;
/**
* @title Fractions
* @author Hyun Cho (@pakchu), refactoring thanks to: Beomsoo Kim (@bombs-kim)
* @dev With Solidity 0.8.0 <= version <=0.9.0, the compiler's built in overflow checker made possible for this library not to depend on SafeMath.
*/
library Fractions {
/**
* @dev Defining a strtuct for Fractional expression.
*/
struct Fraction {
uint256 numerator;
uint256 denominator;
}
struct Mixed {
uint256 integer;
Fraction fraction;
}
function sort(uint256 a, uint256 b) internal pure returns(uint256, uint256){
if (a > b){
return (a,b);
} else return (b,a);
}
/**
* @dev Function for getting greatest common divisor, which is inevitable to operate Fractions.
* This function is using Euclidean Algoithm, you can find info's here: https://en.wikipedia.org/wiki/Euclidean_algorithm
* Has time complexity of O(log(min(a,b))), and a nice proof for this: https://www.geeksforgeeks.org/time-complexity-of-euclidean-algorithm/
*/
function gcd(uint256 a, uint256 b) internal pure returns(uint256){
(a,b) = sort(a,b);
while(b != 0) {
(a, b) = (b, a % b);
}
return a;
}
/**
* @dev Function for getting least common multiplier.
* Has the same time complexity as gcd().
*/
function lcm(uint256 a, uint256 b) internal pure returns(uint256){
return (a / gcd(a,b) ) * b;
}
/**
* @dev Check if a Fraction's denominator is 0.
*/
modifier denominatorIsNotZero(Fraction memory frac) {
require (frac.denominator != 0, "denominator cannot be 0");
_;
}
/**
* @dev Has the same time complexity as abbreviate()
*/
function isAbbreviatable(Fraction memory frac) internal pure denominatorIsNotZero(frac) returns(bool) {
if(gcd(frac.numerator,frac.denominator) != 1) return true;
else return false;
}
/**
* @dev Making Fraction into reduced Fraction.
* Has time complexity of O(log(min(numerator,denominator)))
*/
function abbreviate(Fraction memory frac)internal pure denominatorIsNotZero(frac) returns (Fraction memory){
if (isAbbreviatable(frac)) {
uint256 _gcd = gcd(frac.numerator, frac.denominator);
return Fraction(frac.numerator / _gcd, frac.denominator / _gcd);
} else return frac;
}
function toReciprocal(Fraction memory frac) internal pure denominatorIsNotZero(frac) returns(Fraction memory){
require(frac.numerator != 0, "denominator cannot be 0");
return Fraction(frac.denominator, frac.numerator);
}
/**
* @dev Finding lcm of denominators of two Fractions, and reduce to common denominator with lcm.
* Has time complexity of O(log(min(a.denominator, b.denominator)))
*/
function reduceToCommonDenominator(Fraction memory a, Fraction memory b) internal pure denominatorIsNotZero(a) denominatorIsNotZero(b) returns(Fraction memory, Fraction memory){
uint256 _lcm = lcm(a.denominator, b.denominator);
uint256 numerator0 = (_lcm / a.denominator) * a.numerator;
uint256 numerator1 = (_lcm / b.denominator) * b.numerator;
return (Fraction(numerator0, _lcm), Fraction(numerator1, _lcm));
}
/**
* @dev Has time complexity of O(log(min(big.denominator, small.denominator)))
*/
function isGreaterThan(Fraction memory big, Fraction memory small)internal pure denominatorIsNotZero(big) denominatorIsNotZero(small) returns(bool) {
Fraction memory c;
Fraction memory d;
(c, d) = reduceToCommonDenominator(big, small);
if (c.numerator >= d.numerator) return true;
else return false;
}
/**
* @dev For some use cases which do not need abbreviation.
* Has the same time complexity as reduceToCommonDenominator().
*/
function _add(Fraction memory a, Fraction memory b) internal pure denominatorIsNotZero(a) denominatorIsNotZero(b) returns(Fraction memory c){
(a,b) = reduceToCommonDenominator(a,b);
c = Fraction(a.numerator + b.numerator, a.denominator);
}
/**
* @dev Has time complexity of O(log(max(min(_add(a,b).numerator, _add(a,b).denominator), min(_add(a,b).numerator, _add(a,b).denominator)))).
*/
function add(Fraction memory a, Fraction memory b) internal pure denominatorIsNotZero(a) denominatorIsNotZero(b) returns(Fraction memory c){
c = abbreviate(_add(a,b));
}
/**
* @dev For some use cases which do not need abbreviation.
* Has the same time complexity as reduceToCommonDenominator().
*/
function _sub(Fraction memory a, Fraction memory b) internal pure denominatorIsNotZero(a) denominatorIsNotZero(b) returns(Fraction memory c){
require( isGreaterThan(a, b), "Fraction: Underflow" );
(a,b) = reduceToCommonDenominator(a,b);
c = Fraction( a.numerator - b.numerator, a.denominator );
}
/**
* @dev Has time complexity of O(log(max(min(_sub(a,b).numerator, _sub(a,b).denominator), min(_sub(a,b).numerator, _sub(a,b).denominator)))).
*/
function sub(Fraction memory a, Fraction memory b) internal pure denominatorIsNotZero(a) denominatorIsNotZero(b) returns(Fraction memory c){
c = abbreviate(_sub(a,b));
}
/**
* @dev For some use cases which do not need abbreviation.
*/
function _mul(Fraction memory a, Fraction memory b)internal pure denominatorIsNotZero(a) denominatorIsNotZero(b) returns(Fraction memory c){
c = Fraction(a.numerator * b.numerator, a.denominator * b.denominator);
}
/**
* @dev Has time complexity of O(log(max(min(a.numerator, a.denominator), min(b.numerator, b.denominator), min(a.numerator, b.denominator), min(b.numerator, a.denominator))).
* max(...) = second or third maximum element of (a.numerator, a.denominator, b.numerator, b.denominator).
* If the second maximum element is paired with the maximum element at least once, max(...) = second maximum of (...)
* Else max(...) = third maximum of (...)
*/
function mul(Fraction memory a, Fraction memory b) internal pure denominatorIsNotZero(a) denominatorIsNotZero(b) returns(Fraction memory result) {
a = abbreviate(a);
b = abbreviate(b);
Fraction memory c = abbreviate(Fraction(a.numerator , b.denominator));
Fraction memory d = abbreviate(Fraction(b.numerator , a.denominator));
result = Fraction(c.numerator * d.numerator , c.denominator * d.denominator);
}
/**
* @dev For some use cases which do not need abbreviation.
*/
function _div(Fraction memory a, Fraction memory b)internal pure denominatorIsNotZero(a) denominatorIsNotZero(b) returns(Fraction memory c) {
require( b.numerator != 0, "denominator cannot be 0");
c = _mul(a, toReciprocal(b));
}
/**
* @dev Has time complexity of O(log(max(min(a.numerator, a.denominator), min(b.numerator, b.denominator), min(a.numerator, b.numerator), min(a.denominator, b.denominator))).
* max(...) = second or third maximum element of (a.numerator, a.denominator, b.numerator, b.denominator).
* If the second maximum element is paired with the maximum element at least once, max(...) = second maximum of (...)
* Else max(...) = third maximum of (...)
*/
function div(Fraction memory a, Fraction memory b) denominatorIsNotZero(a) denominatorIsNotZero(b) internal pure returns(Fraction memory result){
require(b.numerator != 0, "denominator cannot be 0");
result = mul(a, toReciprocal(b));
}
/**
* @dev By using this function with proper divider, it can help the Fraction not to overflow.
* Since dividing both numerator and denomiantor with same number keeps the original value of Fraction,
* but as in solidity which is only able to express integers, not floats, integer divided by some integer may give out approximated value.
*/
function preventOverflow(Fraction memory frac, uint256 divider) internal pure denominatorIsNotZero(frac) returns(Fraction memory){
return abbreviate(Fraction(frac.numerator / divider, frac.denominator / divider));
}
} | * @dev Defining a strtuct for Fractional expression./ | struct Fraction {
uint256 numerator;
uint256 denominator;
}
| 6,457,901 | [
1,
6443,
310,
279,
609,
88,
853,
364,
478,
5738,
287,
2652,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
1958,
478,
5738,
288,
203,
3639,
2254,
5034,
16730,
31,
203,
3639,
2254,
5034,
15030,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: BUSL-1.1
// For further clarification please see https://license.premia.legal
pragma solidity ^0.8.0;
import {OwnableInternal, OwnableStorage} from "@solidstate/contracts/access/OwnableInternal.sol";
import {IERC20} from "@solidstate/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@solidstate/contracts/utils/SafeERC20.sol";
import {PremiaMiningStorage} from "./PremiaMiningStorage.sol";
import {IPremiaMining} from "./IPremiaMining.sol";
import {IPoolIO} from "../pool/IPoolIO.sol";
import {IPoolView} from "../pool/IPoolView.sol";
/**
* @title Premia liquidity mining contract, derived from Sushiswap's MasterChef.sol ( https://github.com/sushiswap/sushiswap )
*/
contract PremiaMining is IPremiaMining, OwnableInternal {
using PremiaMiningStorage for PremiaMiningStorage.Layout;
using SafeERC20 for IERC20;
address internal immutable DIAMOND;
address internal immutable PREMIA;
event Claim(
address indexed user,
address indexed pool,
bool indexed isCallPool,
uint256 rewardAmount
);
event UpdatePoolAlloc(address indexed pool, uint256 allocPoints);
constructor(address _diamond, address _premia) {
DIAMOND = _diamond;
PREMIA = _premia;
}
modifier onlyPool(address _pool) {
require(msg.sender == _pool, "Not pool");
_;
}
modifier onlyDiamondOrOwner() {
require(
msg.sender == DIAMOND ||
msg.sender == OwnableStorage.layout().owner,
"Not diamond or owner"
);
_;
}
/**
* @notice Add premia rewards to distribute. Can only be called by the owner
* @param _amount Amount of premia to add
*/
function addPremiaRewards(uint256 _amount) external override onlyOwner {
PremiaMiningStorage.Layout storage l = PremiaMiningStorage.layout();
IERC20(PREMIA).safeTransferFrom(msg.sender, address(this), _amount);
l.premiaAvailable += _amount;
}
/**
* @notice Get amount of premia reward available to distribute
* @return Amount of premia reward available to distribute
*/
function premiaRewardsAvailable() external view override returns (uint256) {
return PremiaMiningStorage.layout().premiaAvailable;
}
/**
* @notice Get the total allocation points
* @return Total allocation points
*/
function getTotalAllocationPoints()
external
view
override
returns (uint256)
{
return PremiaMiningStorage.layout().totalAllocPoint;
}
/**
* @notice Get pool info
* @param pool address of the pool
* @param isCallPool whether we want infos of the CALL pool or the PUT pool
* @return Pool info
*/
function getPoolInfo(address pool, bool isCallPool)
external
view
override
returns (PremiaMiningStorage.PoolInfo memory)
{
return PremiaMiningStorage.layout().poolInfo[pool][isCallPool];
}
/**
* @notice Get the amount of premia emitted per block
* @return Premia emitted per block
*/
function getPremiaPerBlock() external view override returns (uint256) {
return PremiaMiningStorage.layout().premiaPerBlock;
}
/**
* @notice Set new alloc points for an option pool. Can only be called by the owner.
* @param _premiaPerBlock Amount of PREMIA per block to allocate as reward accross all pools
*/
function setPremiaPerBlock(uint256 _premiaPerBlock) external onlyOwner {
PremiaMiningStorage.layout().premiaPerBlock = _premiaPerBlock;
}
/**
* @notice Add a new option pool to the liquidity mining. Can only be called by the owner or premia diamond
* @param _pool Address of option pool contract
* @param _allocPoints Weight of this pool in the reward calculation
*/
function addPool(address _pool, uint256 _allocPoints)
external
override
onlyDiamondOrOwner
{
PremiaMiningStorage.Layout storage l = PremiaMiningStorage.layout();
require(
l.poolInfo[_pool][true].lastRewardBlock == 0 &&
l.poolInfo[_pool][false].lastRewardBlock == 0,
"Pool exists"
);
l.totalAllocPoint += (_allocPoints * 2);
l.poolInfo[_pool][true] = PremiaMiningStorage.PoolInfo({
allocPoint: _allocPoints,
lastRewardBlock: block.number,
accPremiaPerShare: 0
});
l.poolInfo[_pool][false] = PremiaMiningStorage.PoolInfo({
allocPoint: _allocPoints,
lastRewardBlock: block.number,
accPremiaPerShare: 0
});
emit UpdatePoolAlloc(_pool, _allocPoints);
}
/**
* @notice Set new alloc points for an option pool. Can only be called by the owner or premia diamond
* @param _pool Address of option pool contract
* @param _allocPoints Weight of this pool in the reward calculation
*/
function setPoolAllocPoints(address _pool, uint256 _allocPoints)
external
override
onlyDiamondOrOwner
{
PremiaMiningStorage.Layout storage l = PremiaMiningStorage.layout();
require(
l.poolInfo[_pool][true].lastRewardBlock > 0 &&
l.poolInfo[_pool][false].lastRewardBlock > 0,
"Pool does not exists"
);
l.totalAllocPoint =
l.totalAllocPoint -
l.poolInfo[_pool][true].allocPoint -
l.poolInfo[_pool][false].allocPoint +
(_allocPoints * 2);
l.poolInfo[_pool][true].allocPoint = _allocPoints;
l.poolInfo[_pool][false].allocPoint = _allocPoints;
emit UpdatePoolAlloc(_pool, _allocPoints);
}
/**
* @notice Get pending premia reward for a user on a pool
* @param _pool Address of option pool contract
* @param _isCallPool True if for call option pool, False if for put option pool
*/
function pendingPremia(
address _pool,
bool _isCallPool,
address _user
) external view override returns (uint256) {
uint256 TVL;
uint256 userTVL;
{
(uint256 underlyingTVL, uint256 baseTVL) = IPoolView(_pool)
.getTotalTVL();
TVL = _isCallPool ? underlyingTVL : baseTVL;
}
{
(uint256 userUnderlyingTVL, uint256 userBaseTVL) = IPoolView(_pool)
.getUserTVL(_user);
userTVL = _isCallPool ? userUnderlyingTVL : userBaseTVL;
}
PremiaMiningStorage.Layout storage l = PremiaMiningStorage.layout();
PremiaMiningStorage.PoolInfo storage pool = l.poolInfo[_pool][
_isCallPool
];
PremiaMiningStorage.UserInfo storage user = l.userInfo[_pool][
_isCallPool
][_user];
uint256 accPremiaPerShare = pool.accPremiaPerShare;
if (block.number > pool.lastRewardBlock && TVL != 0) {
uint256 premiaReward = ((block.number - pool.lastRewardBlock) *
l.premiaPerBlock *
pool.allocPoint) / l.totalAllocPoint;
// If we are running out of rewards to distribute, distribute whats left
if (premiaReward > l.premiaAvailable) {
premiaReward = l.premiaAvailable;
}
accPremiaPerShare += (premiaReward * 1e12) / TVL;
}
return
((userTVL * accPremiaPerShare) / 1e12) -
user.rewardDebt +
user.reward;
}
/**
* @notice Update reward variables of the given pool to be up-to-date. Only callable by the option pool
* @param _pool Address of option pool contract
* @param _isCallPool True if for call option pool, False if for put option pool
* @param _totalTVL Total amount of tokens deposited in the option pool
*/
function updatePool(
address _pool,
bool _isCallPool,
uint256 _totalTVL
) external override onlyPool(_pool) {
_updatePool(_pool, _isCallPool, _totalTVL);
}
/**
* @notice Update reward variables of the given pool to be up-to-date. Only callable by the option pool
* @param _pool Address of option pool contract
* @param _isCallPool True if for call option pool, False if for put option pool
* @param _totalTVL Total amount of tokens deposited in the option pool
*/
function _updatePool(
address _pool,
bool _isCallPool,
uint256 _totalTVL
) internal {
PremiaMiningStorage.Layout storage l = PremiaMiningStorage.layout();
PremiaMiningStorage.PoolInfo storage pool = l.poolInfo[_pool][
_isCallPool
];
if (block.number <= pool.lastRewardBlock) {
return;
}
if (_totalTVL == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 premiaReward = ((block.number - pool.lastRewardBlock) *
l.premiaPerBlock *
pool.allocPoint) / l.totalAllocPoint;
// If we are running out of rewards to distribute, distribute whats left
if (premiaReward > l.premiaAvailable) {
premiaReward = l.premiaAvailable;
}
l.premiaAvailable -= premiaReward;
pool.accPremiaPerShare += (premiaReward * 1e12) / _totalTVL;
pool.lastRewardBlock = block.number;
}
/**
* @notice Allocate pending rewards to a user. Only callable by the option pool
* @param _user User for whom allocate the rewards
* @param _pool Address of option pool contract
* @param _isCallPool True if for call option pool, False if for put option pool
* @param _userTVLOld Total amount of tokens deposited in the option pool by user before the allocation update
* @param _userTVLNew Total amount of tokens deposited in the option pool by user after the allocation update
* @param _totalTVL Total amount of tokens deposited in the option pool
*/
function allocatePending(
address _user,
address _pool,
bool _isCallPool,
uint256 _userTVLOld,
uint256 _userTVLNew,
uint256 _totalTVL
) external override onlyPool(_pool) {
_allocatePending(
_user,
_pool,
_isCallPool,
_userTVLOld,
_userTVLNew,
_totalTVL
);
}
/**
* @notice Allocate pending rewards to a user. Only callable by the option pool
* @param _user User for whom allocate the rewards
* @param _pool Address of option pool contract
* @param _isCallPool True if for call option pool, False if for put option pool
* @param _userTVLOld Total amount of tokens deposited in the option pool by user before the allocation update
* @param _userTVLNew Total amount of tokens deposited in the option pool by user after the allocation update
* @param _totalTVL Total amount of tokens deposited in the option pool
*/
function _allocatePending(
address _user,
address _pool,
bool _isCallPool,
uint256 _userTVLOld,
uint256 _userTVLNew,
uint256 _totalTVL
) internal {
PremiaMiningStorage.Layout storage l = PremiaMiningStorage.layout();
PremiaMiningStorage.PoolInfo storage pool = l.poolInfo[_pool][
_isCallPool
];
PremiaMiningStorage.UserInfo storage user = l.userInfo[_pool][
_isCallPool
][_user];
_updatePool(_pool, _isCallPool, _totalTVL);
user.reward +=
((_userTVLOld * pool.accPremiaPerShare) / 1e12) -
user.rewardDebt;
user.rewardDebt = (_userTVLNew * pool.accPremiaPerShare) / 1e12;
}
/**
* @notice Update user reward allocation + claim allocated PREMIA reward. Only callable by the option pool
* @param _user User claiming the rewards
* @param _pool Address of option pool contract
* @param _isCallPool True if for call option pool, False if for put option pool
* @param _userTVLOld Total amount of tokens deposited in the option pool by user before the allocation update
* @param _userTVLNew Total amount of tokens deposited in the option pool by user after the allocation update
* @param _totalTVL Total amount of tokens deposited in the option pool
*/
function claim(
address _user,
address _pool,
bool _isCallPool,
uint256 _userTVLOld,
uint256 _userTVLNew,
uint256 _totalTVL
) external override onlyPool(_pool) {
PremiaMiningStorage.Layout storage l = PremiaMiningStorage.layout();
_allocatePending(
_user,
_pool,
_isCallPool,
_userTVLOld,
_userTVLNew,
_totalTVL
);
uint256 reward = l.userInfo[_pool][_isCallPool][_user].reward;
l.userInfo[_pool][_isCallPool][_user].reward = 0;
_safePremiaTransfer(_user, reward);
emit Claim(_user, _pool, _isCallPool, reward);
}
/**
* @notice Trigger reward distribution by multiple pools
* @param account address whose rewards to claim
* @param pools list of pools to call
* @param isCall list of bools indicating whether each pool is call pool
*/
function multiClaim(
address account,
address[] calldata pools,
bool[] calldata isCall
) external {
require(pools.length == isCall.length);
for (uint256 i; i < pools.length; i++) {
IPoolIO(pools[i]).claimRewards(account, isCall[i]);
}
}
/**
* @notice Safe premia transfer function, just in case if rounding error causes pool to not have enough PREMIA.
* @param _to Address where to transfer the Premia
* @param _amount Amount of tokens to transfer
*/
function _safePremiaTransfer(address _to, uint256 _amount) internal {
IERC20 premia = IERC20(PREMIA);
uint256 premiaBal = premia.balanceOf(address(this));
if (_amount > premiaBal) {
premia.safeTransfer(_to, premiaBal);
} else {
premia.safeTransfer(_to, _amount);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { OwnableStorage } from './OwnableStorage.sol';
abstract contract OwnableInternal {
using OwnableStorage for OwnableStorage.Layout;
modifier onlyOwner() {
require(
msg.sender == OwnableStorage.layout().owner,
'Ownable: sender must be owner'
);
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IERC20Internal } from './IERC20Internal.sol';
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 is IERC20Internal {
/**
* @notice query the total minted token supply
* @return token supply
*/
function totalSupply() external view returns (uint256);
/**
* @notice query the token balance of given account
* @param account address to query
* @return token balance
*/
function balanceOf(address account) external view returns (uint256);
/**
* @notice query the allowance granted from given holder to given spender
* @param holder approver of allowance
* @param spender recipient of allowance
* @return token allowance
*/
function allowance(address holder, address spender)
external
view
returns (uint256);
/**
* @notice grant approval to spender to spend tokens
* @dev prefer ERC20Extended functions to avoid transaction-ordering vulnerability (see https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729)
* @param spender recipient of allowance
* @param amount quantity of tokens approved for spending
* @return success status (always true; otherwise function should revert)
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @notice transfer tokens to given recipient
* @param recipient beneficiary of token transfer
* @param amount quantity of tokens to transfer
* @return success status (always true; otherwise function should revert)
*/
function transfer(address recipient, uint256 amount)
external
returns (bool);
/**
* @notice transfer tokens to given recipient on behalf of given holder
* @param holder holder of tokens prior to transfer
* @param recipient beneficiary of token transfer
* @param amount quantity of tokens to transfer
* @return success status (always true; otherwise function should revert)
*/
function transferFrom(
address holder,
address recipient,
uint256 amount
) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IERC20 } from '../token/ERC20/IERC20.sol';
import { AddressUtils } from './AddressUtils.sol';
/**
* @title Safe ERC20 interaction library
* @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts/ (MIT license)
*/
library SafeERC20 {
using AddressUtils 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 safeApprove (like approve) should only be called when setting an initial allowance or when resetting it to zero; otherwise prefer safeIncreaseAllowance and safeDecreaseAllowance
*/
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 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
)
);
}
}
/**
* @notice send transaction data and check validity of return value, if present
* @param token ERC20 token interface
* @param data transaction data
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(
data,
'SafeERC20: low-level call failed'
);
if (returndata.length > 0) {
require(
abi.decode(returndata, (bool)),
'SafeERC20: ERC20 operation did not succeed'
);
}
}
}
// SPDX-License-Identifier: BUSL-1.1
// For further clarification please see https://license.premia.legal
pragma solidity ^0.8.0;
library PremiaMiningStorage {
bytes32 internal constant STORAGE_SLOT =
keccak256("premia.contracts.storage.PremiaMining");
// Info of each pool.
struct PoolInfo {
uint256 allocPoint; // How many allocation points assigned to this pool. PREMIA to distribute per block.
uint256 lastRewardBlock; // Last block number that PREMIA distribution occurs.
uint256 accPremiaPerShare; // Accumulated PREMIA per share, times 1e12. See below.
}
// Info of each user.
struct UserInfo {
uint256 reward; // Total allocated unclaimed reward
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of PREMIA
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accPremiaPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accPremiaPerShare` (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.
}
struct Layout {
// Total PREMIA left to distribute
uint256 premiaAvailable;
// Amount of premia per block distributed
uint256 premiaPerBlock;
// pool -> isCallPool -> PoolInfo
mapping(address => mapping(bool => PoolInfo)) poolInfo;
// pool -> isCallPool -> user -> UserInfo
mapping(address => mapping(bool => mapping(address => UserInfo))) userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 totalAllocPoint;
}
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.8.0;
import {PremiaMiningStorage} from "./PremiaMiningStorage.sol";
interface IPremiaMining {
function addPremiaRewards(uint256 _amount) external;
function premiaRewardsAvailable() external view returns (uint256);
function getTotalAllocationPoints() external view returns (uint256);
function getPoolInfo(address pool, bool isCallPool)
external
view
returns (PremiaMiningStorage.PoolInfo memory);
function getPremiaPerBlock() external view returns (uint256);
function addPool(address _pool, uint256 _allocPoints) external;
function setPoolAllocPoints(address _pool, uint256 _allocPoints) external;
function pendingPremia(
address _pool,
bool _isCallPool,
address _user
) external view returns (uint256);
function updatePool(
address _pool,
bool _isCallPool,
uint256 _totalTVL
) external;
function allocatePending(
address _user,
address _pool,
bool _isCallPool,
uint256 _userTVLOld,
uint256 _userTVLNew,
uint256 _totalTVL
) external;
function claim(
address _user,
address _pool,
bool _isCallPool,
uint256 _userTVLOld,
uint256 _userTVLNew,
uint256 _totalTVL
) external;
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.8.0;
interface IPoolIO {
function setDivestmentTimestamp(uint64 timestamp, bool isCallPool) external;
function deposit(uint256 amount, bool isCallPool) external payable;
function swapAndDeposit(
uint256 amount,
bool isCallPool,
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
bool isSushi
) external payable;
function withdraw(uint256 amount, bool isCallPool) external;
function reassign(uint256 tokenId, uint256 contractSize)
external
returns (
uint256 baseCost,
uint256 feeCost,
uint256 amountOut
);
function reassignBatch(
uint256[] calldata tokenIds,
uint256[] calldata contractSizes
)
external
returns (
uint256[] memory baseCosts,
uint256[] memory feeCosts,
uint256 amountOutCall,
uint256 amountOutPut
);
function withdrawAllAndReassignBatch(
bool isCallPool,
uint256[] calldata tokenIds,
uint256[] calldata contractSizes
)
external
returns (
uint256[] memory baseCosts,
uint256[] memory feeCosts,
uint256 amountOutCall,
uint256 amountOutPut
);
function withdrawFees()
external
returns (uint256 amountOutCall, uint256 amountOutPut);
function annihilate(uint256 tokenId, uint256 contractSize) external;
function claimRewards(bool isCallPool) external;
function claimRewards(address account, bool isCallPool) external;
function updateMiningPools() external;
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.8.0;
import {PoolStorage} from "./PoolStorage.sol";
interface IPoolView {
function getFeeReceiverAddress() external view returns (address);
function getPoolSettings()
external
view
returns (PoolStorage.PoolSettings memory);
function getTokenIds() external view returns (uint256[] memory);
function getCLevel64x64(bool isCall) external view returns (int128);
function getSteepness64x64() external view returns (int128);
function getPrice(uint256 timestamp) external view returns (int128);
function getParametersForTokenId(uint256 tokenId)
external
pure
returns (
PoolStorage.TokenType,
uint64,
int128
);
function getMinimumAmounts()
external
view
returns (uint256 minCallTokenAmount, uint256 minPutTokenAmount);
function getCapAmounts()
external
view
returns (uint256 callTokenCapAmount, uint256 putTokenCapAmount);
function getUserTVL(address user)
external
view
returns (uint256 underlyingTVL, uint256 baseTVL);
function getTotalTVL()
external
view
returns (uint256 underlyingTVL, uint256 baseTVL);
function getPremiaMining() external view returns (address);
function getDivestmentTimestamps(address account)
external
view
returns (
uint256 callDivestmentTimestamp,
uint256 putDivestmentTimestamp
);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library OwnableStorage {
struct Layout {
address owner;
}
bytes32 internal constant STORAGE_SLOT =
keccak256('solidstate.contracts.storage.Ownable');
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
function setOwner(Layout storage l, address owner) internal {
l.owner = owner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Partial ERC20 interface needed by internal functions
*/
interface IERC20Internal {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library AddressUtils {
function toString(address account) internal pure returns (string memory) {
bytes32 value = bytes32(uint256(uint160(account)));
bytes memory alphabet = '0123456789abcdef';
bytes memory chars = new bytes(42);
chars[0] = '0';
chars[1] = 'x';
for (uint256 i = 0; i < 20; i++) {
chars[2 + i * 2] = alphabet[uint8(value[i + 12] >> 4)];
chars[3 + i * 2] = alphabet[uint8(value[i + 12] & 0x0f)];
}
return string(chars);
}
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
function sendValue(address payable account, uint256 amount) internal {
(bool success, ) = account.call{ value: amount }('');
require(success, 'AddressUtils: failed to send value');
}
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionCall(target, data, 'AddressUtils: failed low-level call');
}
function functionCall(
address target,
bytes memory data,
string memory error
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, error);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
'AddressUtils: failed low-level call with value'
);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory error
) internal returns (bytes memory) {
require(
address(this).balance >= value,
'AddressUtils: insufficient balance for call'
);
return _functionCallWithValue(target, data, value, error);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory error
) private returns (bytes memory) {
require(
isContract(target),
'AddressUtils: function call to non-contract'
);
(bool success, bytes memory returnData) = target.call{ value: value }(
data
);
if (success) {
return returnData;
} else if (returnData.length > 0) {
assembly {
let returnData_size := mload(returnData)
revert(add(32, returnData), returnData_size)
}
} else {
revert(error);
}
}
}
// SPDX-License-Identifier: BUSL-1.1
// For further clarification please see https://license.premia.legal
pragma solidity ^0.8.0;
import {AggregatorInterface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorInterface.sol";
import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import {EnumerableSet, ERC1155EnumerableStorage} from "@solidstate/contracts/token/ERC1155/enumerable/ERC1155EnumerableStorage.sol";
import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol";
import {ABDKMath64x64Token} from "../libraries/ABDKMath64x64Token.sol";
import {OptionMath} from "../libraries/OptionMath.sol";
library PoolStorage {
using ABDKMath64x64 for int128;
using PoolStorage for PoolStorage.Layout;
enum TokenType {
UNDERLYING_FREE_LIQ,
BASE_FREE_LIQ,
UNDERLYING_RESERVED_LIQ,
BASE_RESERVED_LIQ,
LONG_CALL,
SHORT_CALL,
LONG_PUT,
SHORT_PUT
}
struct PoolSettings {
address underlying;
address base;
address underlyingOracle;
address baseOracle;
}
struct QuoteArgsInternal {
address feePayer; // address of the fee payer
uint64 maturity; // timestamp of option maturity
int128 strike64x64; // 64x64 fixed point representation of strike price
int128 spot64x64; // 64x64 fixed point representation of spot price
uint256 contractSize; // size of option contract
bool isCall; // true for call, false for put
}
struct QuoteResultInternal {
int128 baseCost64x64; // 64x64 fixed point representation of option cost denominated in underlying currency (without fee)
int128 feeCost64x64; // 64x64 fixed point representation of option fee cost denominated in underlying currency for call, or base currency for put
int128 cLevel64x64; // 64x64 fixed point representation of C-Level of Pool after purchase
int128 slippageCoefficient64x64; // 64x64 fixed point representation of slippage coefficient for given order size
}
struct BatchData {
uint256 eta;
uint256 totalPendingDeposits;
}
bytes32 internal constant STORAGE_SLOT =
keccak256("premia.contracts.storage.Pool");
uint256 private constant C_DECAY_BUFFER = 12 hours;
uint256 private constant C_DECAY_INTERVAL = 4 hours;
struct Layout {
// ERC20 token addresses
address base;
address underlying;
// AggregatorV3Interface oracle addresses
address baseOracle;
address underlyingOracle;
// token metadata
uint8 underlyingDecimals;
uint8 baseDecimals;
// minimum amounts
uint256 baseMinimum;
uint256 underlyingMinimum;
// deposit caps
uint256 basePoolCap;
uint256 underlyingPoolCap;
// market state
int128 steepness64x64;
int128 cLevelBase64x64;
int128 cLevelUnderlying64x64;
uint256 cLevelBaseUpdatedAt;
uint256 cLevelUnderlyingUpdatedAt;
uint256 updatedAt;
// User -> isCall -> depositedAt
mapping(address => mapping(bool => uint256)) depositedAt;
mapping(address => mapping(bool => uint256)) divestmentTimestamps;
// doubly linked list of free liquidity intervals
// isCall -> User -> User
mapping(bool => mapping(address => address)) liquidityQueueAscending;
mapping(bool => mapping(address => address)) liquidityQueueDescending;
// minimum resolution price bucket => price
mapping(uint256 => int128) bucketPrices64x64;
// sequence id (minimum resolution price bucket / 256) => price update sequence
mapping(uint256 => uint256) priceUpdateSequences;
// isCall -> batch data
mapping(bool => BatchData) nextDeposits;
// user -> batch timestamp -> isCall -> pending amount
mapping(address => mapping(uint256 => mapping(bool => uint256))) pendingDeposits;
EnumerableSet.UintSet tokenIds;
// user -> isCallPool -> total value locked of user (Used for liquidity mining)
mapping(address => mapping(bool => uint256)) userTVL;
// isCallPool -> total value locked
mapping(bool => uint256) totalTVL;
}
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
/**
* @notice calculate ERC1155 token id for given option parameters
* @param tokenType TokenType enum
* @param maturity timestamp of option maturity
* @param strike64x64 64x64 fixed point representation of strike price
* @return tokenId token id
*/
function formatTokenId(
TokenType tokenType,
uint64 maturity,
int128 strike64x64
) internal pure returns (uint256 tokenId) {
tokenId =
(uint256(tokenType) << 248) +
(uint256(maturity) << 128) +
uint256(int256(strike64x64));
}
/**
* @notice derive option maturity and strike price from ERC1155 token id
* @param tokenId token id
* @return tokenType TokenType enum
* @return maturity timestamp of option maturity
* @return strike64x64 option strike price
*/
function parseTokenId(uint256 tokenId)
internal
pure
returns (
TokenType tokenType,
uint64 maturity,
int128 strike64x64
)
{
assembly {
tokenType := shr(248, tokenId)
maturity := shr(128, tokenId)
strike64x64 := tokenId
}
}
function getTokenDecimals(Layout storage l, bool isCall)
internal
view
returns (uint8 decimals)
{
decimals = isCall ? l.underlyingDecimals : l.baseDecimals;
}
function totalFreeLiquiditySupply64x64(Layout storage l, bool isCall)
internal
view
returns (int128)
{
uint256 tokenId = formatTokenId(
isCall ? TokenType.UNDERLYING_FREE_LIQ : TokenType.BASE_FREE_LIQ,
0,
0
);
return
ABDKMath64x64Token.fromDecimals(
ERC1155EnumerableStorage.layout().totalSupply[tokenId] -
l.nextDeposits[isCall].totalPendingDeposits,
l.getTokenDecimals(isCall)
);
}
function getReinvestmentStatus(
Layout storage l,
address account,
bool isCallPool
) internal view returns (bool) {
uint256 timestamp = l.divestmentTimestamps[account][isCallPool];
return timestamp == 0 || timestamp > block.timestamp;
}
function addUnderwriter(
Layout storage l,
address account,
bool isCallPool
) internal {
require(account != address(0));
mapping(address => address) storage asc = l.liquidityQueueAscending[
isCallPool
];
mapping(address => address) storage desc = l.liquidityQueueDescending[
isCallPool
];
if (_isInQueue(account, asc, desc)) return;
address last = desc[address(0)];
asc[last] = account;
desc[account] = last;
desc[address(0)] = account;
}
function removeUnderwriter(
Layout storage l,
address account,
bool isCallPool
) internal {
require(account != address(0));
mapping(address => address) storage asc = l.liquidityQueueAscending[
isCallPool
];
mapping(address => address) storage desc = l.liquidityQueueDescending[
isCallPool
];
if (!_isInQueue(account, asc, desc)) return;
address prev = desc[account];
address next = asc[account];
asc[prev] = next;
desc[next] = prev;
delete asc[account];
delete desc[account];
}
function isInQueue(
Layout storage l,
address account,
bool isCallPool
) internal view returns (bool) {
mapping(address => address) storage asc = l.liquidityQueueAscending[
isCallPool
];
mapping(address => address) storage desc = l.liquidityQueueDescending[
isCallPool
];
return _isInQueue(account, asc, desc);
}
function _isInQueue(
address account,
mapping(address => address) storage asc,
mapping(address => address) storage desc
) private view returns (bool) {
return asc[account] != address(0) || desc[address(0)] == account;
}
function getCLevel(Layout storage l, bool isCall)
internal
view
returns (int128 cLevel64x64)
{
int128 oldCLevel64x64 = isCall
? l.cLevelUnderlying64x64
: l.cLevelBase64x64;
uint256 timeElapsed = block.timestamp -
(isCall ? l.cLevelUnderlyingUpdatedAt : l.cLevelBaseUpdatedAt);
// do not apply C decay if less than 24 hours have elapsed
if (timeElapsed > C_DECAY_BUFFER) {
timeElapsed -= C_DECAY_BUFFER;
} else {
return oldCLevel64x64;
}
int128 timeIntervalsElapsed64x64 = ABDKMath64x64.divu(
timeElapsed,
C_DECAY_INTERVAL
);
uint256 tokenId = formatTokenId(
isCall ? TokenType.UNDERLYING_FREE_LIQ : TokenType.BASE_FREE_LIQ,
0,
0
);
uint256 tvl = l.totalTVL[isCall];
int128 utilization = ABDKMath64x64.divu(
tvl -
(ERC1155EnumerableStorage.layout().totalSupply[tokenId] -
l.nextDeposits[isCall].totalPendingDeposits),
tvl
);
cLevel64x64 = OptionMath.calculateCLevelDecay(
OptionMath.CalculateCLevelDecayArgs(
timeIntervalsElapsed64x64,
oldCLevel64x64,
utilization,
0xb333333333333333, // 0.7
0xe666666666666666, // 0.9
0x10000000000000000, // 1.0
0x10000000000000000, // 1.0
0xe666666666666666, // 0.9
0x56fc2a2c515da32ea // 2e
)
);
}
function setCLevel(
Layout storage l,
int128 oldLiquidity64x64,
int128 newLiquidity64x64,
bool isCallPool
) internal returns (int128 cLevel64x64) {
cLevel64x64 = l.calculateCLevel(
oldLiquidity64x64,
newLiquidity64x64,
isCallPool
);
l.setCLevel(cLevel64x64, isCallPool);
}
function setCLevel(
Layout storage l,
int128 cLevel64x64,
bool isCallPool
) internal {
if (isCallPool) {
l.cLevelUnderlying64x64 = cLevel64x64;
l.cLevelUnderlyingUpdatedAt = block.timestamp;
} else {
l.cLevelBase64x64 = cLevel64x64;
l.cLevelBaseUpdatedAt = block.timestamp;
}
}
function calculateCLevel(
Layout storage l,
int128 oldLiquidity64x64,
int128 newLiquidity64x64,
bool isCallPool
) internal view returns (int128 cLevel64x64) {
cLevel64x64 = OptionMath.calculateCLevel(
l.getCLevel(isCallPool),
oldLiquidity64x64,
newLiquidity64x64,
l.steepness64x64
);
if (cLevel64x64 < 0xb333333333333333) {
cLevel64x64 = int128(0xb333333333333333); // 64x64 fixed point representation of 0.7
}
}
function setOracles(
Layout storage l,
address baseOracle,
address underlyingOracle
) internal {
require(
AggregatorV3Interface(baseOracle).decimals() ==
AggregatorV3Interface(underlyingOracle).decimals(),
"Pool: oracle decimals must match"
);
l.baseOracle = baseOracle;
l.underlyingOracle = underlyingOracle;
}
function fetchPriceUpdate(Layout storage l)
internal
view
returns (int128 price64x64)
{
int256 priceUnderlying = AggregatorInterface(l.underlyingOracle)
.latestAnswer();
int256 priceBase = AggregatorInterface(l.baseOracle).latestAnswer();
return ABDKMath64x64.divi(priceUnderlying, priceBase);
}
/**
* @notice set price update for current hourly bucket
* @param l storage layout struct
* @param timestamp timestamp to update
* @param price64x64 64x64 fixed point representation of price
*/
function setPriceUpdate(
Layout storage l,
uint256 timestamp,
int128 price64x64
) internal {
uint256 bucket = timestamp / (1 hours);
l.bucketPrices64x64[bucket] = price64x64;
l.priceUpdateSequences[bucket >> 8] += 1 << (255 - (bucket & 255));
}
/**
* @notice get price update for hourly bucket corresponding to given timestamp
* @param l storage layout struct
* @param timestamp timestamp to query
* @return 64x64 fixed point representation of price
*/
function getPriceUpdate(Layout storage l, uint256 timestamp)
internal
view
returns (int128)
{
return l.bucketPrices64x64[timestamp / (1 hours)];
}
/**
* @notice get first price update available following given timestamp
* @param l storage layout struct
* @param timestamp timestamp to query
* @return 64x64 fixed point representation of price
*/
function getPriceUpdateAfter(Layout storage l, uint256 timestamp)
internal
view
returns (int128)
{
// price updates are grouped into hourly buckets
uint256 bucket = timestamp / (1 hours);
// divide by 256 to get the index of the relevant price update sequence
uint256 sequenceId = bucket >> 8;
// get position within sequence relevant to current price update
uint256 offset = bucket & 255;
// shift to skip buckets from earlier in sequence
uint256 sequence = (l.priceUpdateSequences[sequenceId] << offset) >>
offset;
// iterate through future sequences until a price update is found
// sequence corresponding to current timestamp used as upper bound
uint256 currentPriceUpdateSequenceId = block.timestamp / (256 hours);
while (sequence == 0 && sequenceId <= currentPriceUpdateSequenceId) {
sequence = l.priceUpdateSequences[++sequenceId];
}
// if no price update is found (sequence == 0) function will return 0
// this should never occur, as each relevant external function triggers a price update
// the most significant bit of the sequence corresponds to the offset of the relevant bucket
uint256 msb;
for (uint256 i = 128; i > 0; i >>= 1) {
if (sequence >> i > 0) {
msb += i;
sequence >>= i;
}
}
return l.bucketPrices64x64[((sequenceId + 1) << 8) - msb - 1];
}
function fromBaseToUnderlyingDecimals(Layout storage l, uint256 value)
internal
view
returns (uint256)
{
int128 valueFixed64x64 = ABDKMath64x64Token.fromDecimals(
value,
l.baseDecimals
);
return
ABDKMath64x64Token.toDecimals(
valueFixed64x64,
l.underlyingDecimals
);
}
function fromUnderlyingToBaseDecimals(Layout storage l, uint256 value)
internal
view
returns (uint256)
{
int128 valueFixed64x64 = ABDKMath64x64Token.fromDecimals(
value,
l.underlyingDecimals
);
return ABDKMath64x64Token.toDecimals(valueFixed64x64, l.baseDecimals);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface AggregatorInterface {
function latestAnswer()
external
view
returns (
int256
);
function latestTimestamp()
external
view
returns (
uint256
);
function latestRound()
external
view
returns (
uint256
);
function getAnswer(
uint256 roundId
)
external
view
returns (
int256
);
function getTimestamp(
uint256 roundId
)
external
view
returns (
uint256
);
event AnswerUpdated(
int256 indexed current,
uint256 indexed roundId,
uint256 updatedAt
);
event NewRound(
uint256 indexed roundId,
address indexed startedBy,
uint256 startedAt
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface AggregatorV3Interface {
function decimals()
external
view
returns (
uint8
);
function description()
external
view
returns (
string memory
);
function version()
external
view
returns (
uint256
);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(
uint80 _roundId
)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { EnumerableSet } from '../../../utils/EnumerableSet.sol';
library ERC1155EnumerableStorage {
struct Layout {
mapping(uint256 => uint256) totalSupply;
mapping(uint256 => EnumerableSet.AddressSet) accountsByToken;
mapping(address => EnumerableSet.UintSet) tokensByAccount;
}
bytes32 internal constant STORAGE_SLOT =
keccak256('solidstate.contracts.storage.ERC1155Enumerable');
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
}
// SPDX-License-Identifier: BSD-4-Clause
/*
* ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^0.8.0;
/**
* Smart contract library of mathematical functions operating with signed
* 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is
* basically a simple fraction whose numerator is signed 128-bit integer and
* denominator is 2^64. As long as denominator is always the same, there is no
* need to store it, thus in Solidity signed 64.64-bit fixed point numbers are
* represented by int128 type holding only the numerator.
*/
library ABDKMath64x64 {
/*
* Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/*
* Maximum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Convert signed 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromInt (int256 x) internal pure returns (int128) {
unchecked {
require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
}
/**
* Convert signed 64.64 fixed point number into signed 64-bit integer number
* rounding down.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64-bit integer number
*/
function toInt (int128 x) internal pure returns (int64) {
unchecked {
return int64 (x >> 64);
}
}
/**
* Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromUInt (uint256 x) internal pure returns (int128) {
unchecked {
require (x <= 0x7FFFFFFFFFFFFFFF);
return int128 (int256 (x << 64));
}
}
/**
* Convert signed 64.64 fixed point number into unsigned 64-bit integer
* number rounding down. Revert on underflow.
*
* @param x signed 64.64-bit fixed point number
* @return unsigned 64-bit integer number
*/
function toUInt (int128 x) internal pure returns (uint64) {
unchecked {
require (x >= 0);
return uint64 (uint128 (x >> 64));
}
}
/**
* Convert signed 128.128 fixed point number into signed 64.64-bit fixed point
* number rounding down. Revert on overflow.
*
* @param x signed 128.128-bin fixed point number
* @return signed 64.64-bit fixed point number
*/
function from128x128 (int256 x) internal pure returns (int128) {
unchecked {
int256 result = x >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Convert signed 64.64 fixed point number into signed 128.128 fixed point
* number.
*
* @param x signed 64.64-bit fixed point number
* @return signed 128.128 fixed point number
*/
function to128x128 (int128 x) internal pure returns (int256) {
unchecked {
return int256 (x) << 64;
}
}
/**
* Calculate x + y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function add (int128 x, int128 y) internal pure returns (int128) {
unchecked {
int256 result = int256(x) + y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Calculate x - y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sub (int128 x, int128 y) internal pure returns (int128) {
unchecked {
int256 result = int256(x) - y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Calculate x * y rounding down. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function mul (int128 x, int128 y) internal pure returns (int128) {
unchecked {
int256 result = int256(x) * y >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Calculate x * y rounding towards zero, where x is signed 64.64 fixed point
* number and y is signed 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y signed 256-bit integer number
* @return signed 256-bit integer number
*/
function muli (int128 x, int256 y) internal pure returns (int256) {
unchecked {
if (x == MIN_64x64) {
require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&
y <= 0x1000000000000000000000000000000000000000000000000);
return -y << 63;
} else {
bool negativeResult = false;
if (x < 0) {
x = -x;
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint256 absoluteResult = mulu (x, uint256 (y));
if (negativeResult) {
require (absoluteResult <=
0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256 (absoluteResult);
}
}
}
}
/**
* Calculate x * y rounding down, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y unsigned 256-bit integer number
* @return unsigned 256-bit integer number
*/
function mulu (int128 x, uint256 y) internal pure returns (uint256) {
unchecked {
if (y == 0) return 0;
require (x >= 0);
uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = uint256 (int256 (x)) * (y >> 128);
require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
hi <<= 64;
require (hi <=
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);
return hi + lo;
}
}
/**
* Calculate x / y rounding towards zero. Revert on overflow or when y is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function div (int128 x, int128 y) internal pure returns (int128) {
unchecked {
require (y != 0);
int256 result = (int256 (x) << 64) / y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Calculate x / y rounding towards zero, where x and y are signed 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x signed 256-bit integer number
* @param y signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divi (int256 x, int256 y) internal pure returns (int128) {
unchecked {
require (y != 0);
bool negativeResult = false;
if (x < 0) {
x = -x; // We rely on overflow behavior here
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint128 absoluteResult = divuu (uint256 (x), uint256 (y));
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divu (uint256 x, uint256 y) internal pure returns (int128) {
unchecked {
require (y != 0);
uint128 result = divuu (x, y);
require (result <= uint128 (MAX_64x64));
return int128 (result);
}
}
/**
* Calculate -x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function neg (int128 x) internal pure returns (int128) {
unchecked {
require (x != MIN_64x64);
return -x;
}
}
/**
* Calculate |x|. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function abs (int128 x) internal pure returns (int128) {
unchecked {
require (x != MIN_64x64);
return x < 0 ? -x : x;
}
}
/**
* Calculate 1 / x rounding towards zero. Revert on overflow or when x is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function inv (int128 x) internal pure returns (int128) {
unchecked {
require (x != 0);
int256 result = int256 (0x100000000000000000000000000000000) / x;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function avg (int128 x, int128 y) internal pure returns (int128) {
unchecked {
return int128 ((int256 (x) + int256 (y)) >> 1);
}
}
/**
* Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.
* Revert on overflow or in case x * y is negative.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function gavg (int128 x, int128 y) internal pure returns (int128) {
unchecked {
int256 m = int256 (x) * int256 (y);
require (m >= 0);
require (m <
0x4000000000000000000000000000000000000000000000000000000000000000);
return int128 (sqrtu (uint256 (m)));
}
}
/**
* Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y uint256 value
* @return signed 64.64-bit fixed point number
*/
function pow (int128 x, uint256 y) internal pure returns (int128) {
unchecked {
bool negative = x < 0 && y & 1 == 1;
uint256 absX = uint128 (x < 0 ? -x : x);
uint256 absResult;
absResult = 0x100000000000000000000000000000000;
if (absX <= 0x10000000000000000) {
absX <<= 63;
while (y != 0) {
if (y & 0x1 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x2 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x4 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x8 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
y >>= 4;
}
absResult >>= 64;
} else {
uint256 absXShift = 63;
if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }
if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }
if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }
if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }
if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }
if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }
uint256 resultShift = 0;
while (y != 0) {
require (absXShift < 64);
if (y & 0x1 != 0) {
absResult = absResult * absX >> 127;
resultShift += absXShift;
if (absResult > 0x100000000000000000000000000000000) {
absResult >>= 1;
resultShift += 1;
}
}
absX = absX * absX >> 127;
absXShift <<= 1;
if (absX >= 0x100000000000000000000000000000000) {
absX >>= 1;
absXShift += 1;
}
y >>= 1;
}
require (resultShift < 64);
absResult >>= 64 - resultShift;
}
int256 result = negative ? -int256 (absResult) : int256 (absResult);
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* Calculate sqrt (x) rounding down. Revert if x < 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sqrt (int128 x) internal pure returns (int128) {
unchecked {
require (x >= 0);
return int128 (sqrtu (uint256 (int256 (x)) << 64));
}
}
/**
* Calculate binary logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function log_2 (int128 x) internal pure returns (int128) {
unchecked {
require (x > 0);
int256 msb = 0;
int256 xc = x;
if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 result = msb - 64 << 64;
uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);
for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * int256 (b);
}
return int128 (result);
}
}
/**
* Calculate natural logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function ln (int128 x) internal pure returns (int128) {
unchecked {
require (x > 0);
return int128 (int256 (
uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));
}
}
/**
* Calculate binary exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp_2 (int128 x) internal pure returns (int128) {
unchecked {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
uint256 result = 0x80000000000000000000000000000000;
if (x & 0x8000000000000000 > 0)
result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;
if (x & 0x4000000000000000 > 0)
result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;
if (x & 0x2000000000000000 > 0)
result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;
if (x & 0x1000000000000000 > 0)
result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;
if (x & 0x800000000000000 > 0)
result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;
if (x & 0x400000000000000 > 0)
result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;
if (x & 0x200000000000000 > 0)
result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;
if (x & 0x100000000000000 > 0)
result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;
if (x & 0x80000000000000 > 0)
result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;
if (x & 0x40000000000000 > 0)
result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;
if (x & 0x20000000000000 > 0)
result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;
if (x & 0x10000000000000 > 0)
result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;
if (x & 0x8000000000000 > 0)
result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;
if (x & 0x4000000000000 > 0)
result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;
if (x & 0x2000000000000 > 0)
result = result * 0x1000162E525EE054754457D5995292026 >> 128;
if (x & 0x1000000000000 > 0)
result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;
if (x & 0x800000000000 > 0)
result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;
if (x & 0x400000000000 > 0)
result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;
if (x & 0x200000000000 > 0)
result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;
if (x & 0x100000000000 > 0)
result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;
if (x & 0x80000000000 > 0)
result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;
if (x & 0x40000000000 > 0)
result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;
if (x & 0x20000000000 > 0)
result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;
if (x & 0x10000000000 > 0)
result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;
if (x & 0x8000000000 > 0)
result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;
if (x & 0x4000000000 > 0)
result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;
if (x & 0x2000000000 > 0)
result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;
if (x & 0x1000000000 > 0)
result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;
if (x & 0x800000000 > 0)
result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;
if (x & 0x400000000 > 0)
result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;
if (x & 0x200000000 > 0)
result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;
if (x & 0x100000000 > 0)
result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;
if (x & 0x80000000 > 0)
result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;
if (x & 0x40000000 > 0)
result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;
if (x & 0x20000000 > 0)
result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;
if (x & 0x10000000 > 0)
result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;
if (x & 0x8000000 > 0)
result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;
if (x & 0x4000000 > 0)
result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;
if (x & 0x2000000 > 0)
result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;
if (x & 0x1000000 > 0)
result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;
if (x & 0x800000 > 0)
result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;
if (x & 0x400000 > 0)
result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;
if (x & 0x200000 > 0)
result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;
if (x & 0x100000 > 0)
result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;
if (x & 0x80000 > 0)
result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;
if (x & 0x40000 > 0)
result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;
if (x & 0x20000 > 0)
result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;
if (x & 0x10000 > 0)
result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;
if (x & 0x8000 > 0)
result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;
if (x & 0x4000 > 0)
result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;
if (x & 0x2000 > 0)
result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;
if (x & 0x1000 > 0)
result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;
if (x & 0x800 > 0)
result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;
if (x & 0x400 > 0)
result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;
if (x & 0x200 > 0)
result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;
if (x & 0x100 > 0)
result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;
if (x & 0x80 > 0)
result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;
if (x & 0x40 > 0)
result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;
if (x & 0x20 > 0)
result = result * 0x100000000000000162E42FEFA39EF366F >> 128;
if (x & 0x10 > 0)
result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;
if (x & 0x8 > 0)
result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;
if (x & 0x4 > 0)
result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;
if (x & 0x2 > 0)
result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;
if (x & 0x1 > 0)
result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;
result >>= uint256 (int256 (63 - (x >> 64)));
require (result <= uint256 (int256 (MAX_64x64)));
return int128 (int256 (result));
}
}
/**
* Calculate natural exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp (int128 x) internal pure returns (int128) {
unchecked {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
return exp_2 (
int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return unsigned 64.64-bit fixed point number
*/
function divuu (uint256 x, uint256 y) private pure returns (uint128) {
unchecked {
require (y != 0);
uint256 result;
if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
result = (x << 64) / y;
else {
uint256 msb = 192;
uint256 xc = x >> 192;
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 hi = result * (y >> 128);
uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 xh = x >> 192;
uint256 xl = x << 64;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
lo = hi << 128;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
assert (xh == hi >> 128);
result += xl / y;
}
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint128 (result);
}
}
/**
* Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
* number.
*
* @param x unsigned 256-bit integer number
* @return unsigned 128-bit integer number
*/
function sqrtu (uint256 x) private pure returns (uint128) {
unchecked {
if (x == 0) return 0;
else {
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }
if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }
if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }
if (xx >= 0x10000) { xx >>= 16; r <<= 8; }
if (xx >= 0x100) { xx >>= 8; r <<= 4; }
if (xx >= 0x10) { xx >>= 4; r <<= 2; }
if (xx >= 0x8) { r <<= 1; }
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return uint128 (r < r1 ? r : r1);
}
}
}
}
// SPDX-License-Identifier: BUSL-1.1
// For further clarification please see https://license.premia.legal
pragma solidity ^0.8.0;
import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol";
library ABDKMath64x64Token {
using ABDKMath64x64 for int128;
/**
* @notice convert 64x64 fixed point representation of token amount to decimal
* @param value64x64 64x64 fixed point representation of token amount
* @param decimals token display decimals
* @return value decimal representation of token amount
*/
function toDecimals(int128 value64x64, uint8 decimals)
internal
pure
returns (uint256 value)
{
value = value64x64.mulu(10**decimals);
}
/**
* @notice convert decimal representation of token amount to 64x64 fixed point
* @param value decimal representation of token amount
* @param decimals token display decimals
* @return value64x64 64x64 fixed point representation of token amount
*/
function fromDecimals(uint256 value, uint8 decimals)
internal
pure
returns (int128 value64x64)
{
value64x64 = ABDKMath64x64.divu(value, 10**decimals);
}
/**
* @notice convert 64x64 fixed point representation of token amount to wei (18 decimals)
* @param value64x64 64x64 fixed point representation of token amount
* @return value wei representation of token amount
*/
function toWei(int128 value64x64) internal pure returns (uint256 value) {
value = toDecimals(value64x64, 18);
}
/**
* @notice convert wei representation (18 decimals) of token amount to 64x64 fixed point
* @param value wei representation of token amount
* @return value64x64 64x64 fixed point representation of token amount
*/
function fromWei(uint256 value) internal pure returns (int128 value64x64) {
value64x64 = fromDecimals(value, 18);
}
}
// SPDX-License-Identifier: BUSL-1.1
// For further clarification please see https://license.premia.legal
pragma solidity ^0.8.0;
import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol";
library OptionMath {
using ABDKMath64x64 for int128;
struct QuoteArgs {
int128 varianceAnnualized64x64; // 64x64 fixed point representation of annualized variance
int128 strike64x64; // 64x64 fixed point representation of strike price
int128 spot64x64; // 64x64 fixed point representation of spot price
int128 timeToMaturity64x64; // 64x64 fixed point representation of duration of option contract (in years)
int128 oldCLevel64x64; // 64x64 fixed point representation of C-Level of Pool before purchase
int128 oldPoolState; // 64x64 fixed point representation of current state of the pool
int128 newPoolState; // 64x64 fixed point representation of state of the pool after trade
int128 steepness64x64; // 64x64 fixed point representation of Pool state delta multiplier
int128 minAPY64x64; // 64x64 fixed point representation of minimum APY for capital locked up to underwrite options
bool isCall; // whether to price "call" or "put" option
}
struct CalculateCLevelDecayArgs {
int128 timeIntervalsElapsed64x64; // 64x64 fixed point representation of quantity of discrete arbitrary intervals elapsed since last update
int128 oldCLevel64x64; // 64x64 fixed point representation of C-Level prior to accounting for decay
int128 utilization64x64; // 64x64 fixed point representation of pool capital utilization rate
int128 utilizationLowerBound64x64;
int128 utilizationUpperBound64x64;
int128 cLevelLowerBound64x64;
int128 cLevelUpperBound64x64;
int128 cConvergenceULowerBound64x64;
int128 cConvergenceUUpperBound64x64;
}
// 64x64 fixed point integer constants
int128 internal constant ONE_64x64 = 0x10000000000000000;
int128 internal constant THREE_64x64 = 0x30000000000000000;
// 64x64 fixed point constants used in Choudhury’s approximation of the Black-Scholes CDF
int128 private constant CDF_CONST_0 = 0x09109f285df452394; // 2260 / 3989
int128 private constant CDF_CONST_1 = 0x19abac0ea1da65036; // 6400 / 3989
int128 private constant CDF_CONST_2 = 0x0d3c84b78b749bd6b; // 3300 / 3989
/**
* @notice recalculate C-Level based on change in liquidity
* @param initialCLevel64x64 64x64 fixed point representation of C-Level of Pool before update
* @param oldPoolState64x64 64x64 fixed point representation of liquidity in pool before update
* @param newPoolState64x64 64x64 fixed point representation of liquidity in pool after update
* @param steepness64x64 64x64 fixed point representation of steepness coefficient
* @return 64x64 fixed point representation of new C-Level
*/
function calculateCLevel(
int128 initialCLevel64x64,
int128 oldPoolState64x64,
int128 newPoolState64x64,
int128 steepness64x64
) external pure returns (int128) {
return
newPoolState64x64
.sub(oldPoolState64x64)
.div(
oldPoolState64x64 > newPoolState64x64
? oldPoolState64x64
: newPoolState64x64
)
.mul(steepness64x64)
.neg()
.exp()
.mul(initialCLevel64x64);
}
/**
* @notice calculate the price of an option using the Premia Finance model
* @param args arguments of quotePrice
* @return premiaPrice64x64 64x64 fixed point representation of Premia option price
* @return cLevel64x64 64x64 fixed point representation of C-Level of Pool after purchase
*/
function quotePrice(QuoteArgs memory args)
external
pure
returns (
int128 premiaPrice64x64,
int128 cLevel64x64,
int128 slippageCoefficient64x64
)
{
int128 deltaPoolState64x64 = args
.newPoolState
.sub(args.oldPoolState)
.div(args.oldPoolState)
.mul(args.steepness64x64);
int128 tradingDelta64x64 = deltaPoolState64x64.neg().exp();
int128 blackScholesPrice64x64 = _blackScholesPrice(
args.varianceAnnualized64x64,
args.strike64x64,
args.spot64x64,
args.timeToMaturity64x64,
args.isCall
);
cLevel64x64 = tradingDelta64x64.mul(args.oldCLevel64x64);
slippageCoefficient64x64 = ONE_64x64.sub(tradingDelta64x64).div(
deltaPoolState64x64
);
premiaPrice64x64 = blackScholesPrice64x64.mul(cLevel64x64).mul(
slippageCoefficient64x64
);
int128 intrinsicValue64x64;
if (args.isCall && args.strike64x64 < args.spot64x64) {
intrinsicValue64x64 = args.spot64x64.sub(args.strike64x64);
} else if (!args.isCall && args.strike64x64 > args.spot64x64) {
intrinsicValue64x64 = args.strike64x64.sub(args.spot64x64);
}
int128 collateralValue64x64 = args.isCall
? args.spot64x64
: args.strike64x64;
int128 minPrice64x64 = intrinsicValue64x64.add(
collateralValue64x64.mul(args.minAPY64x64).mul(
args.timeToMaturity64x64
)
);
if (minPrice64x64 > premiaPrice64x64) {
premiaPrice64x64 = minPrice64x64;
}
}
/**
* @notice calculate the decay of C-Level based on heat diffusion function
* @param args structured CalculateCLevelDecayArgs
* @return cLevelDecayed64x64 C-Level after accounting for decay
*/
function calculateCLevelDecay(CalculateCLevelDecayArgs memory args)
external
pure
returns (int128 cLevelDecayed64x64)
{
int128 convFHighU64x64 = (args.utilization64x64 >=
args.utilizationUpperBound64x64 &&
args.oldCLevel64x64 <= args.cLevelLowerBound64x64)
? ONE_64x64
: int128(0);
int128 convFLowU64x64 = (args.utilization64x64 <=
args.utilizationLowerBound64x64 &&
args.oldCLevel64x64 >= args.cLevelUpperBound64x64)
? ONE_64x64
: int128(0);
cLevelDecayed64x64 = args
.oldCLevel64x64
.sub(args.cConvergenceULowerBound64x64.mul(convFLowU64x64))
.sub(args.cConvergenceUUpperBound64x64.mul(convFHighU64x64))
.mul(
convFLowU64x64
.mul(ONE_64x64.sub(args.utilization64x64))
.add(convFHighU64x64.mul(args.utilization64x64))
.mul(args.timeIntervalsElapsed64x64)
.neg()
.exp()
)
.add(
args.cConvergenceULowerBound64x64.mul(convFLowU64x64).add(
args.cConvergenceUUpperBound64x64.mul(convFHighU64x64)
)
);
}
/**
* @notice calculate the exponential decay coefficient for a given interval
* @param oldTimestamp timestamp of previous update
* @param newTimestamp current timestamp
* @return 64x64 fixed point representation of exponential decay coefficient
*/
function _decay(uint256 oldTimestamp, uint256 newTimestamp)
internal
pure
returns (int128)
{
return
ONE_64x64.sub(
(-ABDKMath64x64.divu(newTimestamp - oldTimestamp, 7 days)).exp()
);
}
/**
* @notice calculate Choudhury’s approximation of the Black-Scholes CDF
* @param input64x64 64x64 fixed point representation of random variable
* @return 64x64 fixed point representation of the approximated CDF of x
*/
function _N(int128 input64x64) internal pure returns (int128) {
// squaring via mul is cheaper than via pow
int128 inputSquared64x64 = input64x64.mul(input64x64);
int128 value64x64 = (-inputSquared64x64 >> 1).exp().div(
CDF_CONST_0.add(CDF_CONST_1.mul(input64x64.abs())).add(
CDF_CONST_2.mul(inputSquared64x64.add(THREE_64x64).sqrt())
)
);
return input64x64 > 0 ? ONE_64x64.sub(value64x64) : value64x64;
}
/**
* @notice calculate the price of an option using the Black-Scholes model
* @param varianceAnnualized64x64 64x64 fixed point representation of annualized variance
* @param strike64x64 64x64 fixed point representation of strike price
* @param spot64x64 64x64 fixed point representation of spot price
* @param timeToMaturity64x64 64x64 fixed point representation of duration of option contract (in years)
* @param isCall whether to price "call" or "put" option
* @return 64x64 fixed point representation of Black-Scholes option price
*/
function _blackScholesPrice(
int128 varianceAnnualized64x64,
int128 strike64x64,
int128 spot64x64,
int128 timeToMaturity64x64,
bool isCall
) internal pure returns (int128) {
int128 cumulativeVariance64x64 = timeToMaturity64x64.mul(
varianceAnnualized64x64
);
int128 cumulativeVarianceSqrt64x64 = cumulativeVariance64x64.sqrt();
int128 d1_64x64 = spot64x64
.div(strike64x64)
.ln()
.add(cumulativeVariance64x64 >> 1)
.div(cumulativeVarianceSqrt64x64);
int128 d2_64x64 = d1_64x64.sub(cumulativeVarianceSqrt64x64);
if (isCall) {
return
spot64x64.mul(_N(d1_64x64)).sub(strike64x64.mul(_N(d2_64x64)));
} else {
return
-spot64x64.mul(_N(-d1_64x64)).sub(
strike64x64.mul(_N(-d2_64x64))
);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Set implementation with enumeration functions
* @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts (MIT license)
*/
library EnumerableSet {
struct Set {
bytes32[] _values;
// 1-indexed to allow 0 to signify nonexistence
mapping(bytes32 => uint256) _indexes;
}
struct Bytes32Set {
Set _inner;
}
struct AddressSet {
Set _inner;
}
struct UintSet {
Set _inner;
}
function at(Bytes32Set storage set, uint256 index)
internal
view
returns (bytes32)
{
return _at(set._inner, index);
}
function at(AddressSet storage set, uint256 index)
internal
view
returns (address)
{
return address(uint160(uint256(_at(set._inner, index))));
}
function at(UintSet storage set, uint256 index)
internal
view
returns (uint256)
{
return uint256(_at(set._inner, index));
}
function contains(Bytes32Set storage set, bytes32 value)
internal
view
returns (bool)
{
return _contains(set._inner, value);
}
function contains(AddressSet storage set, address value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
function contains(UintSet storage set, uint256 value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(value));
}
function indexOf(Bytes32Set storage set, bytes32 value)
internal
view
returns (uint256)
{
return _indexOf(set._inner, value);
}
function indexOf(AddressSet storage set, address value)
internal
view
returns (uint256)
{
return _indexOf(set._inner, bytes32(uint256(uint160(value))));
}
function indexOf(UintSet storage set, uint256 value)
internal
view
returns (uint256)
{
return _indexOf(set._inner, bytes32(value));
}
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function add(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
return _add(set._inner, value);
}
function add(AddressSet storage set, address value)
internal
returns (bool)
{
return _add(set._inner, bytes32(uint256(uint160(value))));
}
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
function remove(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
return _remove(set._inner, value);
}
function remove(AddressSet storage set, address value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
function remove(UintSet storage set, uint256 value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(value));
}
function _at(Set storage set, uint256 index)
private
view
returns (bytes32)
{
require(
set._values.length > index,
'EnumerableSet: index out of bounds'
);
return set._values[index];
}
function _contains(Set storage set, bytes32 value)
private
view
returns (bool)
{
return set._indexes[value] != 0;
}
function _indexOf(Set storage set, bytes32 value)
private
view
returns (uint256)
{
unchecked {
return set._indexes[value] - 1;
}
}
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
function _remove(Set storage set, bytes32 value) private returns (bool) {
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
uint256 index = valueIndex - 1;
bytes32 last = set._values[set._values.length - 1];
// move last value to now-vacant index
set._values[index] = last;
set._indexes[last] = index + 1;
// clear last index
set._values.pop();
delete set._indexes[value];
return true;
} else {
return false;
}
}
} | * @notice Allocate pending rewards to a user. Only callable by the option pool @param _user User for whom allocate the rewards @param _pool Address of option pool contract @param _isCallPool True if for call option pool, False if for put option pool @param _userTVLOld Total amount of tokens deposited in the option pool by user before the allocation update @param _userTVLNew Total amount of tokens deposited in the option pool by user after the allocation update @param _totalTVL Total amount of tokens deposited in the option pool/ | function allocatePending(
address _user,
address _pool,
bool _isCallPool,
uint256 _userTVLOld,
uint256 _userTVLNew,
uint256 _totalTVL
) external override onlyPool(_pool) {
_allocatePending(
_user,
_pool,
_isCallPool,
_userTVLOld,
_userTVLNew,
_totalTVL
);
}
| 5,915,387 | [
1,
27483,
4634,
283,
6397,
358,
279,
729,
18,
5098,
4140,
635,
326,
1456,
2845,
225,
389,
1355,
2177,
364,
600,
362,
10101,
326,
283,
6397,
225,
389,
6011,
5267,
434,
1456,
2845,
6835,
225,
389,
291,
1477,
2864,
1053,
309,
364,
745,
1456,
2845,
16,
1083,
309,
364,
1378,
1456,
2845,
225,
389,
1355,
15579,
1502,
1236,
10710,
3844,
434,
2430,
443,
1724,
329,
316,
326,
1456,
2845,
635,
729,
1865,
326,
13481,
1089,
225,
389,
1355,
15579,
48,
1908,
10710,
3844,
434,
2430,
443,
1724,
329,
316,
326,
1456,
2845,
635,
729,
1839,
326,
13481,
1089,
225,
389,
4963,
15579,
48,
10710,
3844,
434,
2430,
443,
1724,
329,
316,
326,
1456,
2845,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
10101,
8579,
12,
203,
3639,
1758,
389,
1355,
16,
203,
3639,
1758,
389,
6011,
16,
203,
3639,
1426,
389,
291,
1477,
2864,
16,
203,
3639,
2254,
5034,
389,
1355,
15579,
1502,
1236,
16,
203,
3639,
2254,
5034,
389,
1355,
15579,
48,
1908,
16,
203,
3639,
2254,
5034,
389,
4963,
15579,
48,
203,
565,
262,
3903,
3849,
1338,
2864,
24899,
6011,
13,
288,
203,
3639,
389,
16247,
8579,
12,
203,
5411,
389,
1355,
16,
203,
5411,
389,
6011,
16,
203,
5411,
389,
291,
1477,
2864,
16,
203,
5411,
389,
1355,
15579,
1502,
1236,
16,
203,
5411,
389,
1355,
15579,
48,
1908,
16,
203,
5411,
389,
4963,
15579,
48,
203,
3639,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/4/0xdAD4035bf7178ae9e9b53e6Bb7319Cb6D912fFDe/sources/contracts/TestUniswapFlashSwap.sol | require(pair != address(0), "!pair"); pair2 = IUniswapV2Factory(FACTORY).getPair(t1, t2);, address pair2address token0 = IUniswapV2Pair(pair).token0(); address token1 = IUniswapV2Pair(pair).token1();uint amount0Out = t1 == token0 ? _amount : 0; uint amount1Out = t1 == token1 ? _amount : 0; need to pass some data to trigger uniswapV2Call uint amount0Out =1000;*1000000000000000000; bytes memory data = abi.encode(t1, amount0Out); IUniswapV2Pair(pair).swap(amount0Out, 0, address(this), data); | function testFlashSwap() external view returns(address pair) {
pair = IUniswapV2Factory(FACTORY).getPair(t2, t1);
address private constant t1 = 0x8AE018880cC2ff55f45f2449aFe84230b32dd220 ;
address private constant FACTORY = 0xc35DADB65012eC5796536bD9864eD8773aBc74C4;
}
| 12,318,832 | [
1,
6528,
12,
6017,
480,
1758,
12,
20,
3631,
17528,
6017,
8863,
225,
3082,
22,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
12,
16193,
2934,
588,
4154,
12,
88,
21,
16,
268,
22,
1769,
16,
1758,
3082,
22,
2867,
1147,
20,
273,
467,
984,
291,
91,
438,
58,
22,
4154,
12,
6017,
2934,
2316,
20,
5621,
1758,
1147,
21,
273,
467,
984,
291,
91,
438,
58,
22,
4154,
12,
6017,
2934,
2316,
21,
5621,
11890,
3844,
20,
1182,
273,
268,
21,
422,
1147,
20,
692,
389,
8949,
294,
374,
31,
2254,
3844,
21,
1182,
273,
268,
21,
422,
1147,
21,
692,
389,
8949,
294,
374,
31,
1608,
358,
1342,
2690,
501,
358,
3080,
640,
291,
91,
438,
58,
22,
1477,
565,
2254,
3844,
20,
1182,
273,
18088,
31,
21,
12648,
2787,
9449,
31,
565,
1731,
3778,
501,
273,
24126,
18,
3015,
12,
88,
21,
16,
3844,
20,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
225,
445,
1842,
11353,
12521,
1435,
3903,
1476,
1135,
12,
2867,
3082,
13,
288,
203,
4202,
203,
282,
3082,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
12,
16193,
2934,
588,
4154,
12,
88,
22,
16,
268,
21,
1769,
203,
203,
377,
203,
203,
377,
203,
203,
225,
1758,
3238,
5381,
268,
21,
273,
374,
92,
28,
16985,
1611,
5482,
3672,
71,
39,
22,
1403,
2539,
74,
7950,
74,
3247,
7616,
69,
2954,
5193,
29157,
70,
1578,
449,
27246,
274,
203,
225,
1758,
3238,
5381,
26724,
3964,
273,
374,
6511,
4763,
40,
1880,
38,
26,
9172,
22,
73,
39,
25,
7235,
9222,
5718,
70,
40,
10689,
1105,
73,
40,
28,
4700,
23,
69,
38,
71,
5608,
39,
24,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "../library/SafeRatioMath.sol";
import "../library/Ownable.sol";
import "../library/ERC20Permit.sol";
import "./GovernanceToken.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
contract veDF is Initializable, Ownable, ReentrancyGuardUpgradeable, GovernanceToken, ERC20Permit {
using SafeRatioMath for uint256;
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
/// @dev Calc the base value
uint256 internal constant BASE = 1e18;
/// @dev Calc the double of the base value
// uint256 internal constant DOUBLE_BASE = 1e36;
/// @dev Min lock step (seconds of a week).
uint256 internal constant MIN_STEP = 1 weeks;
/// @dev Max lock step (seconds of 208 week).
uint256 internal constant MAX_STEP = 4 * 52 weeks;
/// @dev StakedDF address.
IERC20Upgradeable internal stakedDF;
/// @dev veDF total amount.
uint96 public totalSupply;
/// @dev Information of the locker
struct Locker {
uint32 dueTime;
uint32 duration;
uint96 amount;
}
/// @dev veDF holder's lock information
mapping(address => Locker) internal lockers;
/// @dev EnumerableSet of minters
EnumerableSetUpgradeable.AddressSet internal minters;
/// @dev Emitted when `lockers` is changed.
event Lock(
address caller,
address recipient,
uint256 underlyingAmount,
uint96 tokenAmount,
uint32 dueTime,
uint32 duration
);
/// @dev Emitted when `lockers` is removed.
event UnLock(
address caller,
address from,
uint256 underlyingAmount,
uint96 tokenAmount
);
/// @dev Emitted when `minter` is added as `minter`.
event MinterAdded(address minter);
/// @dev Emitted when `minter` is removed from `minters`.
event MinterRemoved(address minter);
/**
* @notice Only for the implementation contract, as for the proxy pattern,
* should call `initialize()` separately.
* @param _stakedDF Staked DF token address.
*/
constructor(IERC20Upgradeable _stakedDF) public {
initialize(_stakedDF);
}
/**
* @dev Initialize contract to set some configs.
* @param _stakedDF Staked DF token address.
*/
function initialize(IERC20Upgradeable _stakedDF) public initializer {
__Ownable_init();
__ReentrancyGuard_init();
stakedDF = _stakedDF;
}
/**
* @dev Duration should be 1. within the range of (0, max_step]
* 2. integral multiple of min_step
* @param _dur Lock duration,in seconds.
*/
modifier isDurationValid(uint256 _dur) {
require(
_dur > 0 && _dur <= MAX_STEP,
"duration is not valid."
);
_;
}
/**
* @dev Check if the due time is valid.
* @param _due Due greenwich timestamp.
*/
modifier isDueTimeValid(uint256 _due) {
require(_due > block.timestamp, "due time is not valid.");
_;
}
/*********************************/
/******** Owner functions ********/
/*********************************/
/**
* @dev Throws if called by any account other than the minters.
*/
modifier onlyMinter() {
require(minters.contains(msg.sender), "caller is not minter.");
_;
}
/**
* @notice Add `minter` into minters.
* If `minter` have not been a minter, emits a `MinterAdded` event.
*
* @param _minter The minter to add
*
* Requirements:
* - the caller must be `owner`.
*/
function _addMinter(address _minter) external onlyOwner {
require(_minter != address(0), "_minter not accepted zero address.");
if (minters.add(_minter)) {
emit MinterAdded(_minter);
}
}
/**
* @notice Remove `minter` from minters.
* If `minter` is a minter, emits a `MinterRemoved` event.
*
* @param _minter The minter to remove
*
* Requirements:
* - the caller must be `owner`.
*/
function _removeMinter(address _minter) external onlyOwner {
require(_minter != address(0), "invalid minter address.");
if (minters.remove(_minter)) {
emit MinterRemoved(_minter);
}
}
/*********************************/
/******** Security Check *********/
/*********************************/
/**
* @notice Ensure this is the veDF contract.
* @return The return value is always true.
*/
function isvDF() external pure returns (bool) {
return true;
}
/*********************************/
/****** Internal functions *******/
/*********************************/
/** @dev Mint balance in `_amount` to `_account`
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* @param _account Account address, cannot be zero address.
* @param _amount veDF amount, cannot be zero.
*/
function _mint(address _account, uint96 _amount) internal {
require(_account != address(0), "not allowed to mint to zero address.");
totalSupply = add96(totalSupply, _amount, "total supply overflows.");
balances[_account] = add96(
balances[_account],
_amount,
"amount overflows."
);
emit Transfer(address(0), _account, _amount);
_moveDelegates(delegates[address(0)], delegates[_account], _amount);
}
/**
* @dev Burn balance in `_amount` from `_account`
*
* Emits a {Transfer} event with `to` set to zero address.
*
* Requirements
*
* @param _account Account address, cannot be zero address.
* @param _amount veDF amount, must have at least balance in `_amount`.
*/
function _burn(address _account, uint96 _amount) internal {
require(_account != address(0), "_burn: Burn from the zero address!");
balances[_account] = sub96(
balances[_account],
_amount,
"burn amount exceeds balance."
);
totalSupply = sub96(totalSupply, _amount, "total supply underflows.");
emit Transfer(_account, address(0), _amount);
_moveDelegates(delegates[_account], delegates[address(0)], _amount);
}
/**
* @dev Burn balance in `_amount` on behalf of `from` account
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* @param _from Account address.
* @param _caller Caller address, the caller must be allowed at least balance in `_amount` from `from` account.
* @param _amount veDF amount, must have at least balance in `_amount`.
*/
function _burnFrom(
address _from,
address _caller,
uint96 _amount
) internal {
if (_caller != _from) {
uint96 _spenderAllowance = allowances[_from][_caller];
if (_spenderAllowance != uint96(-1)) {
uint96 _newAllowance = sub96(
_spenderAllowance,
_amount,
"burn amount exceeds spender's allowance."
);
allowances[_from][_caller] = _newAllowance;
emit Approval(_from, _caller, _newAllowance);
}
}
_burn(_from, _amount);
}
function _approveERC20(address _owner, address _spender, uint256 _rawAmount) internal override {
uint96 _amount;
if (_rawAmount == uint256(-1)) {
_amount = uint96(-1);
} else {
_amount = safe96(_rawAmount, "veDF::approve: amount exceeds 96 bits");
}
allowances[_owner][_spender] = _amount;
emit Approval(_owner, _spender, _amount);
}
/**
* @dev Calculate weight rate on duration.
* @param _d Duration, in seconds.
* @param _multipier weight rate.
*/
function _weightedRate(uint256 _d)
internal
pure
returns (uint256 _multipier)
{
// Linear_rate = _d / MAX_STEP
// curve_rate = (1 + Linear_rate) ^ 2 * Linear_rate
// uint256 _l = (_d * BASE) / MAX_STEP;
// _multipier = (((BASE + _l)**2) * _l) / DOUBLE_BASE;
_multipier = (_d * BASE) / MAX_STEP;
}
/**
* @dev Calculate weight rate on duration.
* @param _amount Staked DF token amount.
* @param _duration Duration, in seconds.
* @return veDF amount.
*/
function _weightedExchange(uint256 _amount, uint256 _duration)
internal
pure
returns (uint96)
{
return
safe96(
_amount.rmul(_weightedRate(_duration)),
"weighted rate overflow."
);
}
/**
* @notice Lock Staked DF and harvest veDF.
* @dev Create lock-up information and mint veDF on lock-up amount and duration.
* @param _caller Caller address.
* @param _recipient veDF recipient address.
* @param _amount Staked DF token amount.
* @param _duration Duration, in seconds.
* @param _minted The amount of veDF minted.
*/
function _lock(
address _caller,
address _recipient,
uint256 _amount,
uint256 _duration
) internal isDurationValid(_duration) returns (uint96 _minted) {
require(_amount > 0, "not allowed zero amount.");
Locker storage _locker = lockers[_recipient];
require(
_locker.dueTime == 0,
"due time refuses to create a new lock."
);
_minted = _weightedExchange(_amount, _duration);
_locker.dueTime = safe32(
(block.timestamp).add(_duration),
"due time overflow."
);
_locker.duration = safe32(_duration, "duration overflow.");
_locker.amount = safe96(_amount, "locked amount overflow.");
emit Lock(
_caller,
_recipient,
_amount,
_minted,
_locker.dueTime,
_locker.duration
);
_mint(_recipient, _minted);
}
/**
* @notice Unlock Staked DF and burn veDF.
* @dev Burn veDF and clear lock information.
* @param _caller Caller address.
* @param _from veDF holder's address.
* @param _burned The amount of veDF burned.
*/
function _unLock(address _caller, address _from)
internal
returns (uint96 _burned)
{
Locker storage _locker = lockers[_from];
require(
uint256(_locker.dueTime) < block.timestamp,
"due time not meeted."
);
_burned = balances[_from];
_burnFrom(_from, _caller, _burned);
uint256 _amount = uint256(_locker.amount);
delete lockers[_from];
emit UnLock(_caller, _from, _amount, _burned);
}
/*********************************/
/******* Users functions *********/
/*********************************/
/**
* @notice Lock Staked DF and harvest veDF.
* @dev Create lock-up information and mint veDF on lock-up amount and duration.
* @param _recipient veDF recipient address.
* @param _amount Staked DF token amount.
* @param _duration Duration, in seconds.
* @return The amount of veDF minted.
*/
function create(
address _recipient,
uint256 _amount,
uint256 _duration
) external onlyMinter nonReentrant returns (uint96) {
stakedDF.safeTransferFrom(msg.sender, address(this), _amount);
return _lock(msg.sender, _recipient, _amount, _duration);
}
/**
* @notice Increased locked staked DF and harvest veDF.
* @dev According to the expiration time in the lock information, the minted veDF.
* @param _recipient veDF recipient address.
* @param _amount Staked DF token amount.
* @param _refilled The amount of veDF minted.
*/
function refill(address _recipient, uint256 _amount)
external
onlyMinter
nonReentrant
isDueTimeValid(lockers[_recipient].dueTime)
returns (uint96 _refilled)
{
require(_amount > 0, "not allowed to add zero amount in lock-up");
stakedDF.safeTransferFrom(msg.sender, address(this), _amount);
Locker storage _locker = lockers[_recipient];
_refilled = _weightedExchange(
_amount,
uint256(_locker.dueTime).sub(block.timestamp)
);
_locker.amount = safe96(
uint256(_locker.amount).add(_amount),
"refilled amount overflow."
);
emit Lock(
msg.sender,
_recipient,
_amount,
_refilled,
_locker.dueTime,
_locker.duration
);
_mint(_recipient, _refilled);
}
/**
* @notice Increase the lock duration and harvest veDF.
* @dev According to the amount of locked staked DF and expansion time, the minted veDF.
* @param _recipient veDF recipient address.
* @param _duration Duration, in seconds.
* @param _extended The amount of veDF minted.
*/
function extend(address _recipient, uint256 _duration)
external
onlyMinter
nonReentrant
isDueTimeValid(lockers[_recipient].dueTime)
isDurationValid(uint256(lockers[_recipient].duration).add(_duration))
returns (uint96 _extended)
{
Locker storage _locker = lockers[_recipient];
_extended = _weightedExchange(uint256(_locker.amount), _duration);
_locker.dueTime = safe32(
uint256(_locker.dueTime).add(_duration),
"extended due time overflow."
);
_locker.duration = safe32(
uint256(_locker.duration).add(_duration),
"extended duration overflow."
);
emit Lock(
msg.sender,
_recipient,
0,
_extended,
_locker.dueTime,
_locker.duration
);
_mint(_recipient, _extended);
}
/**
* @notice Unlock Staked DF and burn veDF.(transfer to msg.sender)
* @dev Burn veDF and clear lock information.
* @param _from veDF holder's address.
* @param _unlocked The amount of veDF burned.
*/
function withdraw(address _from)
external
onlyMinter
nonReentrant
returns (uint96 _unlocked)
{
uint256 _amount = lockers[_from].amount;
_unlocked = _unLock(msg.sender, _from);
stakedDF.safeTransfer(msg.sender, _amount);
}
/**
* @notice Unlock Staked DF and burn veDF.(transfer to _from)
* @dev Burn veDF and clear lock information.
* @param _from veDF holder's address.
* @param _unlocked The amount of veDF burned.
*/
function withdraw2(address _from)
external
onlyMinter
nonReentrant
returns (uint96 _unlocked)
{
uint256 _amount = lockers[_from].amount;
_unlocked = _unLock(msg.sender, _from);
stakedDF.safeTransfer(_from, _amount);
}
/**
* @notice Lock Staked DF and and update veDF balance.(transfer to msg.sender)
* @dev Update the lockup information and veDF balance, return the excess sDF to the user or receive transfer increased amount.
* @param _recipient veDF recipient address.
* @param _amount Staked DF token new amount.
* @param _duration New duration, in seconds.
* @param _refreshed veDF new balance.
*/
function refresh(
address _recipient,
uint256 _amount,
uint256 _duration
) external onlyMinter nonReentrant returns (uint96 _refreshed, uint256 _refund) {
uint256 outstanding = uint256(lockers[_recipient].amount);
if (_amount > outstanding) {
stakedDF.safeTransferFrom(
msg.sender,
address(this),
_amount - outstanding
);
}
_unLock(msg.sender, _recipient);
_refreshed = _lock(msg.sender, _recipient, _amount, _duration);
if (_amount < outstanding) {
_refund = outstanding - _amount;
stakedDF.safeTransfer(msg.sender, _refund);
}
}
/**
* @notice Lock Staked DF and and update veDF balance.(transfer to _recipient)
* @dev Update the lockup information and veDF balance, return the excess sDF to the user or receive transfer increased amount.
* @param _recipient veDF recipient address.
* @param _amount Staked DF token new amount.
* @param _duration New duration, in seconds.
* @param _refreshed veDF new balance.
*/
function refresh2(
address _recipient,
uint256 _amount,
uint256 _duration
) external onlyMinter nonReentrant returns (uint96 _refreshed) {
uint256 outstanding = uint256(lockers[_recipient].amount);
if (_amount > outstanding) {
stakedDF.safeTransferFrom(
msg.sender,
address(this),
_amount - outstanding
);
}
_unLock(msg.sender, _recipient);
_refreshed = _lock(msg.sender, _recipient, _amount, _duration);
if (_amount < outstanding)
stakedDF.safeTransfer(_recipient, outstanding - _amount);
}
/*********************************/
/******** Query function *********/
/*********************************/
/**
* @notice Return all minters
* @return _minters The list of minter addresses
*/
function getMinters() external view returns (address[] memory _minters) {
uint256 _len = minters.length();
_minters = new address[](_len);
for (uint256 i = 0; i < _len; i++) {
_minters[i] = minters.at(i);
}
}
/**
* @dev Used to query the information of the locker.
* @param _lockerAddress veDF locker address.
* @return Information of the locker.
* due time;
* Lock up duration;
* Lock up sDF amount;
*/
function getLocker(address _lockerAddress) external view returns (uint32 ,uint32 ,uint96) {
Locker storage _locker = lockers[_lockerAddress];
return (_locker.dueTime, _locker.duration, _locker.amount);
}
/**
* @dev Calculate the expected amount of users.
* @param _lockerAddress veDF locker address.
* @param _amount Staked DF token amount.
* @param _duration Duration, in seconds.
* @return veDF amount.
*/
function calcBalanceReceived(address _lockerAddress, uint256 _amount, uint256 _duration)
external
view
returns (uint256)
{
Locker storage _locker = lockers[_lockerAddress];
if (_locker.dueTime < block.timestamp)
return _amount.rmul(_weightedRate(_duration));
uint256 _receiveAmount = uint256(_locker.amount).rmul(_weightedRate(_duration));
return _receiveAmount.add(_amount.rmul(_weightedRate(uint256(_locker.dueTime).add(_duration).sub(block.timestamp))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.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 SafeMathUpgradeable for uint256;
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).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20Upgradeable 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(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: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/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.6.12;
pragma experimental ABIEncoderV2;
contract GovernanceToken {
/// @notice EIP-20 token name for this token
string public constant name = "dForce Vote Escrow Token";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "veDF";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @dev Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @dev Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint256) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint256) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint256(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "veDF::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint256) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
// function transfer(address dst, uint256 rawAmount) external returns (bool) {
// uint96 amount = safe96(rawAmount, "veDF::transfer: amount exceeds 96 bits");
// _transferTokens(msg.sender, dst, amount);
// return true;
// }
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
// function transferFrom(address src, address dst, uint256 rawAmount) external returns (bool) {
// address spender = msg.sender;
// uint96 spenderAllowance = allowances[src][spender];
// uint96 amount = safe96(rawAmount, "veDF::approve: amount exceeds 96 bits");
// if (spender != src && spenderAllowance != uint96(-1)) {
// uint96 newAllowance = sub96(spenderAllowance, amount, "veDF::transferFrom: transfer amount exceeds spender allowance");
// allowances[src][spender] = newAllowance;
// emit Approval(src, spender, newAllowance);
// }
// _transferTokens(src, dst, amount);
// return true;
// }
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "veDF::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "veDF::delegateBySig: invalid nonce");
require(now <= expiry, "veDF::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint256 blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "veDF::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
// function _transferTokens(address src, address dst, uint96 amount) internal {
// require(src != address(0), "veDF::_transferTokens: cannot transfer from the zero address");
// require(dst != address(0), "veDF::_transferTokens: cannot transfer to the zero address");
// balances[src] = sub96(balances[src], amount, "veDF::_transferTokens: transfer amount exceeds balance");
// balances[dst] = add96(balances[dst], amount, "veDF::_transferTokens: transfer amount overflows");
// emit Transfer(src, dst, amount);
// _moveDelegates(delegates[src], delegates[dst], amount);
// }
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "veDF::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "veDF::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "veDF::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
*/
abstract contract ERC20Permit {
using SafeMathUpgradeable for uint256;
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 chainId, uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH =
0x576144ed657c8304561e56ca632e17751956250114636e8c01f64a7f2c6d98cf;
mapping(address => uint256) public erc20Nonces;
/**
* @dev EIP2612 permit function. For more details, please look at here:
* https://eips.ethereum.org/EIPS/eip-2612
* @param _owner The owner of the funds.
* @param _spender The spender.
* @param _value The amount.
* @param _deadline The deadline timestamp, type(uint256).max for max deadline.
* @param _v Signature param.
* @param _s Signature param.
* @param _r Signature param.
*/
function permit(
address _owner,
address _spender,
uint256 _value,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external virtual {
require(_deadline >= block.timestamp, "permit: EXPIRED!");
uint256 _currentNonce = erc20Nonces[_owner];
bytes32 _digest =
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
PERMIT_TYPEHASH,
_owner,
_spender,
_getChainId(),
_value,
_currentNonce,
_deadline
)
)
)
);
address _recoveredAddress = ecrecover(_digest, _v, _r, _s);
require(
_recoveredAddress != address(0) && _recoveredAddress == _owner,
"permit: INVALID_SIGNATURE!"
);
erc20Nonces[_owner] = _currentNonce.add(1);
_approveERC20(_owner, _spender, _value);
}
function _getChainId() internal pure virtual returns (uint256) {
uint256 _chainId;
assembly {
_chainId := chainid()
}
return _chainId;
}
function _approveERC20(address _owner, address _spender, uint256 _amount) internal virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.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.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {_setPendingOwner} and {_acceptOwner}.
*/
contract Ownable {
/**
* @dev Returns the address of the current owner.
*/
address payable public owner;
/**
* @dev Returns the address of the current pending owner.
*/
address payable public pendingOwner;
event NewOwner(address indexed previousOwner, address indexed newOwner);
event NewPendingOwner(
address indexed oldPendingOwner,
address indexed newPendingOwner
);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner == msg.sender, "onlyOwner: caller is not the owner");
_;
}
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal {
owner = msg.sender;
emit NewOwner(address(0), msg.sender);
}
/**
* @notice Base on the inputing parameter `newPendingOwner` to check the exact error reason.
* @dev Transfer contract control to a new owner. The newPendingOwner must call `_acceptOwner` to finish the transfer.
* @param newPendingOwner New pending owner.
*/
function _setPendingOwner(address payable newPendingOwner)
external
onlyOwner
{
require(
newPendingOwner != address(0) && newPendingOwner != pendingOwner,
"_setPendingOwner: New owenr can not be zero address and owner has been set!"
);
// Gets current owner.
address oldPendingOwner = pendingOwner;
// Sets new pending owner.
pendingOwner = newPendingOwner;
emit NewPendingOwner(oldPendingOwner, newPendingOwner);
}
/**
* @dev Accepts the admin rights, but only for pendingOwenr.
*/
function _acceptOwner() external {
require(
msg.sender == pendingOwner,
"_acceptOwner: Only for pending owner!"
);
// Gets current values for events.
address oldOwner = owner;
address oldPendingOwner = pendingOwner;
// Set the new contract owner.
owner = pendingOwner;
// Clear the pendingOwner.
pendingOwner = address(0);
emit NewOwner(oldOwner, owner);
emit NewPendingOwner(oldPendingOwner, pendingOwner);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeRatioMath {
using SafeMathUpgradeable for uint256;
uint256 private constant BASE = 10**18;
function rdiv(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a.mul(BASE).div(b);
}
function rmul(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a.mul(b).div(BASE);
}
function rdivup(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a.mul(BASE).add(b.sub(1)).div(b);
}
}
// 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 SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <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);
}
}
}
} | * @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/ First check most recent balance Next check implicit zero balance | function getPriorVotes(address account, uint256 blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "veDF::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
| 14,816,288 | [
1,
8519,
326,
6432,
1300,
434,
19588,
364,
392,
2236,
487,
434,
279,
1203,
1300,
225,
3914,
1300,
1297,
506,
279,
727,
1235,
1203,
578,
469,
333,
445,
903,
15226,
358,
5309,
7524,
13117,
18,
225,
2236,
1021,
1758,
434,
326,
2236,
358,
866,
225,
1203,
1854,
1021,
1203,
1300,
358,
336,
326,
12501,
11013,
622,
327,
1021,
1300,
434,
19588,
326,
2236,
9323,
487,
434,
326,
864,
1203,
19,
5783,
866,
4486,
8399,
11013,
4804,
866,
10592,
3634,
11013,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1689,
2432,
29637,
12,
2867,
2236,
16,
2254,
5034,
1203,
1854,
13,
1071,
1476,
1135,
261,
11890,
10525,
13,
288,
203,
3639,
2583,
12,
2629,
1854,
411,
1203,
18,
2696,
16,
315,
537,
4577,
2866,
588,
25355,
29637,
30,
486,
4671,
11383,
8863,
203,
203,
3639,
2254,
1578,
290,
1564,
4139,
273,
818,
1564,
4139,
63,
4631,
15533,
203,
3639,
309,
261,
82,
1564,
4139,
422,
374,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
203,
3639,
309,
261,
1893,
4139,
63,
4631,
6362,
82,
1564,
4139,
300,
404,
8009,
2080,
1768,
1648,
1203,
1854,
13,
288,
203,
5411,
327,
26402,
63,
4631,
6362,
82,
1564,
4139,
300,
404,
8009,
27800,
31,
203,
3639,
289,
203,
203,
3639,
309,
261,
1893,
4139,
63,
4631,
6362,
20,
8009,
2080,
1768,
405,
1203,
1854,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
203,
3639,
2254,
1578,
2612,
273,
374,
31,
203,
3639,
2254,
1578,
3854,
273,
290,
1564,
4139,
300,
404,
31,
203,
3639,
1323,
261,
5797,
405,
2612,
13,
288,
203,
5411,
25569,
3778,
3283,
273,
26402,
63,
4631,
6362,
5693,
15533,
203,
5411,
309,
261,
4057,
18,
2080,
1768,
422,
1203,
1854,
13,
288,
203,
7734,
327,
3283,
18,
27800,
31,
203,
7734,
2612,
273,
4617,
31,
203,
7734,
3854,
273,
4617,
300,
404,
31,
203,
5411,
289,
203,
3639,
289,
203,
3639,
327,
26402,
63,
4631,
6362,
8167,
8009,
27800,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.7;
import "../strategy-joe-rush-farm-base.sol";
contract StrategyJoeAvaxJgn is StrategyJoeRushFarmBase {
uint256 public avax_jgn_poolId = 35;
address public joe_avax_jgn_lp = 0x47898DbF127205Ea2E94a30B5291C9476E36f3bA;
address public jgn = 0x4e3642603a75528489C2D94f86e9507260d3c5a1;
constructor(
address _governance,
address _strategist,
address _controller,
address _timelock
)
public
StrategyJoeRushFarmBase(
avax_jgn_poolId,
joe_avax_jgn_lp,
_governance,
_strategist,
_controller,
_timelock
)
{}
function _takeFeeJgnToSnob(uint256 _keep) internal {
address[] memory path = new address[](3);
path[0] = jgn;
path[1] = wavax;
path[2] = snob;
IERC20(jgn).safeApprove(joeRouter, 0);
IERC20(jgn).safeApprove(joeRouter, _keep);
_swapTraderJoeWithPath(path, _keep);
uint256 _snob = IERC20(snob).balanceOf(address(this));
uint256 _share = _snob.mul(revenueShare).div(revenueShareMax);
IERC20(snob).safeTransfer(
feeDistributor,
_share
);
IERC20(snob).safeTransfer(
IController(controller).treasury(),
_snob.sub(_share)
);
}
// **** State Mutations ****
function harvest() public override onlyBenevolent {
// Collects JOE tokens
IMasterChefJoeV2(masterChefJoeV3).deposit(poolId, 0);
// Take AVAX Rewards
uint256 _avax = address(this).balance; // get balance of native AVAX
if (_avax > 0) { // wrap AVAX into ERC20
WAVAX(wavax).deposit{value: _avax}();
}
uint256 _jgn = IERC20(jgn).balanceOf(address(this)); //get balance of JGN Tokens
uint256 _wavax = IERC20(wavax).balanceOf(address(this)); //get balance of WAVAX
if (_wavax > 0) {
uint256 _keep1 = _wavax.mul(keep).div(keepMax);
if (_keep1 > 0){
_takeFeeWavaxToSnob(_keep1);
}
_wavax = IERC20(wavax).balanceOf(address(this));
}
if (_jgn > 0) {
uint256 _keep2 = _jgn.mul(keep).div(keepMax);
if (_keep2 > 0){
_takeFeeJgnToSnob(_keep2);
}
_jgn = IERC20(jgn).balanceOf(address(this));
}
//In the case of JGN Rewards, swap JGN for WAVAX
if(_jgn > 0){
IERC20(jgn).safeApprove(joeRouter, 0);
IERC20(jgn).safeApprove(joeRouter, _jgn.div(2));
_swapTraderJoe(jgn, wavax, _jgn.div(2));
}
//in the case of AVAX Rewards, swap WAVAX for JGN
if(_wavax > 0){
IERC20(wavax).safeApprove(joeRouter, 0);
IERC20(wavax).safeApprove(joeRouter, _wavax.div(2));
_swapTraderJoe(wavax, jgn, _wavax.div(2));
}
uint256 _joe = IERC20(joe).balanceOf(address(this));
if (_joe > 0) {
// 10% is sent to treasury
uint256 _keep = _joe.mul(keep).div(keepMax);
if (_keep > 0) {
_takeFeeJoeToSnob(_keep);
}
_joe = IERC20(joe).balanceOf(address(this));
IERC20(joe).safeApprove(joeRouter, 0);
IERC20(joe).safeApprove(joeRouter, _joe);
_swapTraderJoe(joe, wavax, _joe.div(2));
_swapTraderJoe(joe, jgn, _joe.div(2));
}
// Adds in liquidity for AVAX/JGN
_wavax = IERC20(wavax).balanceOf(address(this));
_jgn = IERC20(jgn).balanceOf(address(this));
if (_wavax > 0 && _jgn > 0) {
IERC20(wavax).safeApprove(joeRouter, 0);
IERC20(wavax).safeApprove(joeRouter, _wavax);
IERC20(jgn).safeApprove(joeRouter, 0);
IERC20(jgn).safeApprove(joeRouter, _jgn);
IJoeRouter(joeRouter).addLiquidity(
wavax,
jgn,
_wavax,
_jgn,
0,
0,
address(this),
now + 60
);
// Donates DUST
_wavax = IERC20(wavax).balanceOf(address(this));
_jgn = IERC20(jgn).balanceOf(address(this));
_joe = IERC20(joe).balanceOf(address(this));
if (_wavax > 0){
IERC20(wavax).transfer(
IController(controller).treasury(),
_wavax
);
}
if (_jgn > 0){
IERC20(jgn).safeTransfer(
IController(controller).treasury(),
_jgn
);
}
if (_joe > 0){
IERC20(joe).safeTransfer(
IController(controller).treasury(),
_joe
);
}
}
_distributePerformanceFeesAndDeposit();
}
// **** Views ****
function getName() external override pure returns (string memory) {
return "StrategyJoeAvaxJgn";
}
} | 10% is sent to treasury | if (_joe > 0) {
uint256 _keep = _joe.mul(keep).div(keepMax);
if (_keep > 0) {
_takeFeeJoeToSnob(_keep);
}
_joe = IERC20(joe).balanceOf(address(this));
IERC20(joe).safeApprove(joeRouter, 0);
IERC20(joe).safeApprove(joeRouter, _joe);
_swapTraderJoe(joe, wavax, _joe.div(2));
_swapTraderJoe(joe, jgn, _joe.div(2));
}
_jgn = IERC20(jgn).balanceOf(address(this));
| 13,038,055 | [
1,
2163,
9,
353,
3271,
358,
9787,
345,
22498,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
309,
261,
67,
78,
15548,
405,
374,
13,
288,
203,
5411,
2254,
5034,
389,
10102,
273,
389,
78,
15548,
18,
16411,
12,
10102,
2934,
2892,
12,
10102,
2747,
1769,
203,
5411,
309,
261,
67,
10102,
405,
374,
13,
288,
203,
7734,
389,
22188,
14667,
46,
15548,
774,
10461,
947,
24899,
10102,
1769,
203,
5411,
289,
203,
203,
5411,
389,
78,
15548,
273,
467,
654,
39,
3462,
12,
78,
15548,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
203,
5411,
467,
654,
39,
3462,
12,
78,
15548,
2934,
4626,
12053,
537,
12,
78,
15548,
8259,
16,
374,
1769,
203,
5411,
467,
654,
39,
3462,
12,
78,
15548,
2934,
4626,
12053,
537,
12,
78,
15548,
8259,
16,
389,
78,
15548,
1769,
203,
203,
5411,
389,
22270,
1609,
765,
46,
15548,
12,
78,
15548,
16,
19342,
651,
16,
389,
78,
15548,
18,
2892,
12,
22,
10019,
203,
5411,
389,
22270,
1609,
765,
46,
15548,
12,
78,
15548,
16,
525,
1600,
16,
389,
78,
15548,
18,
2892,
12,
22,
10019,
203,
3639,
289,
203,
203,
3639,
389,
78,
1600,
273,
467,
654,
39,
3462,
12,
78,
1600,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
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
] |
pragma solidity ^0.4.24;
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender)
public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(
ERC20Basic _token,
address _to,
uint256 _value
)
internal
{
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));
}
}
// File: contracts/IMonethaVoucher.sol
interface IMonethaVoucher {
/**
* @dev Total number of vouchers in shared pool
*/
function totalInSharedPool() external view returns (uint256);
/**
* @dev Converts vouchers to equivalent amount of wei.
* @param _value amount of vouchers (vouchers) to convert to amount of wei
* @return A uint256 specifying the amount of wei.
*/
function toWei(uint256 _value) external view returns (uint256);
/**
* @dev Converts amount of wei to equivalent amount of vouchers.
* @param _value amount of wei to convert to vouchers (vouchers)
* @return A uint256 specifying the amount of vouchers.
*/
function fromWei(uint256 _value) external view returns (uint256);
/**
* @dev Applies discount for address by returning vouchers to shared pool and transferring funds (in wei). May be called only by Monetha.
* @param _for address to apply discount for
* @param _vouchers amount of vouchers to return to shared pool
* @return Actual number of vouchers returned to shared pool and amount of funds (in wei) transferred.
*/
function applyDiscount(address _for, uint256 _vouchers) external returns (uint256 amountVouchers, uint256 amountWei);
/**
* @dev Applies payback by transferring vouchers from the shared pool to the user.
* The amount of transferred vouchers is equivalent to the amount of Ether in the `_amountWei` parameter.
* @param _for address to apply payback for
* @param _amountWei amount of Ether to estimate the amount of vouchers
* @return The number of vouchers added
*/
function applyPayback(address _for, uint256 _amountWei) external returns (uint256 amountVouchers);
/**
* @dev Function to buy vouchers by transferring equivalent amount in Ether to contract. May be called only by Monetha.
* After the vouchers are purchased, they can be sold or released to another user. Purchased vouchers are stored in
* a separate pool and may not be expired.
* @param _vouchers The amount of vouchers to buy. The caller must also transfer an equivalent amount of Ether.
*/
function buyVouchers(uint256 _vouchers) external payable;
/**
* @dev The function allows Monetha account to sell previously purchased vouchers and get Ether from the sale.
* The equivalent amount of Ether will be transferred to the caller. May be called only by Monetha.
* @param _vouchers The amount of vouchers to sell.
* @return A uint256 specifying the amount of Ether (in wei) transferred to the caller.
*/
function sellVouchers(uint256 _vouchers) external returns(uint256 weis);
/**
* @dev Function allows Monetha account to release the purchased vouchers to any address.
* The released voucher acquires an expiration property and should be used in Monetha ecosystem within 6 months, otherwise
* it will be returned to shared pool. May be called only by Monetha.
* @param _to address to release vouchers to.
* @param _value the amount of vouchers to release.
*/
function releasePurchasedTo(address _to, uint256 _value) external returns (bool);
/**
* @dev Function to check the amount of vouchers that an owner (Monetha account) allowed to sell or release to some user.
* @param owner The address which owns the funds.
* @return A uint256 specifying the amount of vouchers still available for the owner.
*/
function purchasedBy(address owner) external view returns (uint256);
}
// File: monetha-utility-contracts/contracts/Restricted.sol
/** @title Restricted
* Exposes onlyMonetha modifier
*/
contract Restricted is Ownable {
//MonethaAddress set event
event MonethaAddressSet(
address _address,
bool _isMonethaAddress
);
mapping (address => bool) public isMonethaAddress;
/**
* Restrict methods in such way, that they can be invoked only by monethaAddress account.
*/
modifier onlyMonetha() {
require(isMonethaAddress[msg.sender]);
_;
}
/**
* Allows owner to set new monetha address
*/
function setMonethaAddress(address _address, bool _isMonethaAddress) onlyOwner public {
isMonethaAddress[_address] = _isMonethaAddress;
emit MonethaAddressSet(_address, _isMonethaAddress);
}
}
// File: contracts/token/ERC20/IERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/ownership/CanReclaimEther.sol
contract CanReclaimEther is Ownable {
event ReclaimEther(address indexed to, uint256 amount);
/**
* @dev Transfer all Ether held by the contract to the owner.
*/
function reclaimEther() external onlyOwner {
uint256 value = address(this).balance;
owner.transfer(value);
emit ReclaimEther(owner, value);
}
/**
* @dev Transfer specified amount of Ether held by the contract to the address.
* @param _to The address which will receive the Ether
* @param _value The amount of Ether to transfer
*/
function reclaimEtherTo(address _to, uint256 _value) external onlyOwner {
require(_to != address(0), "zero address is not allowed");
_to.transfer(_value);
emit ReclaimEther(_to, _value);
}
}
// File: contracts/ownership/CanReclaimTokens.sol
contract CanReclaimTokens is Ownable {
using SafeERC20 for ERC20Basic;
event ReclaimTokens(address indexed to, uint256 amount);
/**
* @dev Reclaim all ERC20Basic compatible tokens
* @param _token ERC20Basic The address of the token contract
*/
function reclaimToken(ERC20Basic _token) external onlyOwner {
uint256 balance = _token.balanceOf(this);
_token.safeTransfer(owner, balance);
emit ReclaimTokens(owner, balance);
}
/**
* @dev Reclaim specified amount of ERC20Basic compatible tokens
* @param _token ERC20Basic The address of the token contract
* @param _to The address which will receive the tokens
* @param _value The amount of tokens to transfer
*/
function reclaimTokenTo(ERC20Basic _token, address _to, uint256 _value) external onlyOwner {
require(_to != address(0), "zero address is not allowed");
_token.safeTransfer(_to, _value);
emit ReclaimTokens(_to, _value);
}
}
// File: contracts/MonethaVoucher.sol
contract MonethaVoucher is IMonethaVoucher, Restricted, Pausable, IERC20, CanReclaimEther, CanReclaimTokens {
using SafeMath for uint256;
using SafeERC20 for ERC20Basic;
event DiscountApplied(address indexed user, uint256 releasedVouchers, uint256 amountWeiTransferred);
event PaybackApplied(address indexed user, uint256 addedVouchers, uint256 amountWeiEquivalent);
event VouchersBought(address indexed user, uint256 vouchersBought);
event VouchersSold(address indexed user, uint256 vouchersSold, uint256 amountWeiTransferred);
event VoucherMthRateUpdated(uint256 oldVoucherMthRate, uint256 newVoucherMthRate);
event MthEthRateUpdated(uint256 oldMthEthRate, uint256 newMthEthRate);
event VouchersAdded(address indexed user, uint256 vouchersAdded);
event VoucherReleased(address indexed user, uint256 releasedVoucher);
event PurchasedVouchersReleased(address indexed from, address indexed to, uint256 vouchers);
/* Public variables of the token */
string constant public standard = "ERC20";
string constant public name = "Monetha Voucher";
string constant public symbol = "MTHV";
uint8 constant public decimals = 5;
/* For calculating half year */
uint256 constant private DAY_IN_SECONDS = 86400;
uint256 constant private YEAR_IN_SECONDS = 365 * DAY_IN_SECONDS;
uint256 constant private LEAP_YEAR_IN_SECONDS = 366 * DAY_IN_SECONDS;
uint256 constant private YEAR_IN_SECONDS_AVG = (YEAR_IN_SECONDS * 3 + LEAP_YEAR_IN_SECONDS) / 4;
uint256 constant private HALF_YEAR_IN_SECONDS_AVG = YEAR_IN_SECONDS_AVG / 2;
uint256 constant public RATE_COEFFICIENT = 1000000000000000000; // 10^18
uint256 constant private RATE_COEFFICIENT2 = RATE_COEFFICIENT * RATE_COEFFICIENT; // RATE_COEFFICIENT^2
uint256 public voucherMthRate; // number of voucher units in 10^18 MTH units
uint256 public mthEthRate; // number of mth units in 10^18 wei
uint256 internal voucherMthEthRate; // number of vouchers units (= voucherMthRate * mthEthRate) in 10^36 wei
ERC20Basic public mthToken;
mapping(address => uint256) public purchased; // amount of vouchers purchased by other monetha contract
uint256 public totalPurchased; // total amount of vouchers purchased by monetha
mapping(uint16 => uint256) public totalDistributedIn; // аmount of vouchers distributed in specific half-year
mapping(uint16 => mapping(address => uint256)) public distributed; // amount of vouchers distributed in specific half-year to specific user
constructor(uint256 _voucherMthRate, uint256 _mthEthRate, ERC20Basic _mthToken) public {
require(_voucherMthRate > 0, "voucherMthRate should be greater than 0");
require(_mthEthRate > 0, "mthEthRate should be greater than 0");
require(_mthToken != address(0), "must be valid contract");
voucherMthRate = _voucherMthRate;
mthEthRate = _mthEthRate;
mthToken = _mthToken;
_updateVoucherMthEthRate();
}
/**
* @dev Total number of vouchers in existence = vouchers in shared pool + vouchers distributed + vouchers purchased
*/
function totalSupply() external view returns (uint256) {
return _totalVouchersSupply();
}
/**
* @dev Total number of vouchers in shared pool
*/
function totalInSharedPool() external view returns (uint256) {
return _vouchersInSharedPool(_currentHalfYear());
}
/**
* @dev Total number of vouchers distributed
*/
function totalDistributed() external view returns (uint256) {
return _vouchersDistributed(_currentHalfYear());
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) external view returns (uint256) {
return _distributedTo(owner, _currentHalfYear()).add(purchased[owner]);
}
/**
* @dev Function to check the amount of vouchers 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 vouchers still available for the spender.
*/
function allowance(address owner, address spender) external view returns (uint256) {
owner;
spender;
return 0;
}
/**
* @dev Transfer voucher for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) external returns (bool) {
to;
value;
revert();
}
/**
* @dev Approve the passed address to spend the specified amount of vouchers 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 vouchers to be spent.
*/
function approve(address spender, uint256 value) external returns (bool) {
spender;
value;
revert();
}
/**
* @dev Transfer vouchers from one address to another
* @param from address The address which you want to send vouchers from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of vouchers to be transferred
*/
function transferFrom(address from, address to, uint256 value) external returns (bool) {
from;
to;
value;
revert();
}
// Allows direct funds send by Monetha
function () external onlyMonetha payable {
}
/**
* @dev Converts vouchers to equivalent amount of wei.
* @param _value amount of vouchers to convert to amount of wei
* @return A uint256 specifying the amount of wei.
*/
function toWei(uint256 _value) external view returns (uint256) {
return _vouchersToWei(_value);
}
/**
* @dev Converts amount of wei to equivalent amount of vouchers.
* @param _value amount of wei to convert to vouchers
* @return A uint256 specifying the amount of vouchers.
*/
function fromWei(uint256 _value) external view returns (uint256) {
return _weiToVouchers(_value);
}
/**
* @dev Applies discount for address by returning vouchers to shared pool and transferring funds (in wei). May be called only by Monetha.
* @param _for address to apply discount for
* @param _vouchers amount of vouchers to return to shared pool
* @return Actual number of vouchers returned to shared pool and amount of funds (in wei) transferred.
*/
function applyDiscount(address _for, uint256 _vouchers) external onlyMonetha returns (uint256 amountVouchers, uint256 amountWei) {
require(_for != address(0), "zero address is not allowed");
uint256 releasedVouchers = _releaseVouchers(_for, _vouchers);
if (releasedVouchers == 0) {
return (0,0);
}
uint256 amountToTransfer = _vouchersToWei(releasedVouchers);
require(address(this).balance >= amountToTransfer, "insufficient funds");
_for.transfer(amountToTransfer);
emit DiscountApplied(_for, releasedVouchers, amountToTransfer);
return (releasedVouchers, amountToTransfer);
}
/**
* @dev Applies payback by transferring vouchers from the shared pool to the user.
* The amount of transferred vouchers is equivalent to the amount of Ether in the `_amountWei` parameter.
* @param _for address to apply payback for
* @param _amountWei amount of Ether to estimate the amount of vouchers
* @return The number of vouchers added
*/
function applyPayback(address _for, uint256 _amountWei) external onlyMonetha returns (uint256 amountVouchers) {
amountVouchers = _weiToVouchers(_amountWei);
require(_addVouchers(_for, amountVouchers), "vouchers must be added");
emit PaybackApplied(_for, amountVouchers, _amountWei);
}
/**
* @dev Function to buy vouchers by transferring equivalent amount in Ether to contract. May be called only by Monetha.
* After the vouchers are purchased, they can be sold or released to another user. Purchased vouchers are stored in
* a separate pool and may not be expired.
* @param _vouchers The amount of vouchers to buy. The caller must also transfer an equivalent amount of Ether.
*/
function buyVouchers(uint256 _vouchers) external onlyMonetha payable {
uint16 currentHalfYear = _currentHalfYear();
require(_vouchersInSharedPool(currentHalfYear) >= _vouchers, "insufficient vouchers present");
require(msg.value == _vouchersToWei(_vouchers), "insufficient funds");
_addPurchasedTo(msg.sender, _vouchers);
emit VouchersBought(msg.sender, _vouchers);
}
/**
* @dev The function allows Monetha account to sell previously purchased vouchers and get Ether from the sale.
* The equivalent amount of Ether will be transferred to the caller. May be called only by Monetha.
* @param _vouchers The amount of vouchers to sell.
* @return A uint256 specifying the amount of Ether (in wei) transferred to the caller.
*/
function sellVouchers(uint256 _vouchers) external onlyMonetha returns(uint256 weis) {
require(_vouchers <= purchased[msg.sender], "Insufficient vouchers");
_subPurchasedFrom(msg.sender, _vouchers);
weis = _vouchersToWei(_vouchers);
msg.sender.transfer(weis);
emit VouchersSold(msg.sender, _vouchers, weis);
}
/**
* @dev Function allows Monetha account to release the purchased vouchers to any address.
* The released voucher acquires an expiration property and should be used in Monetha ecosystem within 6 months, otherwise
* it will be returned to shared pool. May be called only by Monetha.
* @param _to address to release vouchers to.
* @param _value the amount of vouchers to release.
*/
function releasePurchasedTo(address _to, uint256 _value) external onlyMonetha returns (bool) {
require(_value <= purchased[msg.sender], "Insufficient Vouchers");
require(_to != address(0), "address should be valid");
_subPurchasedFrom(msg.sender, _value);
_addVouchers(_to, _value);
emit PurchasedVouchersReleased(msg.sender, _to, _value);
return true;
}
/**
* @dev Function to check the amount of vouchers that an owner (Monetha account) allowed to sell or release to some user.
* @param owner The address which owns the funds.
* @return A uint256 specifying the amount of vouchers still available for the owner.
*/
function purchasedBy(address owner) external view returns (uint256) {
return purchased[owner];
}
/**
* @dev updates voucherMthRate.
*/
function updateVoucherMthRate(uint256 _voucherMthRate) external onlyMonetha {
require(_voucherMthRate > 0, "should be greater than 0");
require(voucherMthRate != _voucherMthRate, "same as previous value");
voucherMthRate = _voucherMthRate;
_updateVoucherMthEthRate();
emit VoucherMthRateUpdated(voucherMthRate, _voucherMthRate);
}
/**
* @dev updates mthEthRate.
*/
function updateMthEthRate(uint256 _mthEthRate) external onlyMonetha {
require(_mthEthRate > 0, "should be greater than 0");
require(mthEthRate != _mthEthRate, "same as previous value");
mthEthRate = _mthEthRate;
_updateVoucherMthEthRate();
emit MthEthRateUpdated(mthEthRate, _mthEthRate);
}
function _addPurchasedTo(address _to, uint256 _value) internal {
purchased[_to] = purchased[_to].add(_value);
totalPurchased = totalPurchased.add(_value);
}
function _subPurchasedFrom(address _from, uint256 _value) internal {
purchased[_from] = purchased[_from].sub(_value);
totalPurchased = totalPurchased.sub(_value);
}
function _updateVoucherMthEthRate() internal {
voucherMthEthRate = voucherMthRate.mul(mthEthRate);
}
/**
* @dev Transfer vouchers from shared pool to address. May be called only by Monetha.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function _addVouchers(address _to, uint256 _value) internal returns (bool) {
require(_to != address(0), "zero address is not allowed");
uint16 currentHalfYear = _currentHalfYear();
require(_vouchersInSharedPool(currentHalfYear) >= _value, "must be less or equal than vouchers present in shared pool");
uint256 oldDist = totalDistributedIn[currentHalfYear];
totalDistributedIn[currentHalfYear] = oldDist.add(_value);
uint256 oldBalance = distributed[currentHalfYear][_to];
distributed[currentHalfYear][_to] = oldBalance.add(_value);
emit VouchersAdded(_to, _value);
return true;
}
/**
* @dev Transfer vouchers from address to shared pool
* @param _from address The address which you want to send vouchers from
* @param _value uint256 the amount of vouchers to be transferred
* @return A uint256 specifying the amount of vouchers released to shared pool.
*/
function _releaseVouchers(address _from, uint256 _value) internal returns (uint256) {
require(_from != address(0), "must be valid address");
uint16 currentHalfYear = _currentHalfYear();
uint256 released = 0;
if (currentHalfYear > 0) {
released = released.add(_releaseVouchers(_from, _value, currentHalfYear - 1));
_value = _value.sub(released);
}
released = released.add(_releaseVouchers(_from, _value, currentHalfYear));
emit VoucherReleased(_from, released);
return released;
}
function _releaseVouchers(address _from, uint256 _value, uint16 _currentHalfYear) internal returns (uint256) {
if (_value == 0) {
return 0;
}
uint256 oldBalance = distributed[_currentHalfYear][_from];
uint256 subtracted = _value;
if (oldBalance <= _value) {
delete distributed[_currentHalfYear][_from];
subtracted = oldBalance;
} else {
distributed[_currentHalfYear][_from] = oldBalance.sub(_value);
}
uint256 oldDist = totalDistributedIn[_currentHalfYear];
if (oldDist == subtracted) {
delete totalDistributedIn[_currentHalfYear];
} else {
totalDistributedIn[_currentHalfYear] = oldDist.sub(subtracted);
}
return subtracted;
}
// converts vouchers to Ether (in wei)
function _vouchersToWei(uint256 _value) internal view returns (uint256) {
return _value.mul(RATE_COEFFICIENT2).div(voucherMthEthRate);
}
// converts Ether (in wei) to vouchers
function _weiToVouchers(uint256 _value) internal view returns (uint256) {
return _value.mul(voucherMthEthRate).div(RATE_COEFFICIENT2);
}
// converts MTH tokens to vouchers
function _mthToVouchers(uint256 _value) internal view returns (uint256) {
return _value.mul(voucherMthRate).div(RATE_COEFFICIENT);
}
// converts Ether (in wei) to MTH
function _weiToMth(uint256 _value) internal view returns (uint256) {
return _value.mul(mthEthRate).div(RATE_COEFFICIENT);
}
function _totalVouchersSupply() internal view returns (uint256) {
return _mthToVouchers(mthToken.balanceOf(address(this)));
}
function _vouchersInSharedPool(uint16 _currentHalfYear) internal view returns (uint256) {
return _totalVouchersSupply().sub(_vouchersDistributed(_currentHalfYear)).sub(totalPurchased);
}
function _vouchersDistributed(uint16 _currentHalfYear) internal view returns (uint256) {
uint256 dist = totalDistributedIn[_currentHalfYear];
if (_currentHalfYear > 0) {
// include previous half-year
dist = dist.add(totalDistributedIn[_currentHalfYear - 1]);
}
return dist;
}
function _distributedTo(address _owner, uint16 _currentHalfYear) internal view returns (uint256) {
uint256 balance = distributed[_currentHalfYear][_owner];
if (_currentHalfYear > 0) {
// include previous half-year
balance = balance.add(distributed[_currentHalfYear - 1][_owner]);
}
return balance;
}
function _currentHalfYear() internal view returns (uint16) {
return uint16(now / HALF_YEAR_IN_SECONDS_AVG);
}
} | * @dev Applies discount for address by returning vouchers to shared pool and transferring funds (in wei). May be called only by Monetha. @param _for address to apply discount for @param _vouchers amount of vouchers to return to shared pool @return Actual number of vouchers returned to shared pool and amount of funds (in wei) transferred./ | function applyDiscount(address _for, uint256 _vouchers) external onlyMonetha returns (uint256 amountVouchers, uint256 amountWei) {
require(_for != address(0), "zero address is not allowed");
uint256 releasedVouchers = _releaseVouchers(_for, _vouchers);
if (releasedVouchers == 0) {
return (0,0);
}
uint256 amountToTransfer = _vouchersToWei(releasedVouchers);
require(address(this).balance >= amountToTransfer, "insufficient funds");
_for.transfer(amountToTransfer);
emit DiscountApplied(_for, releasedVouchers, amountToTransfer);
return (releasedVouchers, amountToTransfer);
}
| 1,015,236 | [
1,
13029,
12137,
364,
1758,
635,
5785,
331,
31952,
358,
5116,
2845,
471,
906,
74,
20245,
284,
19156,
261,
267,
732,
77,
2934,
16734,
506,
2566,
1338,
635,
9041,
546,
69,
18,
225,
389,
1884,
1758,
358,
2230,
12137,
364,
225,
389,
90,
31952,
3844,
434,
331,
31952,
358,
327,
358,
5116,
2845,
327,
23788,
1300,
434,
331,
31952,
2106,
358,
5116,
2845,
471,
3844,
434,
284,
19156,
261,
267,
732,
77,
13,
906,
4193,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
2230,
9866,
12,
2867,
389,
1884,
16,
2254,
5034,
389,
90,
31952,
13,
3903,
1338,
11415,
546,
69,
1135,
261,
11890,
5034,
3844,
58,
31952,
16,
2254,
5034,
3844,
3218,
77,
13,
288,
203,
3639,
2583,
24899,
1884,
480,
1758,
12,
20,
3631,
315,
7124,
1758,
353,
486,
2935,
8863,
203,
3639,
2254,
5034,
15976,
58,
31952,
273,
389,
9340,
58,
31952,
24899,
1884,
16,
389,
90,
31952,
1769,
203,
3639,
309,
261,
9340,
72,
58,
31952,
422,
374,
13,
288,
203,
5411,
327,
261,
20,
16,
20,
1769,
203,
3639,
289,
203,
540,
203,
3639,
2254,
5034,
3844,
774,
5912,
273,
389,
90,
31952,
774,
3218,
77,
12,
9340,
72,
58,
31952,
1769,
203,
203,
3639,
2583,
12,
2867,
12,
2211,
2934,
12296,
1545,
3844,
774,
5912,
16,
315,
2679,
11339,
284,
19156,
8863,
203,
3639,
389,
1884,
18,
13866,
12,
8949,
774,
5912,
1769,
203,
203,
3639,
3626,
3035,
1883,
16203,
24899,
1884,
16,
15976,
58,
31952,
16,
3844,
774,
5912,
1769,
203,
203,
3639,
327,
261,
9340,
72,
58,
31952,
16,
3844,
774,
5912,
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
] |
./partial_match/42/0x1EBacf9004e4b89c6b7774356fD762aE44Ee97a7/sources/LinearVesting.sol | we increased existing reward, so sum will be higher we decreased existing reward, so sum will be lower | function setupDistribution(
address[] calldata _participants,
uint256[] calldata _rewards,
uint256[] calldata _durations,
uint256[] calldata _startTimes
)
external onlyOwner {
require(_participants.length != 0, "there is no _participants");
require(_participants.length == _rewards.length, "_participants count must match _rewards count");
require(_participants.length == _durations.length, "_participants count must match _durations count");
require(_participants.length == _startTimes.length, "_participants count must match _startTimes count");
uint256 sum = totalVestingAmount;
for (uint256 i = 0; i < _participants.length; i++) {
require(_participants[i] != address(0x0), "empty participant");
require(_durations[i] != 0, "empty duration");
require(_durations[i] < 5 * 365 days, "duration too long");
require(_rewards[i] != 0, "empty reward");
require(_startTimes[i] != 0, "empty startTime");
uint256 total = rewards[_participants[i]].total;
if (total < _rewards[i]) {
sum = sum.add(_rewards[i] - total);
sum = sum.sub(total - _rewards[i]);
}
if (total != 0) {
require(rewards[_participants[i]].startTime == _startTimes[i], "can't change start time");
require(_rewards[i] >= balanceOf(_participants[i]), "can't take what's already done");
}
rewards[_participants[i]] = Reward(_rewards[i], _durations[i], 0, _startTimes[i]);
}
emit LogSetup(totalVestingAmount, sum);
totalVestingAmount = sum;
}
event LogSetup(uint256 prevSum, uint256 newSum);
event LogClaimed(address indexed recipient, uint256 amount);
| 8,879,090 | [
1,
1814,
31383,
2062,
19890,
16,
1427,
2142,
903,
506,
10478,
732,
23850,
8905,
2062,
19890,
16,
1427,
2142,
903,
506,
2612,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3875,
9003,
12,
203,
3639,
1758,
8526,
745,
892,
389,
2680,
27620,
16,
203,
3639,
2254,
5034,
8526,
745,
892,
389,
266,
6397,
16,
203,
3639,
2254,
5034,
8526,
745,
892,
389,
8760,
87,
16,
203,
3639,
2254,
5034,
8526,
745,
892,
389,
1937,
10694,
203,
565,
262,
203,
565,
3903,
1338,
5541,
288,
203,
3639,
2583,
24899,
2680,
27620,
18,
2469,
480,
374,
16,
315,
18664,
353,
1158,
389,
2680,
27620,
8863,
203,
3639,
2583,
24899,
2680,
27620,
18,
2469,
422,
389,
266,
6397,
18,
2469,
16,
4192,
2680,
27620,
1056,
1297,
845,
389,
266,
6397,
1056,
8863,
203,
3639,
2583,
24899,
2680,
27620,
18,
2469,
422,
389,
8760,
87,
18,
2469,
16,
4192,
2680,
27620,
1056,
1297,
845,
389,
8760,
87,
1056,
8863,
203,
3639,
2583,
24899,
2680,
27620,
18,
2469,
422,
389,
1937,
10694,
18,
2469,
16,
4192,
2680,
27620,
1056,
1297,
845,
389,
1937,
10694,
1056,
8863,
203,
203,
3639,
2254,
5034,
2142,
273,
2078,
58,
10100,
6275,
31,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
389,
2680,
27620,
18,
2469,
31,
277,
27245,
288,
203,
5411,
2583,
24899,
2680,
27620,
63,
77,
65,
480,
1758,
12,
20,
92,
20,
3631,
315,
5531,
14188,
8863,
203,
5411,
2583,
24899,
8760,
87,
63,
77,
65,
480,
374,
16,
315,
5531,
3734,
8863,
203,
5411,
2583,
24899,
8760,
87,
63,
77,
65,
411,
1381,
380,
21382,
4681,
16,
315,
8760,
4885,
1525,
8863,
203,
5411,
2583,
24899,
266,
6397,
63,
77,
65,
480,
374,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "../node_modules/@openzeppelin/contracts/utils/Counters.sol";
import "../node_modules/@openzeppelin/contracts/access/Ownable.sol";
import "./IECPToken.sol";
import "./ILedgerContract.sol";
contract CustomerContract is Ownable {
using Counters for Counters.Counter;
// BMP : Bridge message protocol
// MeasureHeader (32 bytes)
// version : bytes8
// date : YYYYmmddHHii : byte12
// measureType : bytes8 - CODE : 4 number/letter for the physical nature - 4 number/letter for the version
// timeCode : bytes1 (hourly, daily) Y m d H i
// nbTime : bytes3
// MeasureBody (32 bytes)
// Value 1 Max : bytes8
// Value 2 Mean : bytes8
// Value 3 Mediane : bytes8
// Value 4 Min : bytes8
// AlertBody (32 bytes)
// version : bytes8
// codeAlert : bytes4
// date : YYYYmmddHHii : byte12
// valueAlert : bytes8
/**
* @dev Structure of Configuration
* @notice Version and status of activation
* @notice Link to other contract
*/
struct Config {
bytes8 version;
bool isActive;
uint64 prevContractDate;
uint64 nextContractDate;
address _ledgerAddress;
address _ecpTokenAddress;
address customerAddress;
address prevContract;
address nextContract;
}
/**
* @dev Structure of Service
*/
struct Service {
bytes8 version;
bytes8 measureType;
bytes1 timeCode;
uint8 nbTime;
bool isActive;
string description;
address bridgeAddress;
address techMasterAddress;
address legislatorAddress;
Counters.Counter measureIdCounter;
Counters.Counter iotIdCounter;
}
/**
* @dev Structure of Rule
*/
struct Rule {
bytes8 version;
bytes4 codeAlert;
bytes8 valueAlert;
uint16 serviceId;
bool isActive;
uint64 dateOn;
uint64 dateOff;
string description;
address legislatorAddress;
Counters.Counter alertIdCounter;
}
/**
* @dev Structure of Iot
*/
struct Iot {
string description;
bool isActive;
}
modifier isContractActive() {
require(_myConfig.isActive, "Contract off line");
_;
}
modifier isServiceActive(uint _serviceId) {
require(_serviceId < _serviceIdCounter.current(), "Service not exist");
require(_services[_serviceId].isActive, "Service off line");
_;
}
modifier isRulesActive(uint _ruleId) {
require(_ruleId < _ruleIdCounter.current(), "Rules not exist");
require(_serviceRules[_ruleId].isActive, "Rules off line");
_;
}
modifier onlyCustomer() {
require (_myConfig.customerAddress == msg.sender || owner() == msg.sender, "Access denied");
_;
}
modifier onlyBridge(uint _serviceId) {
require (_services[_serviceId].bridgeAddress == msg.sender || owner() == msg.sender, "Access denied");
_;
}
modifier onlyTechMaster(uint _serviceId) {
require (_services[_serviceId].techMasterAddress == msg.sender || owner() == msg.sender, "Access denied");
_;
}
modifier onlyLegislator(uint _serviceId) {
require (_services[_serviceId].legislatorAddress == msg.sender || owner() == msg.sender, "Access denied");
_;
}
modifier checkLedger(address _address, uint _role) {
require (_ILedgerContract.rootingApps(_address) == _role, "Ledger check fail");
_;
}
event ContractUpdate(string _message, address _author);
event ServiceUpdate(uint _serviceId, string _message, address _author);
event ServiceRulesUpdate(uint _serviceId, uint _ruleId, string _message, address _author);
event ServiceIotUpdate(uint _serviceId, bytes6 _iotId, string _message, address _author);
event MeasureReceive(uint _serviceId, bytes32 _header, bytes32 _body, address _author);
event AlertReceive(uint _serviceId, uint _ruleId, bytes32 _alert, address _author);
Config public _myConfig;
mapping(uint => Service) public _services;
Counters.Counter public _serviceIdCounter;
mapping(uint => mapping(bytes6 => Iot)) public _serviceIots;
mapping(uint => Rule) public _serviceRules;
Counters.Counter public _ruleIdCounter;
IECPToken private _ECPToken;
ILedgerContract private _ILedgerContract;
constructor (bytes8 _version, address _ledgerAddress, address _ecpTokenAddress, address _customerAddress, address _prevContract, uint64 _prevContractDate) {
_myConfig = Config(
_version,
true,
_prevContractDate,
0,
_ledgerAddress,
_ecpTokenAddress,
_customerAddress,
_prevContract,
address(0)
);
_ECPToken = IECPToken(_ecpTokenAddress);
_ILedgerContract = ILedgerContract(_ledgerAddress);
}
// SERVICE PART
/**
* @dev add a Service
* @param _version bytes8 version of service
* @param _description string description for the dApps interface
* @param _measureType bytes8 type of measure for the dApps interface
* @param _timeCode bytes1 time code for the dApps interface
* @param _nbTime uint8 number of times for the dApps interface
*/
function addService(
bytes8 _version,
string memory _description,
bytes8 _measureType,
bytes1 _timeCode,
uint8 _nbTime)
onlyCustomer() isContractActive() external{
Counters.Counter memory measureIdCounter;
Counters.Counter memory iotIdCounter;
_services[_serviceIdCounter.current()] = Service(
_version,
_measureType,
_timeCode,
_nbTime,
true,
_description,
address(0),
address(0),
address(0),
measureIdCounter,
iotIdCounter);
emit ServiceUpdate(_serviceIdCounter.current(), "New service", msg.sender);
_serviceIdCounter.increment();
}
/**
* @dev toggle a Contract activation or deactivation
*/
function toggleContract()
onlyOwner() external {
emit ContractUpdate("Contract on/off", msg.sender);
_myConfig.isActive = !_myConfig.isActive;
}
/**
* @dev toggle a Service activation or deactivation
* @param _serviceId index of service
*/
function toggleService(
uint _serviceId)
onlyCustomer() external {
emit ServiceUpdate(_serviceId, "Service on/off", msg.sender);
_services[_serviceId].isActive = !_services[_serviceId].isActive;
}
/**
* @dev set a TechMasterAddress
* @param _serviceId index of service
* @param _techMasterAddress techMaster's address
*/
function setTechMasterAddress(
uint _serviceId,
address _techMasterAddress)
isContractActive() isServiceActive(_serviceId) checkLedger(_techMasterAddress, 4) onlyOwner() external {
_services[_serviceId].techMasterAddress = _techMasterAddress;
emit ServiceUpdate(_serviceId, "TechMaster Address update", msg.sender);
}
/**
* @dev set a LegislatorAddress
* @param _serviceId index of service
* @param _legislatorAddress legislator's address
*/
function setLegislatorAddress(
uint _serviceId,
address _legislatorAddress)
isContractActive() isServiceActive(_serviceId) onlyCustomer() checkLedger(_legislatorAddress, 3) external {
_services[_serviceId].legislatorAddress = _legislatorAddress;
emit ServiceUpdate(_serviceId, "Legislator Address update", msg.sender);
}
/**
* @dev set a BridgeAdress
* @param _serviceId index of service
* @param _bridgeAddress bridge's address
*/
function setBridgeAddress(
uint _serviceId,
address _bridgeAddress)
isContractActive() isServiceActive(_serviceId) onlyTechMaster(_serviceId) checkLedger(_bridgeAddress, 5) external {
_services[_serviceId].bridgeAddress = _bridgeAddress;
emit ServiceUpdate(_serviceId, "Bridge Address update", msg.sender);
}
// MEASURE PART
/**
* @dev add a Measure
* @param _serviceId index of service
* @param _measureHeader header of the measure
* @param _measurebody body of the measure
*/
function addMeasure(
uint _serviceId,
bytes32 _measureHeader,
bytes32 _measurebody)
isContractActive() isServiceActive(_serviceId) onlyBridge(_serviceId) external {
_ECPToken.transfer(_myConfig._ledgerAddress, 1);
_services[_serviceId].measureIdCounter.increment();
emit MeasureReceive(_serviceId, _measureHeader, _measurebody, msg.sender);
}
// ALERT CONFIG PART
/**
* @dev add a fondation's alert config
* @param _serviceId index of service
* @param _version service's version
* @param _description alert config description
* @param _dateOn alert's starting date
* @param _dateOff alert's ending date
* @param _codeAlert alert's code
* @param _valueAlert alert's value
*/
function addRule(
bytes8 _version,
uint16 _serviceId,
string memory _description,
uint64 _dateOn,
uint64 _dateOff,
bytes4 _codeAlert,
bytes8 _valueAlert)
isContractActive() isServiceActive(_serviceId) external {
require (_services[_serviceId].legislatorAddress == msg.sender
|| _myConfig.customerAddress == msg.sender
|| owner() == msg.sender, "Access denied");
Counters.Counter memory alertIdCounter;
_serviceRules[_ruleIdCounter.current()] = Rule(
_version,
_codeAlert,
_valueAlert,
_serviceId,
true,
_dateOn,
_dateOff,
_description,
msg.sender,
alertIdCounter
);
emit ServiceRulesUpdate(_serviceId, _ruleIdCounter.current(), "New rule", msg.sender);
_ruleIdCounter.increment();
}
/**
* @dev toggle an alert config
* @param _ruleId index of the alert config
*/
function toggleRule(uint _ruleId)
external {
require ((msg.sender == _serviceRules[_ruleId].legislatorAddress) || (msg.sender == owner()), "Access denied");
emit ServiceRulesUpdate(_serviceRules[_ruleId].serviceId, _ruleId, "Rules on/off", msg.sender);
_serviceRules[_ruleId].isActive = !_serviceRules[_ruleId].isActive;
}
// ALERTS PART
/**
* @dev add an alert
* @param _serviceId index of service
* @param _alertBody alert's body
*/
function addAlert(
uint _serviceId,
uint _ruleId,
bytes32 _alertBody)
isContractActive() isServiceActive(_serviceId) onlyBridge(_serviceId) external {
_ECPToken.transfer(_myConfig._ledgerAddress, 1);
_serviceRules[_ruleId].alertIdCounter.increment();
emit AlertReceive(_serviceId, _ruleId, _alertBody, msg.sender);
}
// SERVICE IOT
/**
* @dev add a sensor to the list
* @param _serviceId index of service
* @param _macAddress sensor's mac address
* @param _description sensor's description
*/
// function addIot(
// uint _serviceId,
// bytes6 _macAddress,
// string memory _description)
// isContractActive() isServiceActive(_serviceId) onlyTechMaster(_serviceId) external {
// _serviceIots[_serviceId][_macAddress] = Iot(
// _description,
// true
// );
// emit ServiceIotUpdate(_serviceId, _macAddress, "Iot added", msg.sender);
// _services[_serviceId].iotIdCounter.increment();
// }
/**
* @dev toggle a sensor activation or deactivation
* @param _serviceId index of service
* @param _macAddress index of sensor
*/
// function toggleIOT(
// uint _serviceId,
// bytes6 _macAddress)
// isContractActive() isServiceActive(_serviceId) onlyTechMaster(_serviceId) external {
// emit ServiceIotUpdate(_serviceId, _macAddress, "Iot on/off", msg.sender);
// _serviceIots[_serviceId][_macAddress].isActive = !_serviceIots[_serviceId][_macAddress].isActive;
// }
}
| * @dev add an alert @param _serviceId index of service @param _alertBody alert's body/ | function addAlert(
uint _serviceId,
uint _ruleId,
bytes32 _alertBody)
isContractActive() isServiceActive(_serviceId) onlyBridge(_serviceId) external {
_ECPToken.transfer(_myConfig._ledgerAddress, 1);
_serviceRules[_ruleId].alertIdCounter.increment();
emit AlertReceive(_serviceId, _ruleId, _alertBody, msg.sender);
}
| 15,814,392 | [
1,
1289,
392,
6881,
225,
389,
3278,
548,
770,
434,
1156,
225,
389,
11798,
2250,
6881,
1807,
1417,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
527,
13298,
12,
203,
3639,
2254,
389,
3278,
548,
16,
203,
3639,
2254,
389,
5345,
548,
16,
203,
3639,
1731,
1578,
389,
11798,
2250,
13,
7010,
3639,
353,
8924,
3896,
1435,
353,
1179,
3896,
24899,
3278,
548,
13,
1338,
13691,
24899,
3278,
548,
13,
3903,
288,
1850,
203,
203,
3639,
389,
41,
4258,
1345,
18,
13866,
24899,
4811,
809,
6315,
1259,
693,
1887,
16,
404,
1769,
203,
203,
3639,
389,
3278,
4478,
63,
67,
5345,
548,
8009,
11798,
548,
4789,
18,
15016,
5621,
203,
203,
3639,
3626,
17913,
11323,
24899,
3278,
548,
16,
389,
5345,
548,
16,
389,
11798,
2250,
16,
1234,
18,
15330,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/3/0x917B5f28A5b7006Df895F3F6f87943068a6E4bEa/sources/SuperRug.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 Context {
.▄▄ · ▄▄· ▄• ▄▌▄▄▄▄▄▄▄▄▄▄▄▄▌ ▄▄▄ . ▄▄▄▄· ▄▄▄▄▄.▄▄ ·
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
| 14,178,309 | [
1,
17727,
1779,
2973,
326,
783,
4588,
819,
16,
6508,
326,
5793,
434,
326,
2492,
471,
2097,
501,
18,
21572,
4259,
854,
19190,
2319,
3970,
1234,
18,
15330,
471,
1234,
18,
892,
16,
2898,
1410,
486,
506,
15539,
316,
4123,
279,
2657,
21296,
16,
3241,
1347,
21964,
598,
2191,
17,
20376,
326,
2236,
5431,
471,
8843,
310,
364,
4588,
2026,
486,
506,
326,
3214,
5793,
261,
345,
10247,
487,
392,
2521,
353,
356,
2750,
11748,
2934,
1220,
6835,
353,
1338,
1931,
364,
12110,
16,
5313,
17,
5625,
20092,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
17801,
6835,
1772,
288,
203,
203,
18,
163,
249,
231,
163,
249,
231,
225,
131,
120,
225,
225,
163,
249,
231,
163,
249,
231,
131,
120,
225,
163,
249,
231,
163,
227,
100,
225,
163,
249,
231,
163,
249,
239,
163,
249,
231,
163,
249,
231,
163,
249,
231,
163,
249,
231,
163,
249,
231,
163,
249,
231,
163,
249,
231,
163,
249,
231,
163,
249,
231,
163,
249,
231,
163,
249,
231,
163,
249,
231,
163,
249,
239,
225,
225,
163,
249,
231,
163,
249,
231,
163,
249,
231,
263,
565,
225,
163,
249,
231,
163,
249,
231,
163,
249,
231,
163,
249,
231,
131,
120,
4202,
225,
163,
249,
231,
163,
249,
231,
163,
249,
231,
163,
249,
231,
163,
249,
231,
18,
163,
249,
231,
163,
249,
231,
225,
131,
120,
7010,
203,
203,
565,
445,
389,
3576,
12021,
1435,
2713,
1476,
5024,
1135,
261,
2867,
13,
288,
203,
3639,
327,
1234,
18,
15330,
31,
203,
565,
289,
203,
203,
565,
445,
389,
3576,
751,
1435,
2713,
1476,
5024,
1135,
261,
3890,
745,
892,
13,
288,
203,
3639,
327,
1234,
18,
892,
31,
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
] |
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.7.6;
/******************************************************************************\
* Author: Evert Kors <[email protected]> (https://twitter.com/evert0x)
* Sherlock Protocol: https://sherlock.xyz
/******************************************************************************/
import '../interfaces/ISherX.sol';
import '../storage/SherXERC20Storage.sol';
import '../libraries/LibPool.sol';
import '../libraries/LibSherX.sol';
import '../libraries/LibSherXERC20.sol';
contract SherX is ISherX {
using SafeMath for uint256;
using SafeERC20 for IERC20;
//
// Modifiers
//
modifier onlyGovMain() {
require(msg.sender == GovStorage.gs().govMain, 'NOT_GOV_MAIN');
_;
}
//
// View methods
//
function getTotalUsdPerBlock() external view override returns (uint256) {
return SherXStorage.sx().totalUsdPerBlock;
}
function getTotalUsdPoolStored() external view override returns (uint256) {
return SherXStorage.sx().totalUsdPool;
}
function getTotalUsdPool() external view override returns (uint256) {
return LibSherX.viewAccrueUSDPool();
}
function getTotalUsdLastSettled() external view override returns (uint256) {
return SherXStorage.sx().totalUsdLastSettled;
}
function getStoredUsd(IERC20 _token) external view override returns (uint256) {
return SherXStorage.sx().tokenUSD[_token];
}
function getUnmintedSherX(IERC20 _token) internal view returns (uint256) {
return LibPool.getTotalUnmintedSherX(_token);
}
function getTotalSherXUnminted() external view override returns (uint256) {
SherXStorage.Base storage sx = SherXStorage.sx();
GovStorage.Base storage gs = GovStorage.gs();
uint256 total =
block
.number
.sub(gs.watsonsSherxLastAccrued)
.mul(sx.sherXPerBlock)
.mul(gs.watsonsSherxWeight)
.div(type(uint16).max);
for (uint256 i; i < gs.tokensStaker.length; i++) {
total = total.add(getUnmintedSherX(gs.tokensStaker[i]));
}
return total;
}
function getTotalSherX() external view override returns (uint256) {
return LibSherX.getTotalSherX();
}
function getSherXPerBlock() external view override returns (uint256) {
return SherXStorage.sx().sherXPerBlock;
}
function getSherXBalance() external view override returns (uint256) {
return getSherXBalance(msg.sender);
}
function getSherXBalance(address _user) public view override returns (uint256) {
SherXERC20Storage.Base storage sx20 = SherXERC20Storage.sx20();
uint256 balance = sx20.balances[_user];
GovStorage.Base storage gs = GovStorage.gs();
for (uint256 i; i < gs.tokensStaker.length; i++) {
balance = balance.add(LibPool.getUnallocatedSherXFor(_user, gs.tokensStaker[i]));
}
return balance;
}
function getInternalTotalSupply() external view override returns (uint256) {
return SherXStorage.sx().internalTotalSupply;
}
function getInternalTotalSupplySettled() external view override returns (uint256) {
return SherXStorage.sx().internalTotalSupplySettled;
}
function calcUnderlying()
external
view
override
returns (IERC20[] memory tokens, uint256[] memory amounts)
{
return calcUnderlying(msg.sender);
}
function calcUnderlying(address _user)
public
view
override
returns (IERC20[] memory tokens, uint256[] memory amounts)
{
return LibSherX.calcUnderlying(getSherXBalance(_user));
}
function calcUnderlying(uint256 _amount)
external
view
override
returns (IERC20[] memory tokens, uint256[] memory amounts)
{
return LibSherX.calcUnderlying(_amount);
}
function calcUnderlyingInStoredUSD() external view override returns (uint256) {
SherXERC20Storage.Base storage sx20 = SherXERC20Storage.sx20();
return calcUnderlyingInStoredUSD(sx20.balances[msg.sender]);
}
function calcUnderlyingInStoredUSD(uint256 _amount) public view override returns (uint256 usd) {
SherXStorage.Base storage sx = SherXStorage.sx();
GovStorage.Base storage gs = GovStorage.gs();
uint256 total = LibSherX.getTotalSherX();
if (total == 0) {
return 0;
}
for (uint256 i; i < gs.tokensSherX.length; i++) {
IERC20 token = gs.tokensSherX[i];
usd = usd.add(
PoolStorage
.ps(token)
.sherXUnderlying
.add(LibPool.getTotalAccruedDebt(token))
.mul(_amount)
.mul(sx.tokenUSD[token])
.div(10**18)
.div(total)
);
}
}
//
// State changing methods
//
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) external override {
doYield(ILock(msg.sender), from, to, amount);
}
function setInitialWeight() external override onlyGovMain {
GovStorage.Base storage gs = GovStorage.gs();
require(gs.watsonsAddress != address(0), 'WATS_UNSET');
require(gs.watsonsSherxWeight == 0, 'ALREADY_INIT');
for (uint256 i; i < gs.tokensStaker.length; i++) {
PoolStorage.Base storage ps = PoolStorage.ps(gs.tokensStaker[i]);
require(ps.sherXWeight == 0, 'ALREADY_INIT_2');
}
gs.watsonsSherxWeight = type(uint16).max;
}
function setWeights(
IERC20[] memory _tokens,
uint16[] memory _weights,
uint256 _watsons
) external override onlyGovMain {
require(_tokens.length == _weights.length, 'LENGTH');
// NOTE: can potentially be made more gas efficient
// Do not loop over all staker tokens
// But just over the tokens in the _tokens array
LibSherX.accrueSherX();
GovStorage.Base storage gs = GovStorage.gs();
uint256 totalWeightNew;
uint256 totalWeightOld;
for (uint256 i; i < _tokens.length; i++) {
PoolStorage.Base storage ps = PoolStorage.ps(_tokens[i]);
// Disabled tokens can not have ps.sherXWeight != 0
require(ps.stakes, 'DISABLED');
totalWeightNew = totalWeightNew.add(_weights[i]);
totalWeightOld = totalWeightOld.add(ps.sherXWeight);
ps.sherXWeight = _weights[i];
}
if (_watsons != type(uint256).max) {
totalWeightNew = totalWeightNew.add(uint16(_watsons));
totalWeightOld = totalWeightOld.add(gs.watsonsSherxWeight);
gs.watsonsSherxWeight = uint16(_watsons);
}
require(totalWeightNew == totalWeightOld, 'SUM');
}
function harvest() external override {
harvestFor(msg.sender);
}
function harvest(ILock _token) external override {
harvestFor(msg.sender, _token);
}
function harvest(ILock[] calldata _tokens) external override {
for (uint256 i; i < _tokens.length; i++) {
harvestFor(msg.sender, _tokens[i]);
}
}
function harvestFor(address _user) public override {
GovStorage.Base storage gs = GovStorage.gs();
uint256 length = gs.tokensStaker.length;
for (uint256 i; i < length; i++) {
PoolStorage.Base storage ps = PoolStorage.ps(gs.tokensStaker[i]);
harvestFor(_user, ps.lockToken);
}
}
function harvestFor(address _user, ILock _token) public override {
// could potentially call harvest function for token that are not in the pool
// if balance != 0, tx will revert
uint256 stakeBalance = _token.balanceOf(_user);
if (stakeBalance != 0) {
doYield(_token, _user, _user, 0);
}
emit Harvest(_user, _token);
}
function harvestFor(address _user, ILock[] calldata _tokens) external override {
for (uint256 i; i < _tokens.length; i++) {
harvestFor(_user, _tokens[i]);
}
}
function redeem(uint256 _amount, address _receiver) external override {
require(_amount != 0, 'AMOUNT');
require(_receiver != address(0), 'RECEIVER');
SherXStorage.Base storage sx = SherXStorage.sx();
LibSherX.accrueUSDPool();
// Note: LibSherX.accrueSherX() is removed as the calcUnderlying already takes it into consideration (without changing state)
// Calculate the current `amounts` of underlying `tokens` for `_amount` of SherX
(IERC20[] memory tokens, uint256[] memory amounts) = LibSherX.calcUnderlying(_amount);
LibSherXERC20.burn(msg.sender, _amount);
uint256 subUsdPool = 0;
for (uint256 i; i < tokens.length; i++) {
PoolStorage.Base storage ps = PoolStorage.ps(tokens[i]);
// Expensive operation, only execute to prevent tx reverts
if (amounts[i] > ps.sherXUnderlying) {
LibPool.payOffDebtAll(tokens[i]);
}
// Remove the token as underlying of SherX
ps.sherXUnderlying = ps.sherXUnderlying.sub(amounts[i]);
// As the tokens are transferred, remove from the current usdPool
// By summing the total that needs to be deducted in the `subUsdPool` value
subUsdPool = subUsdPool.add(amounts[i].mul(sx.tokenUSD[tokens[i]]).div(10**18));
tokens[i].safeTransfer(_receiver, amounts[i]);
}
sx.totalUsdPool = sx.totalUsdPool.sub(subUsdPool);
LibSherX.settleInternalSupply(_amount);
}
function accrueSherX() external override {
LibSherX.accrueSherX();
}
function accrueSherX(IERC20 _token) external override {
LibSherX.accrueSherX(_token);
}
function accrueSherXWatsons() external override {
LibSherX.accrueSherXWatsons();
}
/// @notice The `from` account could earn SHERX by holding `token` overtime, the earned amount will be staked.
/// @param token The LockToken that could be eligble for SHERX rewards
/// @param from The current account that is holding the tokens
/// @param to The new account that will be holding the tokens
/// @param amount The amount of tokens being transferred
function doYield(
ILock token,
address from,
address to,
uint256 amount
) private {
// The LockToken represents a token staked in the solution.
// Verify if the right LockToken is used.
IERC20 underlying = token.underlying();
PoolStorage.Base storage ps = PoolStorage.ps(underlying);
require(ps.lockToken == token, 'SENDER');
LibSherX.accrueSherX(underlying);
uint256 userAmount = ps.lockToken.balanceOf(from);
uint256 totalAmount = ps.lockToken.totalSupply();
uint256 ineligible_yield_amount;
if (totalAmount != 0) {
// Is `amount` instead of `userAmount` as the `ineligible_yield_amount` is 'transferred' to `to`
ineligible_yield_amount = ps.sWeight.mul(amount).div(totalAmount);
} else {
ineligible_yield_amount = amount;
}
if (from != address(0)) {
uint256 raw_amount = ps.sWeight.mul(userAmount).div(totalAmount);
uint256 withdrawable_amount = raw_amount.sub(ps.sWithdrawn[from]);
if (withdrawable_amount != 0) {
// store the data in a single calc
ps.sWithdrawn[from] = raw_amount.sub(ineligible_yield_amount);
// The `withdrawable_amount` is allocated to `from`, subtract from `unallocatedSherX`
ps.unallocatedSherX = ps.unallocatedSherX.sub(withdrawable_amount);
PoolStorage.Base storage psSherX = PoolStorage.ps(IERC20(address(this)));
if (from == address(this)) {
// add SherX harvested by the pool itself to first money out pool.
psSherX.stakeBalance = psSherX.stakeBalance.add(withdrawable_amount);
psSherX.firstMoneyOut = psSherX.firstMoneyOut.add(withdrawable_amount);
} else {
LibPool.stake(psSherX, withdrawable_amount, from);
}
} else {
ps.sWithdrawn[from] = ps.sWithdrawn[from].sub(ineligible_yield_amount);
}
} else {
ps.sWeight = ps.sWeight.add(ineligible_yield_amount);
}
if (to != address(0)) {
ps.sWithdrawn[to] = ps.sWithdrawn[to].add(ineligible_yield_amount);
} else {
ps.sWeight = ps.sWeight.sub(ineligible_yield_amount);
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.7.6;
/******************************************************************************\
* Author: Evert Kors <[email protected]> (https://twitter.com/evert0x)
* Sherlock Protocol: https://sherlock.xyz
/******************************************************************************/
import '../interfaces/ILock.sol';
/// @title SHERX Logic Controller
/// @author Evert Kors
/// @notice This contract is used to manage functions related to the SHERX token
/// @dev Contract is meant to be included as a facet in the diamond
interface ISherX {
//
// Events
//
/// @notice Sends an event whenever a staker "harvests" earned SHERX
/// @notice Harvesting is when SHERX "interest" is staked in the SHERX pool
/// @param user Address of the user for whom SHERX is harvested
/// @param token Token which had accumulated the harvested SHERX
event Harvest(address indexed user, IERC20 indexed token);
//
// View methods
//
/// @notice Returns the USD amount of tokens being added to the SHERX pool each block
/// @return USD amount added to SHERX pool per block
function getTotalUsdPerBlock() external view returns (uint256);
/// @notice Returns the internal USD amount of tokens represented by SHERX
/// @return Last stored value of total internal USD underlying SHERX
function getTotalUsdPoolStored() external view returns (uint256);
/// @notice Returns the total USD amount of tokens represented by SHERX
/// @return Current total internal USD underlying SHERX
function getTotalUsdPool() external view returns (uint256);
/// @notice Returns block number at which the total USD underlying SHERX was last stored
/// @return Block number for stored USD underlying SHERX
function getTotalUsdLastSettled() external view returns (uint256);
/// @notice Returns stored USD amount for `_token`
/// @param _token Token used for protocol premiums
/// @return Stored USD amount
function getStoredUsd(IERC20 _token) external view returns (uint256);
/// @notice Returns SHERX that has not been minted yet
/// @return Unminted amount of SHERX tokens
function getTotalSherXUnminted() external view returns (uint256);
/// @notice Returns total amount of SHERX, including unminted
/// @return Total amount of SHERX tokens
function getTotalSherX() external view returns (uint256);
/// @notice Returns the amount of SHERX created per block
/// @return SHERX per block
function getSherXPerBlock() external view returns (uint256);
/// @notice Returns the total amount of SHERX accrued by the sender
/// @return Total SHERX balance
function getSherXBalance() external view returns (uint256);
/// @notice Returns the amount of SHERX accrued by `_user`
/// @param _user address to get the SHERX balance of
/// @return Total SHERX balance
function getSherXBalance(address _user) external view returns (uint256);
/// @notice Returns the total supply of SHERX from storage (only used internally)
/// @return Total supply of SHERX
function getInternalTotalSupply() external view returns (uint256);
/// @notice Returns the block number when total SHERX supply was last set in storage
/// @return block number of last write to storage for the total SHERX supply
function getInternalTotalSupplySettled() external view returns (uint256);
/// @notice Returns the tokens and amounts underlying msg.sender's SHERX balance
/// @return tokens Array of ERC-20 tokens representing the underlying
/// @return amounts Corresponding amounts of the underlying tokens
function calcUnderlying()
external
view
returns (IERC20[] memory tokens, uint256[] memory amounts);
/// @notice Returns the tokens and amounts underlying `_user` SHERX balance
/// @param _user Account whose underlying SHERX tokens should be queried
/// @return tokens Array of ERC-20 tokens representing the underlying
/// @return amounts Corresponding amounts of the underlying tokens
function calcUnderlying(address _user)
external
view
returns (IERC20[] memory tokens, uint256[] memory amounts);
/// @notice Returns the tokens and amounts underlying the given amount of SHERX
/// @param _amount Amount of SHERX tokens to calculate the underlying tokens of
/// @return tokens Array of ERC-20 tokens representing the underlying
/// @return amounts Corresponding amounts of the underlying tokens
function calcUnderlying(uint256 _amount)
external
view
returns (IERC20[] memory tokens, uint256[] memory amounts);
/// @notice Returns the internal USD amount underlying senders SHERX
/// @return USD value of SHERX accrued to sender
function calcUnderlyingInStoredUSD() external view returns (uint256);
/// @notice Returns the internal USD amount underlying the given amount SHERX
/// @param _amount Amount of SHERX tokens to find the underlying USD value of
/// @return usd USD value of the given amount of SHERX
function calcUnderlyingInStoredUSD(uint256 _amount) external view returns (uint256 usd);
//
// State changing methods
//
/// @notice Function called by lockTokens before transfer
/// @param from Address from which lockTokens are being transferred
/// @param to Address to which lockTokens are being transferred
/// @param amount Amount of lockTokens to be transferred
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) external;
/// @notice Set initial SHERX distribution to Watsons
function setInitialWeight() external;
/// @notice Set SHERX distribution
/// @param _tokens Array of tokens to set the weights of
/// @param _weights Respective weighting for each token
/// @param _watsons Weighting to set for the Watsons
function setWeights(
IERC20[] memory _tokens,
uint16[] memory _weights,
uint256 _watsons
) external;
/// @notice Harvest all tokens on behalf of the sender
function harvest() external;
/// @notice Harvest `_token` on behalf of the sender
/// @param _token Token to harvest accrued SHERX for
function harvest(ILock _token) external;
/// @notice Harvest `_tokens` on behalf of the sender
/// @param _tokens Array of tokens to harvest accrued SHERX for
function harvest(ILock[] calldata _tokens) external;
/// @notice Harvest all tokens for `_user`
/// @param _user Account for which to harvest SHERX
function harvestFor(address _user) external;
/// @notice Harvest `_token` for `_user`
/// @param _user Account for which to harvest SHERX
/// @param _token Token to harvest
function harvestFor(address _user, ILock _token) external;
/// @notice Harvest `_tokens` for `_user`
/// @param _user Account for which to harvest SHERX
/// @param _tokens Array of tokens to harvest accrued SHERX for
function harvestFor(address _user, ILock[] calldata _tokens) external;
/// @notice Redeems SHERX tokens for the underlying collateral
/// @param _amount Amount of SHERX tokens to redeem
/// @param _receiver Address to send redeemed tokens to
function redeem(uint256 _amount, address _receiver) external;
/// @notice Accrue SHERX based on internal weights
function accrueSherX() external;
/// @notice Accrues SHERX to specific token
/// @param _token Token to accure SHERX to.
function accrueSherX(IERC20 _token) external;
/// @notice Accrues SHERX to the Watsons.
function accrueSherXWatsons() external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.7.6;
/******************************************************************************\
* Author: Evert Kors <[email protected]> (https://twitter.com/evert0x)
* Sherlock Protocol: https://sherlock.xyz
* Inspired by: https://github.com/pie-dao/PieVaults/blob/master/contracts/facets/ERC20/LibERC20Storage.sol
/******************************************************************************/
library SherXERC20Storage {
bytes32 constant SHERX_ERC20_STORAGE_POSITION = keccak256('diamond.sherlock.x.erc20');
struct Base {
string name;
string symbol;
uint256 totalSupply;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowances;
}
function sx20() internal pure returns (Base storage sx20x) {
bytes32 position = SHERX_ERC20_STORAGE_POSITION;
assembly {
sx20x.slot := position
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.7.6;
/******************************************************************************\
* Author: Evert Kors <[email protected]> (https://twitter.com/evert0x)
* Sherlock Protocol: https://sherlock.xyz
/******************************************************************************/
import '@openzeppelin/contracts/math/SafeMath.sol';
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import '../storage/PoolStorage.sol';
import '../storage/SherXStorage.sol';
library LibPool {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using SafeERC20 for ILock;
function stakeBalance(PoolStorage.Base storage ps) public view returns (uint256) {
uint256 balance = ps.stakeBalance;
if (address(ps.strategy) != address(0)) {
balance = balance.add(ps.strategy.balanceOf());
}
return balance.sub(ps.firstMoneyOut);
}
function accruedDebt(bytes32 _protocol, IERC20 _token) external view returns (uint256) {
PoolStorage.Base storage ps = PoolStorage.ps(_token);
return _accruedDebt(ps, _protocol, block.number.sub(ps.totalPremiumLastPaid));
}
function getTotalAccruedDebt(IERC20 _token) external view returns (uint256) {
PoolStorage.Base storage ps = PoolStorage.ps(_token);
return _getTotalAccruedDebt(ps, block.number.sub(ps.totalPremiumLastPaid));
}
function getTotalUnmintedSherX(IERC20 _token) public view returns (uint256 sherX) {
PoolStorage.Base storage ps = PoolStorage.ps(_token);
SherXStorage.Base storage sx = SherXStorage.sx();
sherX = block.number.sub(ps.sherXLastAccrued).mul(sx.sherXPerBlock).mul(ps.sherXWeight).div(
type(uint16).max
);
}
function getUnallocatedSherXFor(address _user, IERC20 _token)
external
view
returns (uint256 withdrawable_amount)
{
PoolStorage.Base storage ps = PoolStorage.ps(_token);
uint256 userAmount = ps.lockToken.balanceOf(_user);
uint256 totalAmount = ps.lockToken.totalSupply();
if (totalAmount == 0) {
return 0;
}
uint256 raw_amount =
ps.sWeight.add(getTotalUnmintedSherX(_token)).mul(userAmount).div(totalAmount);
withdrawable_amount = raw_amount.sub(ps.sWithdrawn[_user]);
}
function stake(
PoolStorage.Base storage ps,
uint256 _amount,
address _receiver
) external returns (uint256 lock) {
uint256 totalLock = ps.lockToken.totalSupply();
if (totalLock == 0) {
// mint initial lock
lock = 10**18;
} else {
// mint lock based on funds in pool
lock = _amount.mul(totalLock).div(stakeBalance(ps));
}
ps.stakeBalance = ps.stakeBalance.add(_amount);
ps.lockToken.mint(_receiver, lock);
}
function payOffDebtAll(IERC20 _token) external {
PoolStorage.Base storage ps = PoolStorage.ps(_token);
uint256 blocks = block.number.sub(ps.totalPremiumLastPaid);
uint256 totalAccruedDebt;
uint256 length = ps.protocols.length;
for (uint256 i = 0; i < length; i++) {
totalAccruedDebt = totalAccruedDebt.add(_payOffDebt(ps, ps.protocols[i], blocks));
}
// move funds to the sherX etf
ps.sherXUnderlying = ps.sherXUnderlying.add(totalAccruedDebt);
ps.totalPremiumLastPaid = uint40(block.number);
}
function _payOffDebt(
PoolStorage.Base storage ps,
bytes32 _protocol,
uint256 _blocks
) private returns (uint256 debt) {
debt = _accruedDebt(ps, _protocol, _blocks);
ps.protocolBalance[_protocol] = ps.protocolBalance[_protocol].sub(debt);
}
function _accruedDebt(
PoolStorage.Base storage ps,
bytes32 _protocol,
uint256 _blocks
) private view returns (uint256) {
return _blocks.mul(ps.protocolPremium[_protocol]);
}
function _getTotalAccruedDebt(PoolStorage.Base storage ps, uint256 _blocks)
private
view
returns (uint256)
{
return _blocks.mul(ps.totalPremiumPerBlock);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.7.6;
/******************************************************************************\
* Author: Evert Kors <[email protected]> (https://twitter.com/evert0x)
* Sherlock Protocol: https://sherlock.xyz
/******************************************************************************/
import '../storage/PoolStorage.sol';
import '../storage/GovStorage.sol';
import './LibSherXERC20.sol';
import './LibPool.sol';
library LibSherX {
using SafeMath for uint256;
function viewAccrueUSDPool() public view returns (uint256 totalUsdPool) {
SherXStorage.Base storage sx = SherXStorage.sx();
totalUsdPool = sx.totalUsdPool.add(
block.number.sub(sx.totalUsdLastSettled).mul(sx.totalUsdPerBlock)
);
}
function accrueUSDPool() external returns (uint256 totalUsdPool) {
SherXStorage.Base storage sx = SherXStorage.sx();
totalUsdPool = viewAccrueUSDPool();
sx.totalUsdPool = totalUsdPool;
sx.totalUsdLastSettled = block.number;
}
function settleInternalSupply(uint256 _deduct) external {
SherXStorage.Base storage sx = SherXStorage.sx();
sx.internalTotalSupply = getTotalSherX().sub(_deduct);
sx.internalTotalSupplySettled = block.number;
}
function getTotalSherX() public view returns (uint256) {
// calc by taking base supply, block at, and calc it by taking base + now - block_at * sherxperblock
// update baseSupply on every premium update
SherXStorage.Base storage sx = SherXStorage.sx();
return
sx.internalTotalSupply.add(
block.number.sub(sx.internalTotalSupplySettled).mul(sx.sherXPerBlock)
);
}
function calcUnderlying(uint256 _amount)
external
view
returns (IERC20[] memory tokens, uint256[] memory amounts)
{
GovStorage.Base storage gs = GovStorage.gs();
uint256 length = gs.tokensSherX.length;
tokens = gs.tokensSherX;
amounts = new uint256[](length);
uint256 total = getTotalSherX();
for (uint256 i; i < length; i++) {
IERC20 token = gs.tokensSherX[i];
if (total != 0) {
PoolStorage.Base storage ps = PoolStorage.ps(token);
amounts[i] = ps.sherXUnderlying.add(LibPool.getTotalAccruedDebt(token)).mul(_amount).div(
total
);
}
}
}
function accrueSherX(IERC20 _token) external {
SherXStorage.Base storage sx = SherXStorage.sx();
uint256 sherX = _accrueSherX(_token, sx.sherXPerBlock);
if (sherX != 0) {
LibSherXERC20.mint(address(this), sherX);
}
}
function accrueSherXWatsons() external {
SherXStorage.Base storage sx = SherXStorage.sx();
_accrueSherXWatsons(sx.sherXPerBlock);
}
function accrueSherX() external {
// loop over pools, increase the pool + pool_weight based on the distribution weights
SherXStorage.Base storage sx = SherXStorage.sx();
GovStorage.Base storage gs = GovStorage.gs();
uint256 sherXPerBlock = sx.sherXPerBlock;
uint256 sherX;
uint256 length = gs.tokensStaker.length;
for (uint256 i; i < length; i++) {
sherX = sherX.add(_accrueSherX(gs.tokensStaker[i], sherXPerBlock));
}
if (sherX != 0) {
LibSherXERC20.mint(address(this), sherX);
}
_accrueSherXWatsons(sherXPerBlock);
}
function _accrueSherXWatsons(uint256 sherXPerBlock) private {
GovStorage.Base storage gs = GovStorage.gs();
uint256 sherX =
block
.number
.sub(gs.watsonsSherxLastAccrued)
.mul(sherXPerBlock)
.mul(gs.watsonsSherxWeight)
.div(type(uint16).max);
// need to settle before return, as updating the sherxperlblock/weight
// after it was 0 will result in a too big amount (accured will be < block.number)
gs.watsonsSherxLastAccrued = uint40(block.number);
if (sherX == 0) {
return;
}
LibSherXERC20.mint(gs.watsonsAddress, sherX);
}
function _accrueSherX(IERC20 _token, uint256 sherXPerBlock) private returns (uint256 sherX) {
PoolStorage.Base storage ps = PoolStorage.ps(_token);
uint256 lastAccrued = ps.sherXLastAccrued;
if (lastAccrued == block.number) {
return 0;
}
sherX = block.number.sub(lastAccrued).mul(sherXPerBlock).mul(ps.sherXWeight).div(
type(uint16).max
);
// need to settle before return, as updating the sherxperlblock/weight
// after it was 0 will result in a too big amount (accured will be < block.number)
ps.sherXLastAccrued = uint40(block.number);
if (address(_token) == address(this)) {
ps.stakeBalance = ps.stakeBalance.add(sherX);
} else {
ps.unallocatedSherX = ps.unallocatedSherX.add(sherX);
ps.sWeight = ps.sWeight.add(sherX);
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.7.6;
/******************************************************************************\
* Author: Evert Kors <[email protected]> (https://twitter.com/evert0x)
* Sherlock Protocol: https://sherlock.xyz
* Inspired by: https://github.com/pie-dao/PieVaults/blob/master/contracts/facets/ERC20/LibERC20.sol
/******************************************************************************/
import '@openzeppelin/contracts/math/SafeMath.sol';
import '../storage/SherXERC20Storage.sol';
library LibSherXERC20 {
using SafeMath for uint256;
// Need to include events locally because `emit Interface.Event(params)` does not work
event Transfer(address indexed from, address indexed to, uint256 amount);
function mint(address _to, uint256 _amount) internal {
SherXERC20Storage.Base storage sx20 = SherXERC20Storage.sx20();
sx20.balances[_to] = sx20.balances[_to].add(_amount);
sx20.totalSupply = sx20.totalSupply.add(_amount);
emit Transfer(address(0), _to, _amount);
}
function burn(address _from, uint256 _amount) internal {
SherXERC20Storage.Base storage sx20 = SherXERC20Storage.sx20();
sx20.balances[_from] = sx20.balances[_from].sub(_amount);
sx20.totalSupply = sx20.totalSupply.sub(_amount);
emit Transfer(_from, address(0), _amount);
}
function approve(
address _from,
address _to,
uint256 _amount
) internal returns (bool) {
SherXERC20Storage.sx20().allowances[_from][_to] = _amount;
return true;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.7.6;
/******************************************************************************\
* Author: Evert Kors <[email protected]> (https://twitter.com/evert0x)
* Sherlock Protocol: https://sherlock.xyz
/******************************************************************************/
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
/// @title Lock Token
/// @author Evert Kors
/// @notice Lock tokens represent a stake in Sherlock
interface ILock is IERC20 {
/// @notice Returns the owner of this contract
/// @return Owner address
/// @dev Should be equal to the Sherlock address
function getOwner() external view returns (address);
/// @notice Returns token it represents
/// @return Token address
function underlying() external view returns (IERC20);
/// @notice Mint `_amount` tokens for `_account`
/// @param _account Account to receive tokens
/// @param _amount Amount to be minted
function mint(address _account, uint256 _amount) external;
/// @notice Burn `_amount` tokens for `_account`
/// @param _account Account to be burned
/// @param _amount Amount to be burned
function burn(address _account, uint256 _amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./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: GPL-2.0-or-later
pragma solidity 0.7.6;
/******************************************************************************\
* Author: Evert Kors <[email protected]> (https://twitter.com/evert0x)
* Sherlock Protocol: https://sherlock.xyz
/******************************************************************************/
import '../interfaces/ILock.sol';
import '../interfaces/IStrategy.sol';
// TokenStorage
library PoolStorage {
bytes32 constant POOL_STORAGE_PREFIX = 'diamond.sherlock.pool.';
struct Base {
address govPool;
// Variable used to calculate the fee when activating the cooldown
// Max value is type(uint32).max which creates a 100% fee on the withdrawal
uint32 activateCooldownFee;
// How much sherX is distributed to stakers of this token
// The max value is type(uint16).max, which means 100% of the total SherX minted is allocated to this pool
uint16 sherXWeight;
// The last block the total amount of rewards were accrued.
// Accrueing SherX increases the `unallocatedSherX` variable
uint40 sherXLastAccrued;
// Indicates if protocol are able to pay premiums with this token
// If this value is true, the token is also included as underlying of the SherX
bool premiums;
// Protocol debt can only be settled at once for all the protocols at the same time
// This variable is the block number the last time all the protocols debt was settled
uint40 totalPremiumLastPaid;
//
// Staking
//
// Indicates if stakers can stake funds in the pool
bool stakes;
// Address of the lockToken. Representing stakes in this pool
ILock lockToken;
// The total amount staked by the stakers in this pool, including value of `firstMoneyOut`
// if you exclude the `firstMoneyOut` from this value, you get the actual amount of tokens staked
// This value is also excluding funds deposited in a strategy.
uint256 stakeBalance;
// All the withdrawals by an account
// The values of the struct are all deleted if expiry() or unstake() function is called
mapping(address => UnstakeEntry[]) unstakeEntries;
// Represents the amount of tokens in the first money out pool
uint256 firstMoneyOut;
// If the `stakes` = true, the stakers can be rewarded by sherx
// stakers can claim their rewards by calling the harvest() function
// SherX could be minted before the stakers call the harvest() function
// Minted SherX that is assigned as reward for the pool will be added to this value
uint256 unallocatedSherX;
// Non-native variables
// These variables are used to calculate the right amount of SherX rewards for the token staked
mapping(address => uint256) sWithdrawn;
uint256 sWeight;
// Storing the protocol token balance based on the protocols bytes32 indentifier
mapping(bytes32 => uint256) protocolBalance;
// Storing the protocol premium, the amount of debt the protocol builds up per block.
// This is based on the bytes32 identifier of the protocol.
mapping(bytes32 => uint256) protocolPremium;
// The sum of all the protocol premiums, the total amount of debt that builds up in this token. (per block)
uint256 totalPremiumPerBlock;
// How much tokens are used as underlying for SherX
uint256 sherXUnderlying;
// Check if the protocol is included in the token pool
// The protocol can deposit balances if this is the case
mapping(bytes32 => bool) isProtocol;
// Array of protocols that are registered in this pool
bytes32[] protocols;
// Active strategy for this token pool
IStrategy strategy;
}
struct UnstakeEntry {
// The block number the cooldown is activated
uint40 blockInitiated;
// The amount of lock tokens to be withdrawn
uint256 lock;
}
function ps(IERC20 _token) internal pure returns (Base storage psx) {
bytes32 position = keccak256(abi.encodePacked(POOL_STORAGE_PREFIX, _token));
assembly {
psx.slot := position
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.7.6;
/******************************************************************************\
* Author: Evert Kors <[email protected]> (https://twitter.com/evert0x)
* Sherlock Protocol: https://sherlock.xyz
/******************************************************************************/
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
library SherXStorage {
bytes32 constant SHERX_STORAGE_POSITION = keccak256('diamond.sherlock.x');
struct Base {
mapping(IERC20 => uint256) tokenUSD;
uint256 totalUsdPerBlock;
uint256 totalUsdPool;
uint256 totalUsdLastSettled;
uint256 sherXPerBlock;
uint256 internalTotalSupply;
uint256 internalTotalSupplySettled;
}
function sx() internal pure returns (Base storage sxx) {
bytes32 position = SHERX_STORAGE_POSITION;
assembly {
sxx.slot := position
}
}
}
// 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: GPL-2.0-or-later
pragma solidity 0.7.6;
/******************************************************************************\
* Author: Evert Kors <[email protected]> (https://twitter.com/evert0x)
* Sherlock Protocol: https://sherlock.xyz
/******************************************************************************/
import '@openzeppelin/contracts/token/ERC20/ERC20.sol';
interface IStrategy {
function want() external view returns (ERC20);
function withdrawAll() external returns (uint256);
function withdraw(uint256 _amount) external;
function deposit() external;
function balanceOf() external view returns (uint256);
function sweep(address _receiver, IERC20[] memory _extraTokens) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.7.6;
/******************************************************************************\
* Author: Evert Kors <[email protected]> (https://twitter.com/evert0x)
* Sherlock Protocol: https://sherlock.xyz
/******************************************************************************/
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
library GovStorage {
bytes32 constant GOV_STORAGE_POSITION = keccak256('diamond.sherlock.gov');
struct Base {
// The address appointed as the govMain entity
address govMain;
// NOTE: UNUSED
mapping(bytes32 => address) protocolManagers;
// Based on the protocol identifier, get the address of the protocol that is able the withdraw balances
mapping(bytes32 => address) protocolAgents;
// Check if the protocol is included in the solution at all
mapping(bytes32 => bool) protocolIsCovered;
// The array of tokens the accounts are able to stake in
IERC20[] tokensStaker;
// The array of tokens the protocol are able to pay premium in
// These tokens will also be the underlying for SherX
IERC20[] tokensSherX;
// The address of the watsons, an account that can receive SherX rewards
address watsonsAddress;
// How much sherX is distributed to this account
// The max value is type(uint16).max, which means 100% of the total SherX minted is allocated to this acocunt
uint16 watsonsSherxWeight;
// The last block the total amount of rewards were accrued.
uint40 watsonsSherxLastAccrued;
// Max amount of SherX token to be in the `tokensSherX` array
uint8 maxTokensSherX;
// Max amount of Staker token to be in the `tokensStaker` array
uint8 maxTokensStaker;
// Max amount of protocol to be in single pool
uint8 maxProtocolPool;
// The amount of blocks the cooldown period takes
uint40 unstakeCooldown;
// The amount of blocks for the window of opportunity of unstaking
uint40 unstakeWindow;
}
function gs() internal pure returns (Base storage gsx) {
bytes32 position = GOV_STORAGE_POSITION;
assembly {
gsx.slot := position
}
}
}
| @title SHERX Logic Controller @author Evert Kors @notice This contract is used to manage functions related to the SHERX token @dev Contract is meant to be included as a facet in the diamond Events View methods State changing methods | interface ISherX {
event Harvest(address indexed user, IERC20 indexed token);
function getTotalUsdPerBlock() external view returns (uint256);
function getTotalUsdPoolStored() external view returns (uint256);
function getTotalUsdPool() external view returns (uint256);
function getTotalUsdLastSettled() external view returns (uint256);
function getStoredUsd(IERC20 _token) external view returns (uint256);
function getTotalSherXUnminted() external view returns (uint256);
function getTotalSherX() external view returns (uint256);
function getSherXPerBlock() external view returns (uint256);
function getSherXBalance() external view returns (uint256);
function getSherXBalance(address _user) external view returns (uint256);
function getInternalTotalSupply() external view returns (uint256);
function getInternalTotalSupplySettled() external view returns (uint256);
function calcUnderlying()
external
view
returns (IERC20[] memory tokens, uint256[] memory amounts);
function calcUnderlying(address _user)
external
view
returns (IERC20[] memory tokens, uint256[] memory amounts);
function calcUnderlying(uint256 _amount)
external
view
returns (IERC20[] memory tokens, uint256[] memory amounts);
function calcUnderlyingInStoredUSD() external view returns (uint256);
function calcUnderlyingInStoredUSD(uint256 _amount) external view returns (uint256 usd);
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) external;
function setInitialWeight() external;
function setWeights(
IERC20[] memory _tokens,
uint16[] memory _weights,
uint256 _watsons
) external;
function harvest() external;
function harvest(ILock _token) external;
function harvest(ILock[] calldata _tokens) external;
function harvestFor(address _user) external;
function harvestFor(address _user, ILock _token) external;
function harvestFor(address _user, ILock[] calldata _tokens) external;
function redeem(uint256 _amount, address _receiver) external;
function accrueSherX() external;
function accrueSherX(IERC20 _token) external;
function accrueSherXWatsons() external;
pragma solidity 0.7.6;
}
| 1,374,937 | [
1,
2664,
654,
60,
10287,
6629,
225,
512,
1097,
1475,
1383,
225,
1220,
6835,
353,
1399,
358,
10680,
4186,
3746,
358,
326,
348,
3891,
60,
1147,
225,
13456,
353,
20348,
358,
506,
5849,
487,
279,
11082,
316,
326,
4314,
301,
1434,
9043,
4441,
2590,
3287,
12770,
2590,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5831,
467,
1555,
264,
60,
288,
203,
203,
225,
871,
670,
297,
26923,
12,
2867,
8808,
729,
16,
467,
654,
39,
3462,
8808,
1147,
1769,
203,
203,
203,
225,
445,
12831,
3477,
72,
2173,
1768,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
225,
445,
12831,
3477,
72,
2864,
18005,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
225,
445,
12831,
3477,
72,
2864,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
225,
445,
12831,
3477,
72,
3024,
694,
88,
1259,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
225,
445,
15818,
72,
3477,
72,
12,
45,
654,
39,
3462,
389,
2316,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
225,
445,
12831,
1555,
264,
60,
984,
81,
474,
329,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
225,
445,
12831,
1555,
264,
60,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
225,
445,
1322,
1614,
60,
2173,
1768,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
225,
445,
1322,
1614,
60,
13937,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
225,
445,
1322,
1614,
60,
13937,
12,
2867,
389,
1355,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
225,
445,
16918,
5269,
3088,
1283,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
225,
445,
16918,
5269,
3088,
1283,
694,
88,
1259,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
225,
445,
7029,
14655,
6291,
1435,
203,
565,
3903,
203,
2
] |
/**
*Submitted for verification at Etherscan.io on 2020-07-28
*/
pragma solidity 0.6.0;
/**
* @title Price contract
* @dev Price check and call
*/
contract Nest_3_OfferPrice{
using SafeMath for uint256;
using address_make_payable for address;
using SafeERC20 for ERC20;
Nest_3_VoteFactory _voteFactory; // Voting contract
ERC20 _nestToken; // NestToken
Nest_NToken_TokenMapping _tokenMapping; // NToken mapping
Nest_3_OfferMain _offerMain; // Offering main contract
Nest_3_Abonus _abonus; // Bonus pool
address _nTokeOfferMain; // NToken offering main contract
address _destructionAddress; // Destruction contract address
address _nTokenAuction; // NToken auction contract address
struct PriceInfo { // Block price
uint256 ethAmount; // ETH amount
uint256 erc20Amount; // Erc20 amount
uint256 frontBlock; // Last effective block
address offerOwner; // Offering address
}
struct TokenInfo { // Token offer information
mapping(uint256 => PriceInfo) priceInfoList; // Block price list, block number => block price
uint256 latestOffer; // Latest effective block
uint256 priceCostLeast; // Minimum ETH cost for prices
uint256 priceCostMost; // Maximum ETH cost for prices
uint256 priceCostSingle; // ETH cost for single data
uint256 priceCostUser; // User ratio of cost
}
uint256 destructionAmount = 10000 ether; // Amount of NEST to destroy to call prices
uint256 effectTime = 1 days; // Waiting time to start calling prices
mapping(address => TokenInfo) _tokenInfo; // Token offer information
mapping(address => bool) _blocklist; // Block list
mapping(address => uint256) _addressEffect; // Effective time of address to call prices
mapping(address => bool) _offerMainMapping; // Offering contract mapping
// Real-time price token, ETH amount, erc20 amount
event NowTokenPrice(address a, uint256 b, uint256 c);
/**
* @dev Initialization method
* @param voteFactory Voting contract address
*/
constructor (address voteFactory) public {
Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory));
_voteFactory = voteFactoryMap;
_offerMain = Nest_3_OfferMain(address(voteFactoryMap.checkAddress("nest.v3.offerMain")));
_nTokeOfferMain = address(voteFactoryMap.checkAddress("nest.nToken.offerMain"));
_abonus = Nest_3_Abonus(address(voteFactoryMap.checkAddress("nest.v3.abonus")));
_destructionAddress = address(voteFactoryMap.checkAddress("nest.v3.destruction"));
_nestToken = ERC20(address(voteFactoryMap.checkAddress("nest")));
_tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.checkAddress("nest.nToken.tokenMapping")));
_nTokenAuction = address(voteFactoryMap.checkAddress("nest.nToken.tokenAuction"));
_offerMainMapping[address(_offerMain)] = true;
_offerMainMapping[address(_nTokeOfferMain)] = true;
}
/**
* @dev Modify voting contract
* @param voteFactory Voting contract address
*/
function changeMapping(address voteFactory) public onlyOwner {
Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory));
_voteFactory = voteFactoryMap;
_offerMain = Nest_3_OfferMain(address(voteFactoryMap.checkAddress("nest.v3.offerMain")));
_nTokeOfferMain = address(voteFactoryMap.checkAddress("nest.nToken.offerMain"));
_abonus = Nest_3_Abonus(address(voteFactoryMap.checkAddress("nest.v3.abonus")));
_destructionAddress = address(voteFactoryMap.checkAddress("nest.v3.destruction"));
_nestToken = ERC20(address(voteFactoryMap.checkAddress("nest")));
_tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.checkAddress("nest.nToken.tokenMapping")));
_nTokenAuction = address(voteFactoryMap.checkAddress("nest.nToken.tokenAuction"));
_offerMainMapping[address(_offerMain)] = true;
_offerMainMapping[address(_nTokeOfferMain)] = true;
}
/**
* @dev Initialize token price charge parameters
* @param tokenAddress Token address
*/
function addPriceCost(address tokenAddress) public {
require(msg.sender == _nTokenAuction);
TokenInfo storage tokenInfo = _tokenInfo[tokenAddress];
tokenInfo.priceCostLeast = 0.001 ether;
tokenInfo.priceCostMost = 0.01 ether;
tokenInfo.priceCostSingle = 0.0001 ether;
tokenInfo.priceCostUser = 2;
}
/**
* @dev Add price
* @param ethAmount ETH amount
* @param tokenAmount Erc20 amount
* @param endBlock Effective price block
* @param tokenAddress Erc20 address
* @param offerOwner Offering address
*/
function addPrice(uint256 ethAmount, uint256 tokenAmount, uint256 endBlock, address tokenAddress, address offerOwner) public onlyOfferMain{
// Add effective block price information
TokenInfo storage tokenInfo = _tokenInfo[tokenAddress];
PriceInfo storage priceInfo = tokenInfo.priceInfoList[endBlock];
priceInfo.ethAmount = priceInfo.ethAmount.add(ethAmount); //injected INTEGER OVERFLOW OR UNDERFLOW
priceInfo.erc20Amount = priceInfo.erc20Amount.add(tokenAmount); //injected INTEGER OVERFLOW OR UNDERFLOW
priceInfo.offerOwner = offerOwner;
if (endBlock != tokenInfo.latestOffer) {
// If different block offer
priceInfo.frontBlock = tokenInfo.latestOffer;
tokenInfo.latestOffer = endBlock;
}
}
/**
* @dev Price modification in taker orders
* @param ethAmount ETH amount
* @param tokenAmount Erc20 amount
* @param tokenAddress Token address
* @param endBlock Block of effective price
*/
function changePrice(uint256 ethAmount, uint256 tokenAmount, address tokenAddress, uint256 endBlock) public onlyOfferMain {
TokenInfo storage tokenInfo = _tokenInfo[tokenAddress];
PriceInfo storage priceInfo = tokenInfo.priceInfoList[endBlock];
priceInfo.ethAmount = priceInfo.ethAmount.sub(ethAmount); //injected INTEGER OVERFLOW OR UNDERFLOW
priceInfo.erc20Amount = priceInfo.erc20Amount.sub(tokenAmount); //injected INTEGER OVERFLOW OR UNDERFLOW
}
/**
* @dev Update and check the latest price
* @param tokenAddress Token address
* @return ethAmount ETH amount
* @return erc20Amount Erc20 amount
* @return blockNum Price block
*/
function updateAndCheckPriceNow(address tokenAddress) public payable returns(uint256 ethAmount, uint256 erc20Amount, uint256 blockNum) {
require(checkUseNestPrice(address(msg.sender)));
TokenInfo storage tokenInfo = _tokenInfo[tokenAddress];
uint256 checkBlock = tokenInfo.latestOffer;
while(checkBlock > 0 && (checkBlock >= block.number || tokenInfo.priceInfoList[checkBlock].ethAmount == 0)) {
checkBlock = tokenInfo.priceInfoList[checkBlock].frontBlock;
}
require(checkBlock != 0);
PriceInfo memory priceInfo = tokenInfo.priceInfoList[checkBlock];
address nToken = _tokenMapping.checkTokenMapping(tokenAddress);
if (nToken == address(0x0)) {
_abonus.switchToEth.value(tokenInfo.priceCostLeast.sub(tokenInfo.priceCostLeast.mul(tokenInfo.priceCostUser).div(10)))(address(_nestToken));
} else {
_abonus.switchToEth.value(tokenInfo.priceCostLeast.sub(tokenInfo.priceCostLeast.mul(tokenInfo.priceCostUser).div(10)))(address(nToken));
}
repayEth(priceInfo.offerOwner, tokenInfo.priceCostLeast.mul(tokenInfo.priceCostUser).div(10));
repayEth(address(msg.sender), msg.value.sub(tokenInfo.priceCostLeast));
emit NowTokenPrice(tokenAddress,priceInfo.ethAmount, priceInfo.erc20Amount);
return (priceInfo.ethAmount,priceInfo.erc20Amount, checkBlock);
}
/**
* @dev Update and check the latest price-internal use
* @param tokenAddress Token address
* @return ethAmount ETH amount
* @return erc20Amount Erc20 amount
*/
function updateAndCheckPricePrivate(address tokenAddress) public view onlyOfferMain returns(uint256 ethAmount, uint256 erc20Amount) {
TokenInfo storage tokenInfo = _tokenInfo[tokenAddress];
uint256 checkBlock = tokenInfo.latestOffer;
while(checkBlock > 0 && (checkBlock >= block.number || tokenInfo.priceInfoList[checkBlock].ethAmount == 0)) {
checkBlock = tokenInfo.priceInfoList[checkBlock].frontBlock;
}
if (checkBlock == 0) {
return (0,0);
}
PriceInfo memory priceInfo = tokenInfo.priceInfoList[checkBlock];
return (priceInfo.ethAmount,priceInfo.erc20Amount);
}
/**
* @dev Update and check the effective price list
* @param tokenAddress Token address
* @param num Number of prices to check
* @return uint256[] price list
*/
function updateAndCheckPriceList(address tokenAddress, uint256 num) public payable returns (uint256[] memory) {
require(checkUseNestPrice(address(msg.sender)));
TokenInfo storage tokenInfo = _tokenInfo[tokenAddress];
// Charge
uint256 thisPay = tokenInfo.priceCostSingle.mul(num);
if (thisPay < tokenInfo.priceCostLeast) {
thisPay=tokenInfo.priceCostLeast;
} else if (thisPay > tokenInfo.priceCostMost) {
thisPay = tokenInfo.priceCostMost;
}
// Extract data
uint256 length = num.mul(3);
uint256 index = 0;
uint256[] memory data = new uint256[](length);
address latestOfferOwner = address(0x0);
uint256 checkBlock = tokenInfo.latestOffer;
while(index < length && checkBlock > 0){
if (checkBlock < block.number && tokenInfo.priceInfoList[checkBlock].ethAmount != 0) {
// Add return data
data[index++] = tokenInfo.priceInfoList[checkBlock].ethAmount;
data[index++] = tokenInfo.priceInfoList[checkBlock].erc20Amount;
data[index++] = checkBlock;
if (latestOfferOwner == address(0x0)) {
latestOfferOwner = tokenInfo.priceInfoList[checkBlock].offerOwner;
}
}
checkBlock = tokenInfo.priceInfoList[checkBlock].frontBlock;
}
require(latestOfferOwner != address(0x0));
require(length == data.length);
// Allocation
address nToken = _tokenMapping.checkTokenMapping(tokenAddress);
if (nToken == address(0x0)) {
_abonus.switchToEth.value(thisPay.sub(thisPay.mul(tokenInfo.priceCostUser).div(10)))(address(_nestToken));
} else {
_abonus.switchToEth.value(thisPay.sub(thisPay.mul(tokenInfo.priceCostUser).div(10)))(address(nToken));
}
repayEth(latestOfferOwner, thisPay.mul(tokenInfo.priceCostUser).div(10));
repayEth(address(msg.sender), msg.value.sub(thisPay));
return data;
}
// Activate the price checking function
function activation() public {
_nestToken.safeTransferFrom(address(msg.sender), _destructionAddress, destructionAmount);
_addressEffect[address(msg.sender)] = now.add(effectTime);
}
// Transfer ETH
function repayEth(address accountAddress, uint256 asset) private {
address payable addr = accountAddress.make_payable();
addr.transfer(asset);
}
// Check block price - user account only
function checkPriceForBlock(address tokenAddress, uint256 blockNum) public view returns (uint256 ethAmount, uint256 erc20Amount) {
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
TokenInfo storage tokenInfo = _tokenInfo[tokenAddress];
return (tokenInfo.priceInfoList[blockNum].ethAmount, tokenInfo.priceInfoList[blockNum].erc20Amount);
}
// Check real-time price - user account only
function checkPriceNow(address tokenAddress) public view returns (uint256 ethAmount, uint256 erc20Amount, uint256 blockNum) {
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
TokenInfo storage tokenInfo = _tokenInfo[tokenAddress];
uint256 checkBlock = tokenInfo.latestOffer;
while(checkBlock > 0 && (checkBlock >= block.number || tokenInfo.priceInfoList[checkBlock].ethAmount == 0)) {
checkBlock = tokenInfo.priceInfoList[checkBlock].frontBlock;
}
if (checkBlock == 0) {
return (0,0,0);
}
PriceInfo storage priceInfo = tokenInfo.priceInfoList[checkBlock];
return (priceInfo.ethAmount,priceInfo.erc20Amount, checkBlock);
}
// Check the cost allocation ratio
function checkPriceCostProportion(address tokenAddress) public view returns(uint256 user, uint256 abonus) {
return (_tokenInfo[tokenAddress].priceCostUser, uint256(10).sub(_tokenInfo[tokenAddress].priceCostUser));
}
// Check the minimum ETH cost of obtaining the price
function checkPriceCostLeast(address tokenAddress) public view returns(uint256) {
return _tokenInfo[tokenAddress].priceCostLeast;
}
// Check the maximum ETH cost of obtaining the price
function checkPriceCostMost(address tokenAddress) public view returns(uint256) {
return _tokenInfo[tokenAddress].priceCostMost;
}
// Check the cost of a single price data
function checkPriceCostSingle(address tokenAddress) public view returns(uint256) {
return _tokenInfo[tokenAddress].priceCostSingle;
}
// Check whether the price-checking functions can be called
function checkUseNestPrice(address target) public view returns (bool) {
if (!_blocklist[target] && _addressEffect[target] < now && _addressEffect[target] != 0) {
return true;
} else {
return false;
}
}
// Check whether the address is in the blocklist
function checkBlocklist(address add) public view returns(bool) {
return _blocklist[add];
}
// Check the amount of NEST to destroy to call prices
function checkDestructionAmount() public view returns(uint256) {
return destructionAmount;
}
// Check the waiting time to start calling prices
function checkEffectTime() public view returns (uint256) {
return effectTime;
}
// Modify user ratio of cost
function changePriceCostProportion(uint256 user, address tokenAddress) public onlyOwner {
_tokenInfo[tokenAddress].priceCostUser = user;
}
// Modify minimum ETH cost for prices
function changePriceCostLeast(uint256 amount, address tokenAddress) public onlyOwner {
_tokenInfo[tokenAddress].priceCostLeast = amount;
}
// Modify maximum ETH cost for prices
function changePriceCostMost(uint256 amount, address tokenAddress) public onlyOwner {
_tokenInfo[tokenAddress].priceCostMost = amount;
}
// Modify ETH cost for single data
function checkPriceCostSingle(uint256 amount, address tokenAddress) public onlyOwner {
_tokenInfo[tokenAddress].priceCostSingle = amount;
}
// Modify the blocklist
function changeBlocklist(address add, bool isBlock) public onlyOwner {
_blocklist[add] = isBlock;
}
// Amount of NEST to destroy to call price-checking functions
function changeDestructionAmount(uint256 amount) public onlyOwner {
destructionAmount = amount;
}
// Modify the waiting time to start calling prices
function changeEffectTime(uint256 num) public onlyOwner {
effectTime = num;
}
// Offering contract only
modifier onlyOfferMain(){
require(_offerMainMapping[address(msg.sender)], "No authority");
_;
}
// Vote administrators only
modifier onlyOwner(){
require(_voteFactory.checkOwners(msg.sender), "No authority");
_;
}
}
// Voting contract
interface Nest_3_VoteFactory {
// Check address
function checkAddress(string calldata name) external view returns (address contractAddress);
// Check whether administrator
function checkOwners(address man) external view returns (bool);
}
// NToken mapping contract
interface Nest_NToken_TokenMapping {
function checkTokenMapping(address token) external view returns (address);
}
// NEST offer main contract
interface Nest_3_OfferMain {
function checkTokenAllow(address token) external view returns(bool);
}
// Bonus pool contract
interface Nest_3_Abonus {
function switchToEth(address token) external payable;
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
//require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
//require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
library address_make_payable {
function make_payable(address x) internal pure returns (address payable) {
return address(uint160(x));
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(ERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(ERC20 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 safeIncreaseAllowance(ERC20 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(ERC20 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));
}
function callOptionalReturn(ERC20 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");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface ERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
} | Maximum ETH cost for prices
| uint256 priceCostMost; | 12,913,694 | [
1,
13528,
512,
2455,
6991,
364,
19827,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2254,
5034,
6205,
8018,
18714,
31,
4766,
4202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/97/0x155BfdE44afc5ec4D17b21F7F5CC48807DFf0F0b/sources/Vault.sol | Redeem collateral. 100% collateral-backed | function redeem(uint256 stableAmount, address receivedCollateralToken, uint256 minimumReceivedCollateralAmount) external notLocked nonReentrant {
require(globalCollateralRatio == 1e18, "redeem-not-allowed");
(uint256 redeemAmount, uint256 redeemFeeAmount) = calculateCollateralRedeemAmount(stableAmount, receivedCollateralToken);
require(redeemAmount <= getCollateralizedBalance(receivedCollateralToken), "not-enough-collateral");
require(redeemAmount <= minimumReceivedCollateralAmount, "slippage-limit-reached");
redeemedCollaterals[msg.sender][receivedCollateralToken] = redeemedCollaterals[msg.sender][receivedCollateralToken].add(redeemAmount);
unclaimedCollaterals[receivedCollateralToken] = unclaimedCollaterals[receivedCollateralToken].add(redeemAmount);
redeemedBlock[msg.sender] = block.number;
IBurnable(stableToken).burnFrom(msg.sender, stableAmount);
IMintable(stableToken).mint(protocolFund, redeemFeeAmount);
}
| 11,410,572 | [
1,
426,
24903,
4508,
2045,
287,
18,
2130,
9,
4508,
2045,
287,
17,
823,
329,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
283,
24903,
12,
11890,
5034,
14114,
6275,
16,
1758,
5079,
13535,
2045,
287,
1345,
16,
2254,
5034,
5224,
8872,
13535,
2045,
287,
6275,
13,
3903,
486,
8966,
1661,
426,
8230,
970,
288,
203,
3639,
2583,
12,
6347,
13535,
2045,
287,
8541,
422,
404,
73,
2643,
16,
315,
266,
24903,
17,
902,
17,
8151,
8863,
203,
3639,
261,
11890,
5034,
283,
24903,
6275,
16,
2254,
5034,
283,
24903,
14667,
6275,
13,
273,
4604,
13535,
2045,
287,
426,
24903,
6275,
12,
15021,
6275,
16,
5079,
13535,
2045,
287,
1345,
1769,
203,
3639,
2583,
12,
266,
24903,
6275,
1648,
336,
13535,
2045,
287,
1235,
13937,
12,
15213,
13535,
2045,
287,
1345,
3631,
315,
902,
17,
275,
4966,
17,
12910,
2045,
287,
8863,
203,
3639,
2583,
12,
266,
24903,
6275,
1648,
5224,
8872,
13535,
2045,
287,
6275,
16,
315,
87,
3169,
2433,
17,
3595,
17,
266,
2004,
8863,
203,
3639,
283,
24903,
329,
13535,
2045,
1031,
63,
3576,
18,
15330,
6362,
15213,
13535,
2045,
287,
1345,
65,
273,
283,
24903,
329,
13535,
2045,
1031,
63,
3576,
18,
15330,
6362,
15213,
13535,
2045,
287,
1345,
8009,
1289,
12,
266,
24903,
6275,
1769,
203,
3639,
6301,
80,
4581,
329,
13535,
2045,
1031,
63,
15213,
13535,
2045,
287,
1345,
65,
273,
6301,
80,
4581,
329,
13535,
2045,
1031,
63,
15213,
13535,
2045,
287,
1345,
8009,
1289,
12,
266,
24903,
6275,
1769,
203,
3639,
283,
24903,
329,
1768,
63,
3576,
18,
15330,
65,
273,
1203,
18,
2696,
31,
203,
3639,
23450,
321,
429,
12,
15021,
1345,
2934,
70,
321,
1265,
2
] |
pragma solidity ^0.4.23;
contract ArtStamp {
/************************** */
/* STORAGE */
/************************** */
struct Piece {
string metadata;
string title;
bytes32 proof;
address owner;
//this currently does nothing, but i believe it will make it much easier if/when we make a future
//version of this app in which buying and selling pieces with ethereum is allowed
bool forSale;
//witnesses have to sign off on any transfer or sale, but have no rights to initiate them
//typically the witness will be the artist or anyone with rights to the pieces
//as of right now witnesses can only be added when a piece is created and cannot be altered
address witness;
}
//structure to keep track of a party to a contract and whether they have signed or not,
// and how much ether they have contributed
struct Signature {
address signee;
bool hasSigned;
}
//structure to represent escrow situation and keep track of all parties to contract
struct Escrow {
Signature sender;
Signature recipient;
Signature witness;
//block number when escrow is initiated, recorded so that escrow can timeout
uint blockNum;
}
//contains all pieces on the market
mapping (uint => Piece) pieces;
//number of pieces
uint piecesLength;
//list of all escrow situations currently in progress
mapping (uint => Escrow) escrowLedger;
//this is used to ensure that no piece can be uploaded twice.
//dataRecord[(hash of a piece goes here)] will be true if that piece has already been uploaded
mapping (bytes32 => bool) dataRecord;
/************************** */
/* LOGIC */
/************************** */
//
/****** PUBLIC READ */
//get data relating to escrow
function getEscrowData(uint i) view public returns (address, bool, address, bool, address, bool, uint){
return (escrowLedger[i].sender.signee, escrowLedger[i].sender.hasSigned,
escrowLedger[i].recipient.signee, escrowLedger[i].recipient.hasSigned,
escrowLedger[i].witness.signee, escrowLedger[i].witness.hasSigned,
escrowLedger[i].blockNum);
}
//returns total number of pieces
function getNumPieces() view public returns (uint) {
return piecesLength;
}
function getOwner(uint id) view public returns (address) {
return pieces[id].owner;
}
function getPiece(uint id) view public returns (string, string, bytes32, bool, address, address) {
Piece memory piece = pieces[id];
return (piece.metadata, piece.title, piece.proof, piece.forSale, piece.owner, piece.witness);
}
function hashExists(bytes32 proof) view public returns (bool) {
return dataRecord[proof];
}
function hasOwnership(uint id) view public returns (bool)
{
return pieces[id].owner == msg.sender;
}
//
/****** PUBLIC WRITE */
function addPieceAndHash(string _metadata, string _title, string data, address witness) public {
bytes32 _proof = keccak256(abi.encodePacked(data));
//check for hash collisions to see if the piece has already been uploaded
addPiece(_metadata,_title,_proof,witness);
}
function addPiece(string _metadata, string _title, bytes32 _proof, address witness) public {
bool exists = hashExists(_proof);
require(!exists, "This piece has already been uploaded");
dataRecord[_proof] = true;
pieces[piecesLength] = Piece(_metadata, _title, _proof, msg.sender, false, witness);
piecesLength++;
}
//edit both title and metadata with one transaction, will make things easier on the front end
function editPieceData(uint id, string newTitle, string newMetadata) public {
bool ownership = hasOwnership(id);
require(ownership, "You don't own this piece");
pieces[id].metadata = newMetadata;
pieces[id].title = newTitle;
}
function editMetadata(uint id, string newMetadata) public {
bool ownership = hasOwnership(id);
require(ownership, "You don't own this piece");
pieces[id].metadata = newMetadata;
}
function editTitle(uint id, string newTitle) public {
bool ownership = hasOwnership(id);
require(ownership, "You don't own this piece");
pieces[id].title = newTitle;
}
function escrowTransfer(uint id, address recipient) public {
bool ownership = hasOwnership(id);
require(ownership, "You don't own this piece");
//set owner of piece to artstamp smart contract
pieces[id].owner = address(this);
//upadte escrow ledger
escrowLedger[id] = Escrow({
sender: Signature(msg.sender,false),
recipient: Signature(recipient,false),
witness: Signature(pieces[id].witness,false),
blockNum: block.number});
}
//100000 blocks should be about 20 days which seems reasonable
//TODO: should make it so contracts owner can change this
uint timeout = 100000;
//timeout where piece will be returned to original owner if people dont sign
function retrievePieceFromEscrow(uint id) public {
//reject transaction if piece is not in escrow
require(pieces[id].owner == address(this));
require(block.number > escrowLedger[id].blockNum + timeout);
address sender = escrowLedger[id].sender.signee;
delete escrowLedger[id];
pieces[id].owner = sender;
}
function signEscrow(uint id) public {
//reject transaction if piece is not in escrow
require(pieces[id].owner == address(this));
//reject transaction if signee isnt any of the parties involved
require(msg.sender == escrowLedger[id].sender.signee ||
msg.sender == escrowLedger[id].recipient.signee ||
msg.sender == escrowLedger[id].witness.signee,
"You don't own this piece");
bool allHaveSigned = true;
if(msg.sender == escrowLedger[id].sender.signee){
escrowLedger[id].sender.hasSigned = true;
}
allHaveSigned = allHaveSigned && escrowLedger[id].sender.hasSigned;
if(msg.sender == escrowLedger[id].recipient.signee){
escrowLedger[id].recipient.hasSigned = true;
}
allHaveSigned = allHaveSigned && escrowLedger[id].recipient.hasSigned;
if(msg.sender == escrowLedger[id].witness.signee){
escrowLedger[id].witness.hasSigned = true;
}
allHaveSigned = allHaveSigned &&
(escrowLedger[id].witness.hasSigned ||
escrowLedger[id].witness.signee == 0x0000000000000000000000000000000000000000);
//transfer the pieces
if(allHaveSigned)
{
address recipient = escrowLedger[id].recipient.signee;
delete escrowLedger[id];
pieces[id].owner = recipient;
}
}
function transferPiece(uint id, address _to) public
{
bool ownership = hasOwnership(id);
require(ownership, "You don't own this piece");
//check if there is a witness, if so initiate escrow
if(pieces[id].witness != 0x0000000000000000000000000000000000000000){
escrowTransfer(id, _to);
return;
}
pieces[id].owner = _to;
}
} | list of all escrow situations currently in progress | mapping (uint => Escrow) escrowLedger;
| 891,837 | [
1,
1098,
434,
777,
2904,
492,
28474,
4551,
316,
4007,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
261,
11890,
516,
512,
1017,
492,
13,
2904,
492,
28731,
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
] |
./full_match/3/0x34Dc408f1173D3EB978693f8A630d35615d15217/sources/galak2.sol | When minting tokens | function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal override {
super._beforeTokenTransfer(from, to, amount);
if (from == address(0)) {
require(totalMinted().add(amount) <= cap(), "ERC20Capped: cap exceeded");
}
}
| 8,185,294 | [
1,
9434,
312,
474,
310,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
5771,
1345,
5912,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
2713,
3849,
288,
203,
3639,
2240,
6315,
5771,
1345,
5912,
12,
2080,
16,
358,
16,
3844,
1769,
203,
203,
3639,
309,
261,
2080,
422,
1758,
12,
20,
3719,
288,
203,
5411,
2583,
12,
4963,
49,
474,
329,
7675,
1289,
12,
8949,
13,
1648,
3523,
9334,
315,
654,
39,
3462,
4664,
1845,
30,
3523,
12428,
8863,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.8.10;
// Copyright BigchainDB GmbH and Ocean Protocol contributors
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
import "./balancer/BFactory.sol";
import "../interfaces/IFactory.sol";
import "../interfaces/IERC20.sol";
import "../interfaces/IFixedRateExchange.sol";
import "../interfaces/IPool.sol";
import "../interfaces/IDispenser.sol";
import "../utils/SafeERC20.sol";
import "OpenZeppelin/[email protected]/contracts/utils/math/SafeMath.sol";
contract FactoryRouter is BFactory {
using SafeERC20 for IERC20;
using SafeMath for uint256;
address public routerOwner;
address public factory;
address public fixedRate;
uint256 public minVestingPeriodInBlocks = 2426000;
uint256 public swapOceanFee = 0;
uint256 public swapNonOceanFee = 1e15; // 0.1%
uint256 public consumeFee = 1e16; // 1%
uint256 public providerFee = 0; // 0%
address[] public oceanTokens;
address[] public ssContracts;
address[] public fixedrates;
address[] public dispensers;
// mapping(address => bool) public oceanTokens;
// mapping(address => bool) public ssContracts;
// mapping(address => bool) public fixedPrice;
// mapping(address => bool) public dispenser;
event NewPool(address indexed poolAddress, bool isOcean);
event VestingPeriodChanges(address indexed caller, uint256 minVestingPeriodInBlocks);
event RouterChanged(address indexed caller, address indexed newRouter);
event FactoryContractChanged(
address indexed caller,
address indexed contractAddress
);
event TokenAdded(address indexed caller, address indexed token);
event TokenRemoved(address indexed caller, address indexed token);
event SSContractAdded(
address indexed caller,
address indexed contractAddress
);
event SSContractRemoved(
address indexed caller,
address indexed contractAddress
);
event FixedRateContractAdded(
address indexed caller,
address indexed contractAddress
);
event FixedRateContractRemoved(
address indexed caller,
address indexed contractAddress
);
event DispenserContractAdded(
address indexed caller,
address indexed contractAddress
);
event DispenserContractRemoved(
address indexed caller,
address indexed contractAddress
);
event OPCFeeChanged(address indexed caller, uint256 newSwapOceanFee,
uint256 newSwapNonOceanFee, uint256 newConsumeFee, uint256 newProviderFee);
modifier onlyRouterOwner() {
require(routerOwner == msg.sender, "OceanRouter: NOT OWNER");
_;
}
constructor(
address _routerOwner,
address _oceanToken,
address _bpoolTemplate,
address _opcCollector,
address[] memory _preCreatedPools
) public BFactory(_bpoolTemplate, _opcCollector, _preCreatedPools) {
require(
_routerOwner != address(0),
"FactoryRouter: Invalid router owner"
);
require(
_opcCollector != address(0),
"FactoryRouter: Invalid opcCollector"
);
require(
_oceanToken != address(0),
"FactoryRouter: Invalid Ocean Token address"
);
routerOwner = _routerOwner;
opcCollector = _opcCollector;
_addOceanToken(_oceanToken);
}
function changeRouterOwner(address _routerOwner) external onlyRouterOwner {
require(_routerOwner != address(0), "Invalid new router owner");
routerOwner = _routerOwner;
emit RouterChanged(msg.sender, _routerOwner);
}
/**
* @dev addOceanToken
* Adds a token to the list of tokens with reduced fees
* @param oceanTokenAddress address Token to be added
*/
function addOceanToken(address oceanTokenAddress) external onlyRouterOwner {
_addOceanToken(oceanTokenAddress);
}
function _addOceanToken(address oceanTokenAddress) internal {
if(!isOceanToken(oceanTokenAddress)){
oceanTokens.push(oceanTokenAddress);
emit TokenAdded(msg.sender, oceanTokenAddress);
}
}
/**
* @dev removeOceanToken
* Removes a token if exists from the list of tokens with reduced fees
* @param oceanTokenAddress address Token to be removed
*/
function removeOceanToken(address oceanTokenAddress)
external
onlyRouterOwner
{
require(
oceanTokenAddress != address(0),
"FactoryRouter: Invalid Ocean Token address"
);
uint256 i;
for (i = 0; i < oceanTokens.length; i++) {
if(oceanTokens[i] == oceanTokenAddress) break;
}
if(i < oceanTokens.length){
// it's in the array
for (uint c = i; c < oceanTokens.length - 1; c++) {
oceanTokens[c] = oceanTokens[c + 1];
}
oceanTokens.pop();
emit TokenRemoved(msg.sender, oceanTokenAddress);
}
}
/**
* @dev isOceanToken
* Returns true if token exists in the list of tokens with reduced fees
* @param oceanTokenAddress address Token to be checked
*/
function isOceanToken(address oceanTokenAddress) public view returns(bool) {
for (uint256 i = 0; i < oceanTokens.length; i++) {
if(oceanTokens[i] == oceanTokenAddress) return true;
}
return false;
}
/**
* @dev getOceanTokens
* Returns the list of tokens with reduced fees
*/
function getOceanTokens() public view returns(address[] memory) {
return(oceanTokens);
}
/**
* @dev addSSContract
* Adds a token to the list of ssContracts
* @param _ssContract address Contract to be added
*/
function addSSContract(address _ssContract) external onlyRouterOwner {
require(
_ssContract != address(0),
"FactoryRouter: Invalid _ssContract address"
);
if(!isSSContract(_ssContract)){
ssContracts.push(_ssContract);
emit SSContractAdded(msg.sender, _ssContract);
}
}
/**
* @dev removeSSContract
* Removes a token if exists from the list of ssContracts
* @param _ssContract address Contract to be removed
*/
function removeSSContract(address _ssContract) external onlyRouterOwner {
require(
_ssContract != address(0),
"FactoryRouter: Invalid _ssContract address"
);
uint256 i;
for (i = 0; i < ssContracts.length; i++) {
if(ssContracts[i] == _ssContract) break;
}
if(i < ssContracts.length){
// it's in the array
for (uint c = i; c < ssContracts.length - 1; c++) {
ssContracts[c] = ssContracts[c + 1];
}
ssContracts.pop();
emit SSContractRemoved(msg.sender, _ssContract);
}
}
/**
* @dev isSSContract
* Returns true if token exists in the list of ssContracts
* @param _ssContract address Contract to be checked
*/
function isSSContract(address _ssContract) public view returns(bool) {
for (uint256 i = 0; i < ssContracts.length; i++) {
if(ssContracts[i] == _ssContract) return true;
}
return false;
}
/**
* @dev getSSContracts
* Returns the list of ssContracts
*/
function getSSContracts() public view returns(address[] memory) {
return(ssContracts);
}
function addFactory(address _factory) external onlyRouterOwner {
require(
_factory != address(0),
"FactoryRouter: Invalid _factory address"
);
require(factory == address(0), "FACTORY ALREADY SET");
factory = _factory;
emit FactoryContractChanged(msg.sender, _factory);
}
/**
* @dev addFixedRateContract
* Adds an address to the list of fixed rate contracts
* @param _fixedRate address Contract to be added
*/
function addFixedRateContract(address _fixedRate) external onlyRouterOwner {
require(
_fixedRate != address(0),
"FactoryRouter: Invalid _fixedRate address"
);
if(!isFixedRateContract(_fixedRate)){
fixedrates.push(_fixedRate);
emit FixedRateContractAdded(msg.sender, _fixedRate);
}
}
/**
* @dev removeFixedRateContract
* Removes an address from the list of fixed rate contracts
* @param _fixedRate address Contract to be removed
*/
function removeFixedRateContract(address _fixedRate)
external
onlyRouterOwner
{
require(
_fixedRate != address(0),
"FactoryRouter: Invalid _fixedRate address"
);
uint256 i;
for (i = 0; i < fixedrates.length; i++) {
if(fixedrates[i] == _fixedRate) break;
}
if(i < fixedrates.length){
// it's in the array
for (uint c = i; c < fixedrates.length - 1; c++) {
fixedrates[c] = fixedrates[c + 1];
}
fixedrates.pop();
emit FixedRateContractRemoved(msg.sender, _fixedRate);
}
}
/**
* @dev isFixedRateContract
* Removes true if address exists in the list of fixed rate contracts
* @param _fixedRate address Contract to be checked
*/
function isFixedRateContract(address _fixedRate) public view returns(bool) {
for (uint256 i = 0; i < fixedrates.length; i++) {
if(fixedrates[i] == _fixedRate) return true;
}
return false;
}
/**
* @dev getFixedRatesContracts
* Returns the list of fixed rate contracts
*/
function getFixedRatesContracts() public view returns(address[] memory) {
return(fixedrates);
}
/**
* @dev addDispenserContract
* Adds an address to the list of dispensers
* @param _dispenser address Contract to be added
*/
function addDispenserContract(address _dispenser) external onlyRouterOwner {
require(
_dispenser != address(0),
"FactoryRouter: Invalid _dispenser address"
);
if(!isDispenserContract(_dispenser)){
dispensers.push(_dispenser);
emit DispenserContractAdded(msg.sender, _dispenser);
}
}
/**
* @dev removeDispenserContract
* Removes an address from the list of dispensers
* @param _dispenser address Contract to be removed
*/
function removeDispenserContract(address _dispenser)
external
onlyRouterOwner
{
require(
_dispenser != address(0),
"FactoryRouter: Invalid _dispenser address"
);
uint256 i;
for (i = 0; i < dispensers.length; i++) {
if(dispensers[i] == _dispenser) break;
}
if(i < dispensers.length){
// it's in the array
for (uint c = i; c < dispensers.length - 1; c++) {
dispensers[c] = dispensers[c + 1];
}
dispensers.pop();
emit DispenserContractRemoved(msg.sender, _dispenser);
}
}
/**
* @dev isDispenserContract
* Returns true if address exists in the list of dispensers
* @param _dispenser address Contract to be checked
*/
function isDispenserContract(address _dispenser) public view returns(bool) {
for (uint256 i = 0; i < dispensers.length; i++) {
if(dispensers[i] == _dispenser) return true;
}
return false;
}
/**
* @dev getDispensersContracts
* Returns the list of fixed rate contracts
*/
function getDispensersContracts() public view returns(address[] memory) {
return(dispensers);
}
/**
* @dev getOPCFee
* Gets OP Community Fees for a particular token
* @param baseToken address token to be checked
*/
function getOPCFee(address baseToken) public view returns (uint256) {
if (isOceanToken(baseToken)) {
return swapOceanFee;
} else return swapNonOceanFee;
}
/**
* @dev getOPCFees
* Gets OP Community Fees for approved tokens and non approved tokens
*/
function getOPCFees() public view returns (uint256,uint256) {
return (swapOceanFee, swapNonOceanFee);
}
/**
* @dev getConsumeFee
* Gets OP Community Fee cuts for consume fees
*/
function getOPCConsumeFee() public view returns (uint256) {
return consumeFee;
}
/**
* @dev getOPCProviderFee
* Gets OP Community Fee cuts for provider fees
*/
function getOPCProviderFee() public view returns (uint256) {
return providerFee;
}
/**
* @dev updateOPCFee
* Updates OP Community Fees
* @param _newSwapOceanFee Amount charged for swapping with ocean approved tokens
* @param _newSwapNonOceanFee Amount charged for swapping with non ocean approved tokens
* @param _newConsumeFee Amount charged from consumeFees
* @param _newProviderFee Amount charged for providerFees
*/
function updateOPCFee(uint256 _newSwapOceanFee, uint256 _newSwapNonOceanFee,
uint256 _newConsumeFee, uint256 _newProviderFee) external onlyRouterOwner {
swapOceanFee = _newSwapOceanFee;
swapNonOceanFee = _newSwapNonOceanFee;
consumeFee = _newConsumeFee;
providerFee = _newProviderFee;
emit OPCFeeChanged(msg.sender, _newSwapOceanFee, _newSwapNonOceanFee, _newConsumeFee, _newProviderFee);
}
/*
* @dev getMinVestingPeriod
* Returns current minVestingPeriodInBlocks
@return minVestingPeriodInBlocks
*/
function getMinVestingPeriod() public view returns (uint256) {
return minVestingPeriodInBlocks;
}
/*
* @dev updateMinVestingPeriod
* Set new minVestingPeriodInBlocks
* @param _newPeriod
*/
function updateMinVestingPeriod(uint256 _newPeriod) external onlyRouterOwner {
minVestingPeriodInBlocks = _newPeriod;
emit VestingPeriodChanges(msg.sender, _newPeriod);
}
/**
* @dev Deploys a new `OceanPool` on Ocean Friendly Fork modified for 1SS.
This function cannot be called directly, but ONLY through the ERC20DT contract from a ERC20DEployer role
ssContract address
tokens [datatokenAddress, baseTokenAddress]
publisherAddress user which will be assigned the vested amount.
* @param tokens precreated parameter
* @param ssParams params for the ssContract.
* [0] = rate (wei)
* [1] = baseToken decimals
* [2] = vesting amount (wei)
* [3] = vested blocks
* [4] = initial liquidity in baseToken for pool creation
* @param swapFees swapFees (swapFee, swapMarketFee), swapOceanFee will be set automatically later
* [0] = swapFee for LP Providers
* [1] = swapFee for marketplace runner
.
* @param addresses refers to an array of addresses passed by user
* [0] = side staking contract address
* [1] = baseToken address for pool creation(OCEAN or other)
* [2] = baseTokenSender user which will provide the baseToken amount for initial liquidity
* [3] = publisherAddress user which will be assigned the vested amount
* [4] = marketFeeCollector marketFeeCollector address
[5] = poolTemplateAddress
@return pool address
*/
function deployPool(
address[2] calldata tokens,
// [datatokenAddress, baseTokenAddress]
uint256[] calldata ssParams,
uint256[] calldata swapFees,
address[] calldata addresses
)
external
returns (
//[controller,baseTokenAddress,baseTokenSender,publisherAddress, marketFeeCollector,poolTemplateAddress]
address
)
{
require(
IFactory(factory).erc20List(msg.sender),
"FACTORY ROUTER: NOT ORIGINAL ERC20 TEMPLATE"
);
require(isSSContract(addresses[0]),
"FACTORY ROUTER: invalid ssContract"
);
require(ssParams[1] > 0, "Wrong decimals");
// we pull baseToken for creating initial pool and send it to the controller (ssContract)
_pullUnderlying(tokens[1],addresses[2], addresses[0], ssParams[4]);
address pool = newBPool(tokens, ssParams, swapFees, addresses);
require(pool != address(0), "FAILED TO DEPLOY POOL");
if (isOceanToken(tokens[1])) emit NewPool(pool, true);
else emit NewPool(pool, false);
return pool;
}
function getLength(IERC20[] memory array) internal pure returns (uint256) {
return array.length;
}
/**
* @dev deployFixedRate
* Creates a new FixedRateExchange setup.
* As for deployPool, this function cannot be called directly,
* but ONLY through the ERC20DT contract from a ERC20DEployer role
* @param fixedPriceAddress fixedPriceAddress
* @param addresses array of addresses [baseToken,owner,marketFeeCollector]
* @param uints array of uints [baseTokenDecimals,datatokenDecimals, fixedRate, marketFee, withMint]
@return exchangeId
*/
function deployFixedRate(
address fixedPriceAddress,
address[] calldata addresses,
uint256[] calldata uints
) external returns (bytes32 exchangeId) {
require(
IFactory(factory).erc20List(msg.sender),
"FACTORY ROUTER: NOT ORIGINAL ERC20 TEMPLATE"
);
require(isFixedRateContract(fixedPriceAddress),
"FACTORY ROUTER: Invalid FixedPriceContract"
);
exchangeId = IFixedRateExchange(fixedPriceAddress).createWithDecimals(
msg.sender,
addresses,
uints
);
}
/**
* @dev deployDispenser
* Activates a new Dispenser
* As for deployPool, this function cannot be called directly,
* but ONLY through the ERC20DT contract from a ERC20DEployer role
* @param _dispenser dispenser contract address
* @param datatoken refers to datatoken address.
* @param maxTokens - max tokens to dispense
* @param maxBalance - max balance of requester.
* @param owner - owner
* @param allowedSwapper - if !=0, only this address can request DTs
*/
function deployDispenser(
address _dispenser,
address datatoken,
uint256 maxTokens,
uint256 maxBalance,
address owner,
address allowedSwapper
) external {
require(
IFactory(factory).erc20List(msg.sender),
"FACTORY ROUTER: NOT ORIGINAL ERC20 TEMPLATE"
);
require(isDispenserContract(_dispenser),
"FACTORY ROUTER: Invalid DispenserContract"
);
IDispenser(_dispenser).create(
datatoken,
maxTokens,
maxBalance,
owner,
allowedSwapper
);
}
/**
* @dev addPoolTemplate
* Adds an address to the list of pools templates
* @param poolTemplate address Contract to be added
*/
function addPoolTemplate(address poolTemplate) external onlyRouterOwner {
_addPoolTemplate(poolTemplate);
}
/**
* @dev removePoolTemplate
* Removes an address from the list of pool templates
* @param poolTemplate address Contract to be removed
*/
function removePoolTemplate(address poolTemplate) external onlyRouterOwner {
_removePoolTemplate(poolTemplate);
}
// If you need to buy multiple DT (let's say for a compute job which has multiple datasets),
// you have to send one transaction for each DT that you want to buy.
// Perks:
// one single call to buy multiple DT for multiple assets (better UX, better gas optimization)
enum operationType {
SwapExactIn,
SwapExactOut,
FixedRate,
Dispenser
}
struct Operations {
bytes32 exchangeIds; // used for fixedRate or dispenser
address source; // pool, dispenser or fixed rate address
operationType operation; // type of operation: enum operationType
address tokenIn; // token in address, only for pools
uint256 amountsIn; // ExactAmount In for swapExactIn operation, maxAmount In for swapExactOut
address tokenOut; // token out address, only for pools
uint256 amountsOut; // minAmountOut for swapExactIn or exactAmountOut for swapExactOut
uint256 maxPrice; // maxPrice, only for pools
uint256 swapMarketFee;
address marketFeeAddress;
}
// require tokenIn approvals for router from user. (except for dispenser operations)
function buyDTBatch(Operations[] calldata _operations) external {
// TODO: to avoid DOS attack, we set a limit to maximum orders (50?)
require(_operations.length <= 50, "FactoryRouter: Too Many Operations");
for (uint256 i = 0; i < _operations.length; i++) {
// address[] memory tokenInOutMarket = new address[](3);
address[3] memory tokenInOutMarket = [
_operations[i].tokenIn,
_operations[i].tokenOut,
_operations[i].marketFeeAddress
];
uint256[4] memory amountsInOutMaxFee = [
_operations[i].amountsIn,
_operations[i].amountsOut,
_operations[i].maxPrice,
_operations[i].swapMarketFee
];
// tokenInOutMarket[0] =
if (_operations[i].operation == operationType.SwapExactIn) {
// Get amountIn from user to router
_pullUnderlying(_operations[i].tokenIn,msg.sender,
address(this),
_operations[i].amountsIn);
// we approve pool to pull token from router
IERC20(_operations[i].tokenIn).safeIncreaseAllowance(
_operations[i].source,
_operations[i].amountsIn
);
// Perform swap
(uint256 amountReceived, ) = IPool(_operations[i].source)
.swapExactAmountIn(tokenInOutMarket, amountsInOutMaxFee);
// transfer token swapped to user
IERC20(_operations[i].tokenOut).safeTransfer(
msg.sender,
amountReceived
);
} else if (_operations[i].operation == operationType.SwapExactOut) {
// calculate how much amount In we need for exact Out
uint256 amountIn;
(amountIn, , , , ) = IPool(_operations[i].source)
.getAmountInExactOut(
_operations[i].tokenIn,
_operations[i].tokenOut,
_operations[i].amountsOut,
_operations[i].swapMarketFee
);
// pull amount In from user
_pullUnderlying(_operations[i].tokenIn,msg.sender,
address(this),
amountIn);
// we approve pool to pull token from router
IERC20(_operations[i].tokenIn).safeIncreaseAllowance(
_operations[i].source,
amountIn
);
// perform swap
(uint tokenAmountIn,) = IPool(_operations[i].source).swapExactAmountOut(
tokenInOutMarket,
amountsInOutMaxFee
);
require(tokenAmountIn <= amountsInOutMaxFee[0], 'TOO MANY TOKENS IN');
// send amount out back to user
IERC20(_operations[i].tokenOut).safeTransfer(
msg.sender,
_operations[i].amountsOut
);
} else if (_operations[i].operation == operationType.FixedRate) {
// get datatoken address
(, address datatoken, , , , , , , , , , ) = IFixedRateExchange(
_operations[i].source
).getExchange(_operations[i].exchangeIds);
// get tokenIn amount required for dt out
(uint256 baseTokenAmount, , , ) = IFixedRateExchange(
_operations[i].source
).calcBaseInGivenOutDT(
_operations[i].exchangeIds,
_operations[i].amountsOut,
_operations[i].swapMarketFee
);
// pull tokenIn amount
_pullUnderlying(_operations[i].tokenIn,msg.sender,
address(this),
baseTokenAmount);
// we approve pool to pull token from router
IERC20(_operations[i].tokenIn).safeIncreaseAllowance(
_operations[i].source,
baseTokenAmount
);
// perform swap
IFixedRateExchange(_operations[i].source).buyDT(
_operations[i].exchangeIds,
_operations[i].amountsOut,
_operations[i].amountsIn,
_operations[i].marketFeeAddress,
_operations[i].swapMarketFee
);
// send dt out to user
IERC20(datatoken).safeTransfer(
msg.sender,
_operations[i].amountsOut
);
} else {
IDispenser(_operations[i].source).dispense(
_operations[i].tokenOut,
_operations[i].amountsOut,
msg.sender
);
}
}
}
struct Stakes {
address poolAddress;
uint256 tokenAmountIn;
uint256 minPoolAmountOut;
}
// require pool[].baseToken (for each pool) approvals for router from user.
function stakeBatch(Stakes[] calldata _stakes) external {
// TODO: to avoid DOS attack, we set a limit to maximum orders (50?)
require(_stakes.length <= 50, "FactoryRouter: Too Many Operations");
for (uint256 i = 0; i < _stakes.length; i++) {
address baseToken = IPool(_stakes[i].poolAddress).getBaseTokenAddress();
_pullUnderlying(baseToken,msg.sender,
address(this),
_stakes[i].tokenAmountIn);
uint256 balanceBefore = IERC20(_stakes[i].poolAddress).balanceOf(address(this));
// we approve pool to pull token from router
IERC20(baseToken).safeIncreaseAllowance(
_stakes[i].poolAddress,
_stakes[i].tokenAmountIn);
//now stake
uint poolAmountOut = IPool(_stakes[i].poolAddress).joinswapExternAmountIn(
_stakes[i].tokenAmountIn, _stakes[i].minPoolAmountOut
);
require(poolAmountOut >= _stakes[i].minPoolAmountOut,'NOT ENOUGH LP');
uint256 balanceAfter = IERC20(_stakes[i].poolAddress).balanceOf(address(this));
//send LP shares to user
IERC20(_stakes[i].poolAddress).safeTransfer(
msg.sender,
balanceAfter.sub(balanceBefore)
);
}
}
function _pullUnderlying(
address erc20,
address from,
address to,
uint256 amount
) internal {
uint256 balanceBefore = IERC20(erc20).balanceOf(to);
IERC20(erc20).safeTransferFrom(from, to, amount);
require(IERC20(erc20).balanceOf(to) >= balanceBefore.add(amount),
"Transfer amount is too low");
}
}
| * @dev getOPCFee Gets OP Community Fees for a particular token @param baseToken address token to be checked/ | function getOPCFee(address baseToken) public view returns (uint256) {
if (isOceanToken(baseToken)) {
return swapOceanFee;
} else return swapNonOceanFee;
}
| 7,270,563 | [
1,
588,
51,
3513,
14667,
1377,
11881,
7247,
16854,
13352,
5782,
281,
364,
279,
6826,
1147,
225,
1026,
1345,
225,
1758,
1147,
358,
506,
5950,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
17971,
3513,
14667,
12,
2867,
1026,
1345,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
309,
261,
291,
51,
31393,
1345,
12,
1969,
1345,
3719,
288,
203,
5411,
327,
7720,
51,
31393,
14667,
31,
203,
3639,
289,
469,
327,
7720,
3989,
51,
31393,
14667,
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
] |
pragma solidity ^0.4.18;
/*
Game: Dragon Ball Super ( Tournament of Power )
Domain: EtherDragonBall.com
*/
contract DragonBallZ {
//The contract creator and dev fee addresses are defined here
address contractCreator = 0x606A19ea257aF8ED76D160Ad080782C938660A33;
address devFeeAddress = 0xAe406d5900DCe1bB7cF3Bc5e92657b5ac9cBa34B;
struct Hero {
string heroName;
address ownerAddress;
address DBZHeroOwnerAddress;
uint256 currentPrice;
uint currentLevel;
}
Hero[] heroes;
//The number of heroes in Tournament of Power
uint256 heroMax = 55;
//The array defined for winner variable
uint256[] winners;
modifier onlyContractCreator() {
require (msg.sender == contractCreator);
_;
}
bool isPaused;
/*
We use the following functions to pause and unpause the game.
*/
function pauseGame() public onlyContractCreator {
isPaused = true;
}
function unPauseGame() public onlyContractCreator {
isPaused = false;
}
function GetGamestatus() public view returns(bool) {
return(isPaused);
}
/*
This function allows users to purchase Tournament of Power heroes
The price is automatically multiplied by 2 after each purchase.
Users can purchase multiple heroes.
*/
function purchaseHero(uint _heroId) public payable {
//Check if current price of hero is equal with the price entered to purchase the hero
require(msg.value == heroes[_heroId].currentPrice);
//Check if the game is not PAUSED
require(isPaused == false);
// Calculate the 10% of Tournament of Power prize fee
uint256 TournamentPrizeFee = (msg.value / 10); // => 10%
// Calculate the 5% - Dev fee
uint256 devFee = ((msg.value / 10)/2); // => 5%
// Calculate the 10% commission - Dragon Ball Z Hero Owner
uint256 DBZHeroOwnerCommission = (msg.value / 10); // => 10%
// Calculate the current hero owner commission on this sale & transfer the commission to the owner.
uint256 commissionOwner = (msg.value - (devFee + TournamentPrizeFee + DBZHeroOwnerCommission));
heroes[_heroId].ownerAddress.transfer(commissionOwner); // => 75%
// Transfer the 10% commission to the DBZ Hero Owner
heroes[_heroId].DBZHeroOwnerAddress.transfer(DBZHeroOwnerCommission); // => 10%
// Transfer the 5% commission to the Dev
devFeeAddress.transfer(devFee); // => 5%
//The hero will be leveled up after new purchase
heroes[_heroId].currentLevel +=1;
// Update the hero owner and set the new price (2X)
heroes[_heroId].ownerAddress = msg.sender;
heroes[_heroId].currentPrice = mul(heroes[_heroId].currentPrice, 2);
}
/*
This function will be used to update the details of DBZ hero details by the contract creator
*/
function updateDBZHeroDetails(uint _heroId, string _heroName,address _ownerAddress, address _newDBZHeroOwnerAddress, uint _currentLevel) public onlyContractCreator{
require(heroes[_heroId].ownerAddress != _newDBZHeroOwnerAddress);
heroes[_heroId].heroName = _heroName;
heroes[_heroId].ownerAddress = _ownerAddress;
heroes[_heroId].DBZHeroOwnerAddress = _newDBZHeroOwnerAddress;
heroes[_heroId].currentLevel = _currentLevel;
}
/*
This function can be used by the owner of a hero to modify the price of its hero.
The hero owner can make the price lesser than the current price only.
*/
function modifyCurrentHeroPrice(uint _heroId, uint256 _newPrice) public {
require(_newPrice > 0);
require(heroes[_heroId].ownerAddress == msg.sender);
require(_newPrice < heroes[_heroId].currentPrice);
heroes[_heroId].currentPrice = _newPrice;
}
// This function will return all of the details of the Tournament of Power heroes
function getHeroDetails(uint _heroId) public view returns (
string heroName,
address ownerAddress,
address DBZHeroOwnerAddress,
uint256 currentPrice,
uint currentLevel
) {
Hero storage _hero = heroes[_heroId];
heroName = _hero.heroName;
ownerAddress = _hero.ownerAddress;
DBZHeroOwnerAddress = _hero.DBZHeroOwnerAddress;
currentPrice = _hero.currentPrice;
currentLevel = _hero.currentLevel;
}
// This function will return only the price of a specific hero
function getHeroCurrentPrice(uint _heroId) public view returns(uint256) {
return(heroes[_heroId].currentPrice);
}
// This function will return only the price of a specific hero
function getHeroCurrentLevel(uint _heroId) public view returns(uint256) {
return(heroes[_heroId].currentLevel);
}
// This function will return only the owner address of a specific hero
function getHeroOwner(uint _heroId) public view returns(address) {
return(heroes[_heroId].ownerAddress);
}
// This function will return only the DBZ owner address of a specific hero
function getHeroDBZHeroAddress(uint _heroId) public view returns(address) {
return(heroes[_heroId].DBZHeroOwnerAddress);
}
// This function will return only Tournament of Power total prize
function getTotalPrize() public view returns(uint256) {
return this.balance;
}
/**
@dev Multiplies two numbers, throws on overflow. => From the SafeMath library
*/
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. => From the SafeMath library
*/
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;
}
// This function will be used to add a new hero by the contract creator
function addHero(string _heroName, address _ownerAddress, address _DBZHeroOwnerAddress, uint256 _currentPrice, uint _currentLevel) public onlyContractCreator {
heroes.push(Hero(_heroName,_ownerAddress,_DBZHeroOwnerAddress,_currentPrice,_currentLevel));
}
/*
This function will be used by the contract creator to generate 5 heroes ID randomly out of 55 heroes
and it can be generated only once and cannot be altered at all even by contractCreator
*/
function getWinner() public onlyContractCreator returns (uint256[]) {
uint i;
//Loop to generate 5 random hero IDs from 55 heroes
for(i=0;i<=4;i++){
//Block timestamp and number used to generate the random number
winners.push(uint256(sha256(block.timestamp, block.number-i-1)) % heroMax);
}
return winners;
}
// This function will return only the winner's hero id
function getWinnerDetails(uint _winnerId) public view returns(uint256) {
return(winners[_winnerId]);
}
/*
This function can be used by the contractCreator to start the payout to the lucky 5 winners
The payout will be initiated in a week time
*/
function payoutWinners() public onlyContractCreator {
//Assign 20% of total contract eth
uint256 TotalPrize20PercentShare = (this.balance/5);
uint i;
for(i=0;i<=4;i++){
// Get the hero ID from getWinnerDetails function - Randomly generated
uint _heroID = getWinnerDetails(i);
// Assign the owner address of hero ID - Randomly generated
address winner = heroes[_heroID].ownerAddress;
if(winner != address(0)){
// Transfer the 20% of total contract eth to each winner (5 winners in total)
winner.transfer(TotalPrize20PercentShare);
}
// Reset the winner's address after payout for next loop
winner = address(0);
}
}
} | This function will return only Tournament of Power total prize | function getTotalPrize() public view returns(uint256) {
return this.balance;
}
| 6,749,200 | [
1,
2503,
445,
903,
327,
1338,
2974,
30751,
434,
23783,
2078,
846,
554,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
12831,
2050,
554,
1435,
1071,
1476,
1135,
12,
11890,
5034,
13,
288,
203,
3639,
327,
333,
18,
12296,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x007FEA2a31644F20b0fE18f69643890b6F878AA6/sources/src/bases/BondBaseSDA.sol | @inheritdoc IBondAuctioneer Restricted to authorized addresses, initially restricted to guardian | function setCallbackAuthStatus(address creator_, bool status_) external override requiresAuth {
callbackAuthorized[creator_] = status_;
}
| 8,303,926 | [
1,
36,
10093,
16178,
37,
4062,
4943,
29814,
358,
10799,
6138,
16,
22458,
15693,
358,
11026,
2779,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
444,
2428,
1730,
1482,
12,
2867,
11784,
67,
16,
1426,
1267,
67,
13,
3903,
3849,
4991,
1730,
288,
203,
3639,
1348,
15341,
63,
20394,
67,
65,
273,
1267,
67,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xB23F0796e592A91467E5D42F3368Cd722E7f0251/sources/contracts/medrecords.sol | Retrieve a list of all doctors address | function getDoctors() public view returns(address[] memory) {
return doctorList;
}
| 11,630,154 | [
1,
5767,
279,
666,
434,
777,
31263,
1383,
1758,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
11165,
299,
1383,
1435,
1071,
1476,
1135,
12,
2867,
8526,
3778,
13,
288,
203,
3639,
327,
741,
30206,
682,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol";
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
/// Minimal contract to be inherited by contracts consumed by users that provide
/// data for fraud proofs
abstract contract Abs_FraudContributor is Lib_AddressResolver {
/// Decorate your functions with this modifier to store how much total gas was
/// consumed by the sender, to reward users fairly
modifier contributesToFraudProof(bytes32 preStateRoot, bytes32 txHash) {
uint256 startGas = gasleft();
_;
uint256 gasSpent = startGas - gasleft();
iOVM_BondManager(resolve('OVM_BondManager')).recordGasSpent(preStateRoot, txHash, msg.sender, gasSpent);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
/* Interface Imports */
import { iOVM_FraudVerifier } from "../../iOVM/verification/iOVM_FraudVerifier.sol";
import { iOVM_StateTransitioner } from "../../iOVM/verification/iOVM_StateTransitioner.sol";
import { iOVM_StateTransitionerFactory } from "../../iOVM/verification/iOVM_StateTransitionerFactory.sol";
import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol";
import { iOVM_StateCommitmentChain } from "../../iOVM/chain/iOVM_StateCommitmentChain.sol";
import { iOVM_CanonicalTransactionChain } from "../../iOVM/chain/iOVM_CanonicalTransactionChain.sol";
/* Contract Imports */
import { Abs_FraudContributor } from "./Abs_FraudContributor.sol";
/**
* @title OVM_FraudVerifier
* @dev The Fraud Verifier contract coordinates the entire fraud proof verification process.
* If the fraud proof was successful it prunes any state batches from State Commitment Chain
* which were published after the fraudulent state root.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_FraudVerifier is Lib_AddressResolver, Abs_FraudContributor, iOVM_FraudVerifier {
/*******************************************
* Contract Variables: Internal Accounting *
*******************************************/
mapping (bytes32 => iOVM_StateTransitioner) internal transitioners;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Address Manager.
*/
constructor(
address _libAddressManager
)
Lib_AddressResolver(_libAddressManager)
{}
/***************************************
* Public Functions: Transition Status *
***************************************/
/**
* Retrieves the state transitioner for a given root.
* @param _preStateRoot State root to query a transitioner for.
* @return _transitioner Corresponding state transitioner contract.
*/
function getStateTransitioner(
bytes32 _preStateRoot,
bytes32 _txHash
)
override
public
view
returns (
iOVM_StateTransitioner _transitioner
)
{
return transitioners[keccak256(abi.encodePacked(_preStateRoot, _txHash))];
}
/****************************************
* Public Functions: Fraud Verification *
****************************************/
/**
* Begins the fraud verification process.
* @param _preStateRoot State root before the fraudulent transaction.
* @param _preStateRootBatchHeader Batch header for the provided pre-state root.
* @param _preStateRootProof Inclusion proof for the provided pre-state root.
* @param _transaction OVM transaction claimed to be fraudulent.
* @param _txChainElement OVM transaction chain element.
* @param _transactionBatchHeader Batch header for the provided transaction.
* @param _transactionProof Inclusion proof for the provided transaction.
*/
function initializeFraudVerification(
bytes32 _preStateRoot,
Lib_OVMCodec.ChainBatchHeader memory _preStateRootBatchHeader,
Lib_OVMCodec.ChainInclusionProof memory _preStateRootProof,
Lib_OVMCodec.Transaction memory _transaction,
Lib_OVMCodec.TransactionChainElement memory _txChainElement,
Lib_OVMCodec.ChainBatchHeader memory _transactionBatchHeader,
Lib_OVMCodec.ChainInclusionProof memory _transactionProof
)
override
public
contributesToFraudProof(_preStateRoot, Lib_OVMCodec.hashTransaction(_transaction))
{
bytes32 _txHash = Lib_OVMCodec.hashTransaction(_transaction);
if (_hasStateTransitioner(_preStateRoot, _txHash)) {
return;
}
iOVM_StateCommitmentChain ovmStateCommitmentChain = iOVM_StateCommitmentChain(resolve("OVM_StateCommitmentChain"));
iOVM_CanonicalTransactionChain ovmCanonicalTransactionChain = iOVM_CanonicalTransactionChain(resolve("OVM_CanonicalTransactionChain"));
require(
ovmStateCommitmentChain.verifyStateCommitment(
_preStateRoot,
_preStateRootBatchHeader,
_preStateRootProof
),
"Invalid pre-state root inclusion proof."
);
require(
ovmCanonicalTransactionChain.verifyTransaction(
_transaction,
_txChainElement,
_transactionBatchHeader,
_transactionProof
),
"Invalid transaction inclusion proof."
);
require (
_preStateRootBatchHeader.prevTotalElements + _preStateRootProof.index + 1 == _transactionBatchHeader.prevTotalElements + _transactionProof.index,
"Pre-state root global index must equal to the transaction root global index."
);
_deployTransitioner(_preStateRoot, _txHash, _preStateRootProof.index);
emit FraudProofInitialized(
_preStateRoot,
_preStateRootProof.index,
_txHash,
msg.sender
);
}
/**
* Finalizes the fraud verification process.
* @param _preStateRoot State root before the fraudulent transaction.
* @param _preStateRootBatchHeader Batch header for the provided pre-state root.
* @param _preStateRootProof Inclusion proof for the provided pre-state root.
* @param _txHash The transaction for the state root
* @param _postStateRoot State root after the fraudulent transaction.
* @param _postStateRootBatchHeader Batch header for the provided post-state root.
* @param _postStateRootProof Inclusion proof for the provided post-state root.
*/
function finalizeFraudVerification(
bytes32 _preStateRoot,
Lib_OVMCodec.ChainBatchHeader memory _preStateRootBatchHeader,
Lib_OVMCodec.ChainInclusionProof memory _preStateRootProof,
bytes32 _txHash,
bytes32 _postStateRoot,
Lib_OVMCodec.ChainBatchHeader memory _postStateRootBatchHeader,
Lib_OVMCodec.ChainInclusionProof memory _postStateRootProof
)
override
public
contributesToFraudProof(_preStateRoot, _txHash)
{
iOVM_StateTransitioner transitioner = getStateTransitioner(_preStateRoot, _txHash);
iOVM_StateCommitmentChain ovmStateCommitmentChain = iOVM_StateCommitmentChain(resolve("OVM_StateCommitmentChain"));
require(
transitioner.isComplete() == true,
"State transition process must be completed prior to finalization."
);
require (
_postStateRootBatchHeader.prevTotalElements + _postStateRootProof.index == _preStateRootBatchHeader.prevTotalElements + _preStateRootProof.index + 1,
"Post-state root global index must equal to the pre state root global index plus one."
);
require(
ovmStateCommitmentChain.verifyStateCommitment(
_preStateRoot,
_preStateRootBatchHeader,
_preStateRootProof
),
"Invalid pre-state root inclusion proof."
);
require(
ovmStateCommitmentChain.verifyStateCommitment(
_postStateRoot,
_postStateRootBatchHeader,
_postStateRootProof
),
"Invalid post-state root inclusion proof."
);
// If the post state root did not match, then there was fraud and we should delete the batch
require(
_postStateRoot != transitioner.getPostStateRoot(),
"State transition has not been proven fraudulent."
);
_cancelStateTransition(_postStateRootBatchHeader, _preStateRoot);
// TEMPORARY: Remove the transitioner; for minnet.
transitioners[keccak256(abi.encodePacked(_preStateRoot, _txHash))] = iOVM_StateTransitioner(0x0000000000000000000000000000000000000000);
emit FraudProofFinalized(
_preStateRoot,
_preStateRootProof.index,
_txHash,
msg.sender
);
}
/************************************
* Internal Functions: Verification *
************************************/
/**
* Checks whether a transitioner already exists for a given pre-state root.
* @param _preStateRoot Pre-state root to check.
* @return _exists Whether or not we already have a transitioner for the root.
*/
function _hasStateTransitioner(
bytes32 _preStateRoot,
bytes32 _txHash
)
internal
view
returns (
bool _exists
)
{
return address(getStateTransitioner(_preStateRoot, _txHash)) != address(0);
}
/**
* Deploys a new state transitioner.
* @param _preStateRoot Pre-state root to initialize the transitioner with.
* @param _txHash Hash of the transaction this transitioner will execute.
* @param _stateTransitionIndex Index of the transaction in the chain.
*/
function _deployTransitioner(
bytes32 _preStateRoot,
bytes32 _txHash,
uint256 _stateTransitionIndex
)
internal
{
transitioners[keccak256(abi.encodePacked(_preStateRoot, _txHash))] = iOVM_StateTransitionerFactory(
resolve("OVM_StateTransitionerFactory")
).create(
address(libAddressManager),
_stateTransitionIndex,
_preStateRoot,
_txHash
);
}
/**
* Removes a state transition from the state commitment chain.
* @param _postStateRootBatchHeader Header for the post-state root.
* @param _preStateRoot Pre-state root hash.
*/
function _cancelStateTransition(
Lib_OVMCodec.ChainBatchHeader memory _postStateRootBatchHeader,
bytes32 _preStateRoot
)
internal
{
iOVM_StateCommitmentChain ovmStateCommitmentChain = iOVM_StateCommitmentChain(resolve("OVM_StateCommitmentChain"));
iOVM_BondManager ovmBondManager = iOVM_BondManager(resolve("OVM_BondManager"));
// Delete the state batch.
ovmStateCommitmentChain.deleteStateBatch(
_postStateRootBatchHeader
);
// Get the timestamp and publisher for that block.
(uint256 timestamp, address publisher) = abi.decode(_postStateRootBatchHeader.extraData, (uint256, address));
// Slash the bonds at the bond manager.
ovmBondManager.finalize(
_preStateRoot,
publisher,
timestamp
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
/* Interface Imports */
import { iOVM_ChainStorageContainer } from "./iOVM_ChainStorageContainer.sol";
/**
* @title iOVM_CanonicalTransactionChain
*/
interface iOVM_CanonicalTransactionChain {
/**********
* Events *
**********/
event TransactionEnqueued(
address _l1TxOrigin,
address _target,
uint256 _gasLimit,
bytes _data,
uint256 _queueIndex,
uint256 _timestamp
);
event QueueBatchAppended(
uint256 _startingQueueIndex,
uint256 _numQueueElements,
uint256 _totalElements
);
event SequencerBatchAppended(
uint256 _startingQueueIndex,
uint256 _numQueueElements,
uint256 _totalElements
);
event TransactionBatchAppended(
uint256 indexed _batchIndex,
bytes32 _batchRoot,
uint256 _batchSize,
uint256 _prevTotalElements,
bytes _extraData
);
/***********
* Structs *
***********/
struct BatchContext {
uint256 numSequencedTransactions;
uint256 numSubsequentQueueTransactions;
uint256 timestamp;
uint256 blockNumber;
}
/********************
* Public Functions *
********************/
/**
* Accesses the batch storage container.
* @return Reference to the batch storage container.
*/
function batches()
external
view
returns (
iOVM_ChainStorageContainer
);
/**
* Accesses the queue storage container.
* @return Reference to the queue storage container.
*/
function queue()
external
view
returns (
iOVM_ChainStorageContainer
);
/**
* Retrieves the total number of elements submitted.
* @return _totalElements Total submitted elements.
*/
function getTotalElements()
external
view
returns (
uint256 _totalElements
);
/**
* Retrieves the total number of batches submitted.
* @return _totalBatches Total submitted batches.
*/
function getTotalBatches()
external
view
returns (
uint256 _totalBatches
);
/**
* Returns the index of the next element to be enqueued.
* @return Index for the next queue element.
*/
function getNextQueueIndex()
external
view
returns (
uint40
);
/**
* Gets the queue element at a particular index.
* @param _index Index of the queue element to access.
* @return _element Queue element at the given index.
*/
function getQueueElement(
uint256 _index
)
external
view
returns (
Lib_OVMCodec.QueueElement memory _element
);
/**
* Returns the timestamp of the last transaction.
* @return Timestamp for the last transaction.
*/
function getLastTimestamp()
external
view
returns (
uint40
);
/**
* Returns the blocknumber of the last transaction.
* @return Blocknumber for the last transaction.
*/
function getLastBlockNumber()
external
view
returns (
uint40
);
/**
* Get the number of queue elements which have not yet been included.
* @return Number of pending queue elements.
*/
function getNumPendingQueueElements()
external
view
returns (
uint40
);
/**
* Retrieves the length of the queue, including
* both pending and canonical transactions.
* @return Length of the queue.
*/
function getQueueLength()
external
view
returns (
uint40
);
/**
* Adds a transaction to the queue.
* @param _target Target contract to send the transaction to.
* @param _gasLimit Gas limit for the given transaction.
* @param _data Transaction data.
*/
function enqueue(
address _target,
uint256 _gasLimit,
bytes memory _data
)
external;
/**
* Appends a given number of queued transactions as a single batch.
* @param _numQueuedTransactions Number of transactions to append.
*/
function appendQueueBatch(
uint256 _numQueuedTransactions
)
external;
/**
* Allows the sequencer to append a batch of transactions.
* @dev This function uses a custom encoding scheme for efficiency reasons.
* .param _shouldStartAtElement Specific batch we expect to start appending to.
* .param _totalElementsToAppend Total number of batch elements we expect to append.
* .param _contexts Array of batch contexts.
* .param _transactionDataFields Array of raw transaction data.
*/
function appendSequencerBatch(
// uint40 _shouldStartAtElement,
// uint24 _totalElementsToAppend,
// BatchContext[] _contexts,
// bytes[] _transactionDataFields
)
external;
/**
* Verifies whether a transaction is included in the chain.
* @param _transaction Transaction to verify.
* @param _txChainElement Transaction chain element corresponding to the transaction.
* @param _batchHeader Header of the batch the transaction was included in.
* @param _inclusionProof Inclusion proof for the provided transaction chain element.
* @return True if the transaction exists in the CTC, false if not.
*/
function verifyTransaction(
Lib_OVMCodec.Transaction memory _transaction,
Lib_OVMCodec.TransactionChainElement memory _txChainElement,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _inclusionProof
)
external
view
returns (
bool
);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title iOVM_ChainStorageContainer
*/
interface iOVM_ChainStorageContainer {
/********************
* Public Functions *
********************/
/**
* Sets the container's global metadata field. We're using `bytes27` here because we use five
* bytes to maintain the length of the underlying data structure, meaning we have an extra
* 27 bytes to store arbitrary data.
* @param _globalMetadata New global metadata to set.
*/
function setGlobalMetadata(
bytes27 _globalMetadata
)
external;
/**
* Retrieves the container's global metadata field.
* @return Container global metadata field.
*/
function getGlobalMetadata()
external
view
returns (
bytes27
);
/**
* Retrieves the number of objects stored in the container.
* @return Number of objects in the container.
*/
function length()
external
view
returns (
uint256
);
/**
* Pushes an object into the container.
* @param _object A 32 byte value to insert into the container.
*/
function push(
bytes32 _object
)
external;
/**
* Pushes an object into the container. Function allows setting the global metadata since
* we'll need to touch the "length" storage slot anyway, which also contains the global
* metadata (it's an optimization).
* @param _object A 32 byte value to insert into the container.
* @param _globalMetadata New global metadata for the container.
*/
function push(
bytes32 _object,
bytes27 _globalMetadata
)
external;
/**
* Retrieves an object from the container.
* @param _index Index of the particular object to access.
* @return 32 byte object value.
*/
function get(
uint256 _index
)
external
view
returns (
bytes32
);
/**
* Removes all objects after and including a given index.
* @param _index Object index to delete from.
*/
function deleteElementsAfterInclusive(
uint256 _index
)
external;
/**
* Removes all objects after and including a given index. Also allows setting the global
* metadata field.
* @param _index Object index to delete from.
* @param _globalMetadata New global metadata for the container.
*/
function deleteElementsAfterInclusive(
uint256 _index,
bytes27 _globalMetadata
)
external;
/**
* Marks an index as overwritable, meaing the underlying buffer can start to write values over
* any objects before and including the given index.
*/
function setNextOverwritableIndex(
uint256 _index
)
external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
/**
* @title iOVM_StateCommitmentChain
*/
interface iOVM_StateCommitmentChain {
/**********
* Events *
**********/
event StateBatchAppended(
uint256 indexed _batchIndex,
bytes32 _batchRoot,
uint256 _batchSize,
uint256 _prevTotalElements,
bytes _extraData
);
event StateBatchDeleted(
uint256 indexed _batchIndex,
bytes32 _batchRoot
);
/********************
* Public Functions *
********************/
/**
* Retrieves the total number of elements submitted.
* @return _totalElements Total submitted elements.
*/
function getTotalElements()
external
view
returns (
uint256 _totalElements
);
/**
* Retrieves the total number of batches submitted.
* @return _totalBatches Total submitted batches.
*/
function getTotalBatches()
external
view
returns (
uint256 _totalBatches
);
/**
* Retrieves the timestamp of the last batch submitted by the sequencer.
* @return _lastSequencerTimestamp Last sequencer batch timestamp.
*/
function getLastSequencerTimestamp()
external
view
returns (
uint256 _lastSequencerTimestamp
);
/**
* Appends a batch of state roots to the chain.
* @param _batch Batch of state roots.
* @param _shouldStartAtElement Index of the element at which this batch should start.
*/
function appendStateBatch(
bytes32[] calldata _batch,
uint256 _shouldStartAtElement
)
external;
/**
* Deletes all state roots after (and including) a given batch.
* @param _batchHeader Header of the batch to start deleting from.
*/
function deleteStateBatch(
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
external;
/**
* Verifies a batch inclusion proof.
* @param _element Hash of the element to verify a proof for.
* @param _batchHeader Header of the batch in which the element was included.
* @param _proof Merkle inclusion proof for the element.
*/
function verifyStateCommitment(
bytes32 _element,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _proof
)
external
view
returns (
bool _verified
);
/**
* Checks whether a given batch is still inside its fraud proof window.
* @param _batchHeader Header of the batch to check.
* @return _inside Whether or not the batch is inside the fraud proof window.
*/
function insideFraudProofWindow(
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
external
view
returns (
bool _inside
);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
interface ERC20 {
function transfer(address, uint256) external returns (bool);
function transferFrom(address, address, uint256) external returns (bool);
}
/// All the errors which may be encountered on the bond manager
library Errors {
string constant ERC20_ERR = "BondManager: Could not post bond";
string constant ALREADY_FINALIZED = "BondManager: Fraud proof for this pre-state root has already been finalized";
string constant SLASHED = "BondManager: Cannot finalize withdrawal, you probably got slashed";
string constant WRONG_STATE = "BondManager: Wrong bond state for proposer";
string constant CANNOT_CLAIM = "BondManager: Cannot claim yet. Dispute must be finalized first";
string constant WITHDRAWAL_PENDING = "BondManager: Withdrawal already pending";
string constant TOO_EARLY = "BondManager: Too early to finalize your withdrawal";
string constant ONLY_TRANSITIONER = "BondManager: Only the transitioner for this pre-state root may call this function";
string constant ONLY_FRAUD_VERIFIER = "BondManager: Only the fraud verifier may call this function";
string constant ONLY_STATE_COMMITMENT_CHAIN = "BondManager: Only the state commitment chain may call this function";
string constant WAIT_FOR_DISPUTES = "BondManager: Wait for other potential disputes";
}
/**
* @title iOVM_BondManager
*/
interface iOVM_BondManager {
/*******************
* Data Structures *
*******************/
/// The lifecycle of a proposer's bond
enum State {
// Before depositing or after getting slashed, a user is uncollateralized
NOT_COLLATERALIZED,
// After depositing, a user is collateralized
COLLATERALIZED,
// After a user has initiated a withdrawal
WITHDRAWING
}
/// A bond posted by a proposer
struct Bond {
// The user's state
State state;
// The timestamp at which a proposer issued their withdrawal request
uint32 withdrawalTimestamp;
// The time when the first disputed was initiated for this bond
uint256 firstDisputeAt;
// The earliest observed state root for this bond which has had fraud
bytes32 earliestDisputedStateRoot;
// The state root's timestamp
uint256 earliestTimestamp;
}
// Per pre-state root, store the number of state provisions that were made
// and how many of these calls were made by each user. Payouts will then be
// claimed by users proportionally for that dispute.
struct Rewards {
// Flag to check if rewards for a fraud proof are claimable
bool canClaim;
// Total number of `recordGasSpent` calls made
uint256 total;
// The gas spent by each user to provide witness data. The sum of all
// values inside this map MUST be equal to the value of `total`
mapping(address => uint256) gasSpent;
}
/********************
* Public Functions *
********************/
function recordGasSpent(
bytes32 _preStateRoot,
bytes32 _txHash,
address _who,
uint256 _gasSpent
) external;
function finalize(
bytes32 _preStateRoot,
address _publisher,
uint256 _timestamp
) external;
function deposit() external;
function startWithdrawal() external;
function finalizeWithdrawal() external;
function claim(
address _who
) external;
function isCollateralized(
address _who
) external view returns (bool);
function getGasSpent(
bytes32 _preStateRoot,
address _who
) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
/* Interface Imports */
import { iOVM_StateTransitioner } from "./iOVM_StateTransitioner.sol";
/**
* @title iOVM_FraudVerifier
*/
interface iOVM_FraudVerifier {
/**********
* Events *
**********/
event FraudProofInitialized(
bytes32 _preStateRoot,
uint256 _preStateRootIndex,
bytes32 _transactionHash,
address _who
);
event FraudProofFinalized(
bytes32 _preStateRoot,
uint256 _preStateRootIndex,
bytes32 _transactionHash,
address _who
);
/***************************************
* Public Functions: Transition Status *
***************************************/
function getStateTransitioner(bytes32 _preStateRoot, bytes32 _txHash) external view returns (iOVM_StateTransitioner _transitioner);
/****************************************
* Public Functions: Fraud Verification *
****************************************/
function initializeFraudVerification(
bytes32 _preStateRoot,
Lib_OVMCodec.ChainBatchHeader calldata _preStateRootBatchHeader,
Lib_OVMCodec.ChainInclusionProof calldata _preStateRootProof,
Lib_OVMCodec.Transaction calldata _transaction,
Lib_OVMCodec.TransactionChainElement calldata _txChainElement,
Lib_OVMCodec.ChainBatchHeader calldata _transactionBatchHeader,
Lib_OVMCodec.ChainInclusionProof calldata _transactionProof
) external;
function finalizeFraudVerification(
bytes32 _preStateRoot,
Lib_OVMCodec.ChainBatchHeader calldata _preStateRootBatchHeader,
Lib_OVMCodec.ChainInclusionProof calldata _preStateRootProof,
bytes32 _txHash,
bytes32 _postStateRoot,
Lib_OVMCodec.ChainBatchHeader calldata _postStateRootBatchHeader,
Lib_OVMCodec.ChainInclusionProof calldata _postStateRootProof
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
/**
* @title iOVM_StateTransitioner
*/
interface iOVM_StateTransitioner {
/**********
* Events *
**********/
event AccountCommitted(
address _address
);
event ContractStorageCommitted(
address _address,
bytes32 _key
);
/**********************************
* Public Functions: State Access *
**********************************/
function getPreStateRoot() external view returns (bytes32 _preStateRoot);
function getPostStateRoot() external view returns (bytes32 _postStateRoot);
function isComplete() external view returns (bool _complete);
/***********************************
* Public Functions: Pre-Execution *
***********************************/
function proveContractState(
address _ovmContractAddress,
address _ethContractAddress,
bytes calldata _stateTrieWitness
) external;
function proveStorageSlot(
address _ovmContractAddress,
bytes32 _key,
bytes calldata _storageTrieWitness
) external;
/*******************************
* Public Functions: Execution *
*******************************/
function applyTransaction(
Lib_OVMCodec.Transaction calldata _transaction
) external;
/************************************
* Public Functions: Post-Execution *
************************************/
function commitContractState(
address _ovmContractAddress,
bytes calldata _stateTrieWitness
) external;
function commitStorageSlot(
address _ovmContractAddress,
bytes32 _key,
bytes calldata _storageTrieWitness
) external;
/**********************************
* Public Functions: Finalization *
**********************************/
function completeTransition() external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Contract Imports */
import { iOVM_StateTransitioner } from "./iOVM_StateTransitioner.sol";
/**
* @title iOVM_StateTransitionerFactory
*/
interface iOVM_StateTransitionerFactory {
/***************************************
* Public Functions: Contract Creation *
***************************************/
function create(
address _proxyManager,
uint256 _stateTransitionIndex,
bytes32 _preStateRoot,
bytes32 _transactionHash
)
external
returns (
iOVM_StateTransitioner _ovmStateTransitioner
);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol";
import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol";
import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol";
import { Lib_Bytes32Utils } from "../utils/Lib_Bytes32Utils.sol";
import { Lib_SafeExecutionManagerWrapper } from "../../libraries/wrappers/Lib_SafeExecutionManagerWrapper.sol";
/**
* @title Lib_OVMCodec
*/
library Lib_OVMCodec {
/*********
* Enums *
*********/
enum EOASignatureType {
EIP155_TRANSACTION,
ETH_SIGNED_MESSAGE
}
enum QueueOrigin {
SEQUENCER_QUEUE,
L1TOL2_QUEUE
}
/***********
* Structs *
***********/
struct Account {
uint256 nonce;
uint256 balance;
bytes32 storageRoot;
bytes32 codeHash;
address ethAddress;
bool isFresh;
}
struct EVMAccount {
uint256 nonce;
uint256 balance;
bytes32 storageRoot;
bytes32 codeHash;
}
struct ChainBatchHeader {
uint256 batchIndex;
bytes32 batchRoot;
uint256 batchSize;
uint256 prevTotalElements;
bytes extraData;
}
struct ChainInclusionProof {
uint256 index;
bytes32[] siblings;
}
struct Transaction {
uint256 timestamp;
uint256 blockNumber;
QueueOrigin l1QueueOrigin;
address l1TxOrigin;
address entrypoint;
uint256 gasLimit;
bytes data;
}
struct TransactionChainElement {
bool isSequenced;
uint256 queueIndex; // QUEUED TX ONLY
uint256 timestamp; // SEQUENCER TX ONLY
uint256 blockNumber; // SEQUENCER TX ONLY
bytes txData; // SEQUENCER TX ONLY
}
struct QueueElement {
bytes32 transactionHash;
uint40 timestamp;
uint40 blockNumber;
}
struct EIP155Transaction {
uint256 nonce;
uint256 gasPrice;
uint256 gasLimit;
address to;
uint256 value;
bytes data;
uint256 chainId;
}
/**********************
* Internal Functions *
**********************/
/**
* Decodes an EOA transaction (i.e., native Ethereum RLP encoding).
* @param _transaction Encoded EOA transaction.
* @return Transaction decoded into a struct.
*/
function decodeEIP155Transaction(
bytes memory _transaction,
bool _isEthSignedMessage
)
internal
pure
returns (
EIP155Transaction memory
)
{
if (_isEthSignedMessage) {
(
uint256 _nonce,
uint256 _gasLimit,
uint256 _gasPrice,
uint256 _chainId,
address _to,
bytes memory _data
) = abi.decode(
_transaction,
(uint256, uint256, uint256, uint256, address ,bytes)
);
return EIP155Transaction({
nonce: _nonce,
gasPrice: _gasPrice,
gasLimit: _gasLimit,
to: _to,
value: 0,
data: _data,
chainId: _chainId
});
} else {
Lib_RLPReader.RLPItem[] memory decoded = Lib_RLPReader.readList(_transaction);
return EIP155Transaction({
nonce: Lib_RLPReader.readUint256(decoded[0]),
gasPrice: Lib_RLPReader.readUint256(decoded[1]),
gasLimit: Lib_RLPReader.readUint256(decoded[2]),
to: Lib_RLPReader.readAddress(decoded[3]),
value: Lib_RLPReader.readUint256(decoded[4]),
data: Lib_RLPReader.readBytes(decoded[5]),
chainId: Lib_RLPReader.readUint256(decoded[6])
});
}
}
/**
* Decompresses a compressed EIP155 transaction.
* @param _transaction Compressed EIP155 transaction bytes.
* @return Transaction parsed into a struct.
*/
function decompressEIP155Transaction(
bytes memory _transaction
)
internal
returns (
EIP155Transaction memory
)
{
return EIP155Transaction({
gasLimit: Lib_BytesUtils.toUint24(_transaction, 0),
gasPrice: uint256(Lib_BytesUtils.toUint24(_transaction, 3)) * 1000000,
nonce: Lib_BytesUtils.toUint24(_transaction, 6),
to: Lib_BytesUtils.toAddress(_transaction, 9),
data: Lib_BytesUtils.slice(_transaction, 29),
chainId: Lib_SafeExecutionManagerWrapper.safeCHAINID(),
value: 0
});
}
/**
* Encodes an EOA transaction back into the original transaction.
* @param _transaction EIP155transaction to encode.
* @param _isEthSignedMessage Whether or not this was an eth signed message.
* @return Encoded transaction.
*/
function encodeEIP155Transaction(
EIP155Transaction memory _transaction,
bool _isEthSignedMessage
)
internal
pure
returns (
bytes memory
)
{
if (_isEthSignedMessage) {
return abi.encode(
_transaction.nonce,
_transaction.gasLimit,
_transaction.gasPrice,
_transaction.chainId,
_transaction.to,
_transaction.data
);
} else {
bytes[] memory raw = new bytes[](9);
raw[0] = Lib_RLPWriter.writeUint(_transaction.nonce);
raw[1] = Lib_RLPWriter.writeUint(_transaction.gasPrice);
raw[2] = Lib_RLPWriter.writeUint(_transaction.gasLimit);
if (_transaction.to == address(0)) {
raw[3] = Lib_RLPWriter.writeBytes('');
} else {
raw[3] = Lib_RLPWriter.writeAddress(_transaction.to);
}
raw[4] = Lib_RLPWriter.writeUint(0);
raw[5] = Lib_RLPWriter.writeBytes(_transaction.data);
raw[6] = Lib_RLPWriter.writeUint(_transaction.chainId);
raw[7] = Lib_RLPWriter.writeBytes(bytes(''));
raw[8] = Lib_RLPWriter.writeBytes(bytes(''));
return Lib_RLPWriter.writeList(raw);
}
}
/**
* Encodes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Encoded transaction bytes.
*/
function encodeTransaction(
Transaction memory _transaction
)
internal
pure
returns (
bytes memory
)
{
return abi.encodePacked(
_transaction.timestamp,
_transaction.blockNumber,
_transaction.l1QueueOrigin,
_transaction.l1TxOrigin,
_transaction.entrypoint,
_transaction.gasLimit,
_transaction.data
);
}
/**
* Hashes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Hashed transaction
*/
function hashTransaction(
Transaction memory _transaction
)
internal
pure
returns (
bytes32
)
{
return keccak256(encodeTransaction(_transaction));
}
/**
* Converts an OVM account to an EVM account.
* @param _in OVM account to convert.
* @return Converted EVM account.
*/
function toEVMAccount(
Account memory _in
)
internal
pure
returns (
EVMAccount memory
)
{
return EVMAccount({
nonce: _in.nonce,
balance: _in.balance,
storageRoot: _in.storageRoot,
codeHash: _in.codeHash
});
}
/**
* @notice RLP-encodes an account state struct.
* @param _account Account state struct.
* @return RLP-encoded account state.
*/
function encodeEVMAccount(
EVMAccount memory _account
)
internal
pure
returns (
bytes memory
)
{
bytes[] memory raw = new bytes[](4);
// Unfortunately we can't create this array outright because
// Lib_RLPWriter.writeList will reject fixed-size arrays. Assigning
// index-by-index circumvents this issue.
raw[0] = Lib_RLPWriter.writeBytes(
Lib_Bytes32Utils.removeLeadingZeros(
bytes32(_account.nonce)
)
);
raw[1] = Lib_RLPWriter.writeBytes(
Lib_Bytes32Utils.removeLeadingZeros(
bytes32(_account.balance)
)
);
raw[2] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.storageRoot));
raw[3] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.codeHash));
return Lib_RLPWriter.writeList(raw);
}
/**
* @notice Decodes an RLP-encoded account state into a useful struct.
* @param _encoded RLP-encoded account state.
* @return Account state struct.
*/
function decodeEVMAccount(
bytes memory _encoded
)
internal
pure
returns (
EVMAccount memory
)
{
Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(_encoded);
return EVMAccount({
nonce: Lib_RLPReader.readUint256(accountState[0]),
balance: Lib_RLPReader.readUint256(accountState[1]),
storageRoot: Lib_RLPReader.readBytes32(accountState[2]),
codeHash: Lib_RLPReader.readBytes32(accountState[3])
});
}
/**
* Calculates a hash for a given batch header.
* @param _batchHeader Header to hash.
* @return Hash of the header.
*/
function hashBatchHeader(
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
internal
pure
returns (
bytes32
)
{
return keccak256(
abi.encode(
_batchHeader.batchRoot,
_batchHeader.batchSize,
_batchHeader.prevTotalElements,
_batchHeader.extraData
)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Contract Imports */
import { Ownable } from "./Lib_Ownable.sol";
/**
* @title Lib_AddressManager
*/
contract Lib_AddressManager is Ownable {
/**********
* Events *
**********/
event AddressSet(
string _name,
address _newAddress
);
/*******************************************
* Contract Variables: Internal Accounting *
*******************************************/
mapping (bytes32 => address) private addresses;
/********************
* Public Functions *
********************/
function setAddress(
string memory _name,
address _address
)
public
onlyOwner
{
emit AddressSet(_name, _address);
addresses[_getNameHash(_name)] = _address;
}
function getAddress(
string memory _name
)
public
view
returns (address)
{
return addresses[_getNameHash(_name)];
}
/**********************
* Internal Functions *
**********************/
function _getNameHash(
string memory _name
)
internal
pure
returns (
bytes32 _hash
)
{
return keccak256(abi.encodePacked(_name));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_AddressManager } from "./Lib_AddressManager.sol";
/**
* @title Lib_AddressResolver
*/
abstract contract Lib_AddressResolver {
/*******************************************
* Contract Variables: Contract References *
*******************************************/
Lib_AddressManager public libAddressManager;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Lib_AddressManager.
*/
constructor(
address _libAddressManager
) {
libAddressManager = Lib_AddressManager(_libAddressManager);
}
/********************
* Public Functions *
********************/
function resolve(
string memory _name
)
public
view
returns (
address _contract
)
{
return libAddressManager.getAddress(_name);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Ownable
* @dev Adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol
*/
abstract contract Ownable {
/*************
* Variables *
*************/
address public owner;
/**********
* Events *
**********/
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/***************
* Constructor *
***************/
constructor() {
owner = msg.sender;
emit OwnershipTransferred(address(0), owner);
}
/**********************
* Function Modifiers *
**********************/
modifier onlyOwner() {
require(
owner == msg.sender,
"Ownable: caller is not the owner"
);
_;
}
/********************
* Public Functions *
********************/
function renounceOwnership()
public
virtual
onlyOwner
{
emit OwnershipTransferred(owner, address(0));
owner = address(0);
}
function transferOwnership(address _newOwner)
public
virtual
onlyOwner
{
require(
_newOwner != address(0),
"Ownable: new owner cannot be the zero address"
);
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_RLPReader
* @dev Adapted from "RLPReader" by Hamdi Allam ([email protected]).
*/
library Lib_RLPReader {
/*************
* Constants *
*************/
uint256 constant internal MAX_LIST_LENGTH = 32;
/*********
* Enums *
*********/
enum RLPItemType {
DATA_ITEM,
LIST_ITEM
}
/***********
* Structs *
***********/
struct RLPItem {
uint256 length;
uint256 ptr;
}
/**********************
* Internal Functions *
**********************/
/**
* Converts bytes to a reference to memory position and length.
* @param _in Input bytes to convert.
* @return Output memory reference.
*/
function toRLPItem(
bytes memory _in
)
internal
pure
returns (
RLPItem memory
)
{
uint256 ptr;
assembly {
ptr := add(_in, 32)
}
return RLPItem({
length: _in.length,
ptr: ptr
});
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(
RLPItem memory _in
)
internal
pure
returns (
RLPItem[] memory
)
{
(
uint256 listOffset,
,
RLPItemType itemType
) = _decodeLength(_in);
require(
itemType == RLPItemType.LIST_ITEM,
"Invalid RLP list value."
);
// Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by
// writing to the length. Since we can't know the number of RLP items without looping over
// the entire input, we'd have to loop twice to accurately size this array. It's easier to
// simply set a reasonable maximum list length and decrease the size before we finish.
RLPItem[] memory out = new RLPItem[](MAX_LIST_LENGTH);
uint256 itemCount = 0;
uint256 offset = listOffset;
while (offset < _in.length) {
require(
itemCount < MAX_LIST_LENGTH,
"Provided RLP list exceeds max list length."
);
(
uint256 itemOffset,
uint256 itemLength,
) = _decodeLength(RLPItem({
length: _in.length - offset,
ptr: _in.ptr + offset
}));
out[itemCount] = RLPItem({
length: itemLength + itemOffset,
ptr: _in.ptr + offset
});
itemCount += 1;
offset += itemOffset + itemLength;
}
// Decrease the array size to match the actual item count.
assembly {
mstore(out, itemCount)
}
return out;
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(
bytes memory _in
)
internal
pure
returns (
RLPItem[] memory
)
{
return readList(
toRLPItem(_in)
);
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(
RLPItem memory _in
)
internal
pure
returns (
bytes memory
)
{
(
uint256 itemOffset,
uint256 itemLength,
RLPItemType itemType
) = _decodeLength(_in);
require(
itemType == RLPItemType.DATA_ITEM,
"Invalid RLP bytes value."
);
return _copy(_in.ptr, itemOffset, itemLength);
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(
bytes memory _in
)
internal
pure
returns (
bytes memory
)
{
return readBytes(
toRLPItem(_in)
);
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(
RLPItem memory _in
)
internal
pure
returns (
string memory
)
{
return string(readBytes(_in));
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(
bytes memory _in
)
internal
pure
returns (
string memory
)
{
return readString(
toRLPItem(_in)
);
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(
RLPItem memory _in
)
internal
pure
returns (
bytes32
)
{
require(
_in.length <= 33,
"Invalid RLP bytes32 value."
);
(
uint256 itemOffset,
uint256 itemLength,
RLPItemType itemType
) = _decodeLength(_in);
require(
itemType == RLPItemType.DATA_ITEM,
"Invalid RLP bytes32 value."
);
uint256 ptr = _in.ptr + itemOffset;
bytes32 out;
assembly {
out := mload(ptr)
// Shift the bytes over to match the item size.
if lt(itemLength, 32) {
out := div(out, exp(256, sub(32, itemLength)))
}
}
return out;
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(
bytes memory _in
)
internal
pure
returns (
bytes32
)
{
return readBytes32(
toRLPItem(_in)
);
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(
RLPItem memory _in
)
internal
pure
returns (
uint256
)
{
return uint256(readBytes32(_in));
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(
bytes memory _in
)
internal
pure
returns (
uint256
)
{
return readUint256(
toRLPItem(_in)
);
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(
RLPItem memory _in
)
internal
pure
returns (
bool
)
{
require(
_in.length == 1,
"Invalid RLP boolean value."
);
uint256 ptr = _in.ptr;
uint256 out;
assembly {
out := byte(0, mload(ptr))
}
require(
out == 0 || out == 1,
"Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1"
);
return out != 0;
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(
bytes memory _in
)
internal
pure
returns (
bool
)
{
return readBool(
toRLPItem(_in)
);
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(
RLPItem memory _in
)
internal
pure
returns (
address
)
{
if (_in.length == 1) {
return address(0);
}
require(
_in.length == 21,
"Invalid RLP address value."
);
return address(readUint256(_in));
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(
bytes memory _in
)
internal
pure
returns (
address
)
{
return readAddress(
toRLPItem(_in)
);
}
/**
* Reads the raw bytes of an RLP item.
* @param _in RLP item to read.
* @return Raw RLP bytes.
*/
function readRawBytes(
RLPItem memory _in
)
internal
pure
returns (
bytes memory
)
{
return _copy(_in);
}
/*********************
* Private Functions *
*********************/
/**
* Decodes the length of an RLP item.
* @param _in RLP item to decode.
* @return Offset of the encoded data.
* @return Length of the encoded data.
* @return RLP item type (LIST_ITEM or DATA_ITEM).
*/
function _decodeLength(
RLPItem memory _in
)
private
pure
returns (
uint256,
uint256,
RLPItemType
)
{
require(
_in.length > 0,
"RLP item cannot be null."
);
uint256 ptr = _in.ptr;
uint256 prefix;
assembly {
prefix := byte(0, mload(ptr))
}
if (prefix <= 0x7f) {
// Single byte.
return (0, 1, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xb7) {
// Short string.
uint256 strLen = prefix - 0x80;
require(
_in.length > strLen,
"Invalid RLP short string."
);
return (1, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xbf) {
// Long string.
uint256 lenOfStrLen = prefix - 0xb7;
require(
_in.length > lenOfStrLen,
"Invalid RLP long string length."
);
uint256 strLen;
assembly {
// Pick out the string length.
strLen := div(
mload(add(ptr, 1)),
exp(256, sub(32, lenOfStrLen))
)
}
require(
_in.length > lenOfStrLen + strLen,
"Invalid RLP long string."
);
return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xf7) {
// Short list.
uint256 listLen = prefix - 0xc0;
require(
_in.length > listLen,
"Invalid RLP short list."
);
return (1, listLen, RLPItemType.LIST_ITEM);
} else {
// Long list.
uint256 lenOfListLen = prefix - 0xf7;
require(
_in.length > lenOfListLen,
"Invalid RLP long list length."
);
uint256 listLen;
assembly {
// Pick out the list length.
listLen := div(
mload(add(ptr, 1)),
exp(256, sub(32, lenOfListLen))
)
}
require(
_in.length > lenOfListLen + listLen,
"Invalid RLP long list."
);
return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM);
}
}
/**
* Copies the bytes from a memory location.
* @param _src Pointer to the location to read from.
* @param _offset Offset to start reading from.
* @param _length Number of bytes to read.
* @return Copied bytes.
*/
function _copy(
uint256 _src,
uint256 _offset,
uint256 _length
)
private
pure
returns (
bytes memory
)
{
bytes memory out = new bytes(_length);
if (out.length == 0) {
return out;
}
uint256 src = _src + _offset;
uint256 dest;
assembly {
dest := add(out, 32)
}
// Copy over as many complete words as we can.
for (uint256 i = 0; i < _length / 32; i++) {
assembly {
mstore(dest, mload(src))
}
src += 32;
dest += 32;
}
// Pick out the remaining bytes.
uint256 mask = 256 ** (32 - (_length % 32)) - 1;
assembly {
mstore(
dest,
or(
and(mload(src), not(mask)),
and(mload(dest), mask)
)
)
}
return out;
}
/**
* Copies an RLP item into bytes.
* @param _in RLP item to copy.
* @return Copied bytes.
*/
function _copy(
RLPItem memory _in
)
private
pure
returns (
bytes memory
)
{
return _copy(_in.ptr, 0, _in.length);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol";
/**
* @title Lib_RLPWriter
* @author Bakaoh (with modifications)
*/
library Lib_RLPWriter {
/**********************
* Internal Functions *
**********************/
/**
* RLP encodes a byte string.
* @param _in The byte string to encode.
* @return _out The RLP encoded string in bytes.
*/
function writeBytes(
bytes memory _in
)
internal
pure
returns (
bytes memory _out
)
{
bytes memory encoded;
if (_in.length == 1 && uint8(_in[0]) < 128) {
encoded = _in;
} else {
encoded = abi.encodePacked(_writeLength(_in.length, 128), _in);
}
return encoded;
}
/**
* RLP encodes a list of RLP encoded byte byte strings.
* @param _in The list of RLP encoded byte strings.
* @return _out The RLP encoded list of items in bytes.
*/
function writeList(
bytes[] memory _in
)
internal
pure
returns (
bytes memory _out
)
{
bytes memory list = _flatten(_in);
return abi.encodePacked(_writeLength(list.length, 192), list);
}
/**
* RLP encodes a string.
* @param _in The string to encode.
* @return _out The RLP encoded string in bytes.
*/
function writeString(
string memory _in
)
internal
pure
returns (
bytes memory _out
)
{
return writeBytes(bytes(_in));
}
/**
* RLP encodes an address.
* @param _in The address to encode.
* @return _out The RLP encoded address in bytes.
*/
function writeAddress(
address _in
)
internal
pure
returns (
bytes memory _out
)
{
return writeBytes(abi.encodePacked(_in));
}
/**
* RLP encodes a uint.
* @param _in The uint256 to encode.
* @return _out The RLP encoded uint256 in bytes.
*/
function writeUint(
uint256 _in
)
internal
pure
returns (
bytes memory _out
)
{
return writeBytes(_toBinary(_in));
}
/**
* RLP encodes a bool.
* @param _in The bool to encode.
* @return _out The RLP encoded bool in bytes.
*/
function writeBool(
bool _in
)
internal
pure
returns (
bytes memory _out
)
{
bytes memory encoded = new bytes(1);
encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80));
return encoded;
}
/*********************
* Private Functions *
*********************/
/**
* Encode the first byte, followed by the `len` in binary form if `length` is more than 55.
* @param _len The length of the string or the payload.
* @param _offset 128 if item is string, 192 if item is list.
* @return _encoded RLP encoded bytes.
*/
function _writeLength(
uint256 _len,
uint256 _offset
)
private
pure
returns (
bytes memory _encoded
)
{
bytes memory encoded;
if (_len < 56) {
encoded = new bytes(1);
encoded[0] = byte(uint8(_len) + uint8(_offset));
} else {
uint256 lenLen;
uint256 i = 1;
while (_len / i != 0) {
lenLen++;
i *= 256;
}
encoded = new bytes(lenLen + 1);
encoded[0] = byte(uint8(lenLen) + uint8(_offset) + 55);
for(i = 1; i <= lenLen; i++) {
encoded[i] = byte(uint8((_len / (256**(lenLen-i))) % 256));
}
}
return encoded;
}
/**
* Encode integer in big endian binary form with no leading zeroes.
* @notice TODO: This should be optimized with assembly to save gas costs.
* @param _x The integer to encode.
* @return _binary RLP encoded bytes.
*/
function _toBinary(
uint256 _x
)
private
pure
returns (
bytes memory _binary
)
{
bytes memory b = abi.encodePacked(_x);
uint256 i = 0;
for (; i < 32; i++) {
if (b[i] != 0) {
break;
}
}
bytes memory res = new bytes(32 - i);
for (uint256 j = 0; j < res.length; j++) {
res[j] = b[i++];
}
return res;
}
/**
* Copies a piece of memory to another location.
* @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol.
* @param _dest Destination location.
* @param _src Source location.
* @param _len Length of memory to copy.
*/
function _memcpy(
uint256 _dest,
uint256 _src,
uint256 _len
)
private
pure
{
uint256 dest = _dest;
uint256 src = _src;
uint256 len = _len;
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint256 mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/**
* Flattens a list of byte strings into one byte string.
* @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol.
* @param _list List of byte strings to flatten.
* @return _flattened The flattened byte string.
*/
function _flatten(
bytes[] memory _list
)
private
pure
returns (
bytes memory _flattened
)
{
if (_list.length == 0) {
return new bytes(0);
}
uint256 len;
uint256 i = 0;
for (; i < _list.length; i++) {
len += _list[i].length;
}
bytes memory flattened = new bytes(len);
uint256 flattenedPtr;
assembly { flattenedPtr := add(flattened, 0x20) }
for(i = 0; i < _list.length; i++) {
bytes memory item = _list[i];
uint256 listPtr;
assembly { listPtr := add(item, 0x20)}
_memcpy(flattenedPtr, listPtr, item.length);
flattenedPtr += _list[i].length;
}
return flattened;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_Byte32Utils
*/
library Lib_Bytes32Utils {
/**********************
* Internal Functions *
**********************/
/**
* Converts a bytes32 value to a boolean. Anything non-zero will be converted to "true."
* @param _in Input bytes32 value.
* @return Bytes32 as a boolean.
*/
function toBool(
bytes32 _in
)
internal
pure
returns (
bool
)
{
return _in != 0;
}
/**
* Converts a boolean to a bytes32 value.
* @param _in Input boolean value.
* @return Boolean as a bytes32.
*/
function fromBool(
bool _in
)
internal
pure
returns (
bytes32
)
{
return bytes32(uint256(_in ? 1 : 0));
}
/**
* Converts a bytes32 value to an address. Takes the *last* 20 bytes.
* @param _in Input bytes32 value.
* @return Bytes32 as an address.
*/
function toAddress(
bytes32 _in
)
internal
pure
returns (
address
)
{
return address(uint160(uint256(_in)));
}
/**
* Converts an address to a bytes32.
* @param _in Input address value.
* @return Address as a bytes32.
*/
function fromAddress(
address _in
)
internal
pure
returns (
bytes32
)
{
return bytes32(uint256(_in));
}
/**
* Removes the leading zeros from a bytes32 value and returns a new (smaller) bytes value.
* @param _in Input bytes32 value.
* @return Bytes32 without any leading zeros.
*/
function removeLeadingZeros(
bytes32 _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory out;
assembly {
// Figure out how many leading zero bytes to remove.
let shift := 0
for { let i := 0 } and(lt(i, 32), eq(byte(i, _in), 0)) { i := add(i, 1) } {
shift := add(shift, 1)
}
// Reserve some space for our output and fix the free memory pointer.
out := mload(0x40)
mstore(0x40, add(out, 0x40))
// Shift the value and store it into the output bytes.
mstore(add(out, 0x20), shl(mul(shift, 8), _in))
// Store the new size (with leading zero bytes removed) in the output byte size.
mstore(out, sub(32, shift))
}
return out;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_BytesUtils
*/
library Lib_BytesUtils {
/**********************
* Internal Functions *
**********************/
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
)
internal
pure
returns (bytes memory)
{
require(_length + 31 >= _length, "slice_overflow");
require(_start + _length >= _start, "slice_overflow");
require(_bytes.length >= _start + _length, "slice_outOfBounds");
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function slice(
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (bytes memory)
{
if (_bytes.length - _start == 0) {
return bytes('');
}
return slice(_bytes, _start, _bytes.length - _start);
}
function toBytes32PadLeft(
bytes memory _bytes
)
internal
pure
returns (bytes32)
{
bytes32 ret;
uint256 len = _bytes.length <= 32 ? _bytes.length : 32;
assembly {
ret := shr(mul(sub(32, len), 8), mload(add(_bytes, 32)))
}
return ret;
}
function toBytes32(
bytes memory _bytes
)
internal
pure
returns (bytes32)
{
if (_bytes.length < 32) {
bytes32 ret;
assembly {
ret := mload(add(_bytes, 32))
}
return ret;
}
return abi.decode(_bytes,(bytes32)); // will truncate if input length > 32 bytes
}
function toUint256(
bytes memory _bytes
)
internal
pure
returns (uint256)
{
return uint256(toBytes32(_bytes));
}
function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) {
require(_start + 3 >= _start, "toUint24_overflow");
require(_bytes.length >= _start + 3 , "toUint24_outOfBounds");
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) {
require(_start + 1 >= _start, "toUint8_overflow");
require(_bytes.length >= _start + 1 , "toUint8_outOfBounds");
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
require(_start + 20 >= _start, "toAddress_overflow");
require(_bytes.length >= _start + 20, "toAddress_outOfBounds");
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toNibbles(
bytes memory _bytes
)
internal
pure
returns (bytes memory)
{
bytes memory nibbles = new bytes(_bytes.length * 2);
for (uint256 i = 0; i < _bytes.length; i++) {
nibbles[i * 2] = _bytes[i] >> 4;
nibbles[i * 2 + 1] = bytes1(uint8(_bytes[i]) % 16);
}
return nibbles;
}
function fromNibbles(
bytes memory _bytes
)
internal
pure
returns (bytes memory)
{
bytes memory ret = new bytes(_bytes.length / 2);
for (uint256 i = 0; i < ret.length; i++) {
ret[i] = (_bytes[i * 2] << 4) | (_bytes[i * 2 + 1]);
}
return ret;
}
function equal(
bytes memory _bytes,
bytes memory _other
)
internal
pure
returns (bool)
{
return keccak256(_bytes) == keccak256(_other);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/**
* @title Lib_ErrorUtils
*/
library Lib_ErrorUtils {
/**********************
* Internal Functions *
**********************/
/**
* Encodes an error string into raw solidity-style revert data.
* (i.e. ascii bytes, prefixed with bytes4(keccak("Error(string))"))
* Ref: https://docs.soliditylang.org/en/v0.8.2/control-structures.html?highlight=Error(string)#panic-via-assert-and-error-via-require
* @param _reason Reason for the reversion.
* @return Standard solidity revert data for the given reason.
*/
function encodeRevertString(
string memory _reason
)
internal
pure
returns (
bytes memory
)
{
return abi.encodeWithSignature(
"Error(string)",
_reason
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_ErrorUtils } from "../utils/Lib_ErrorUtils.sol";
/**
* @title Lib_SafeExecutionManagerWrapper
* @dev The Safe Execution Manager Wrapper provides functions which facilitate writing OVM safe
* code using the standard solidity compiler, by routing all its operations through the Execution
* Manager.
*
* Compiler used: solc
* Runtime target: OVM
*/
library Lib_SafeExecutionManagerWrapper {
/**********************
* Internal Functions *
**********************/
/**
* Performs a safe ovmCALL.
* @param _gasLimit Gas limit for the call.
* @param _target Address to call.
* @param _calldata Data to send to the call.
* @return _success Whether or not the call reverted.
* @return _returndata Data returned by the call.
*/
function safeCALL(
uint256 _gasLimit,
address _target,
bytes memory _calldata
)
internal
returns (
bool _success,
bytes memory _returndata
)
{
bytes memory returndata = _safeExecutionManagerInteraction(
abi.encodeWithSignature(
"ovmCALL(uint256,address,bytes)",
_gasLimit,
_target,
_calldata
)
);
return abi.decode(returndata, (bool, bytes));
}
/**
* Performs a safe ovmDELEGATECALL.
* @param _gasLimit Gas limit for the call.
* @param _target Address to call.
* @param _calldata Data to send to the call.
* @return _success Whether or not the call reverted.
* @return _returndata Data returned by the call.
*/
function safeDELEGATECALL(
uint256 _gasLimit,
address _target,
bytes memory _calldata
)
internal
returns (
bool _success,
bytes memory _returndata
)
{
bytes memory returndata = _safeExecutionManagerInteraction(
abi.encodeWithSignature(
"ovmDELEGATECALL(uint256,address,bytes)",
_gasLimit,
_target,
_calldata
)
);
return abi.decode(returndata, (bool, bytes));
}
/**
* Performs a safe ovmCREATE call.
* @param _gasLimit Gas limit for the creation.
* @param _bytecode Code for the new contract.
* @return _contract Address of the created contract.
*/
function safeCREATE(
uint256 _gasLimit,
bytes memory _bytecode
)
internal
returns (
address,
bytes memory
)
{
bytes memory returndata = _safeExecutionManagerInteraction(
_gasLimit,
abi.encodeWithSignature(
"ovmCREATE(bytes)",
_bytecode
)
);
return abi.decode(returndata, (address, bytes));
}
/**
* Performs a safe ovmEXTCODESIZE call.
* @param _contract Address of the contract to query the size of.
* @return _EXTCODESIZE Size of the requested contract in bytes.
*/
function safeEXTCODESIZE(
address _contract
)
internal
returns (
uint256 _EXTCODESIZE
)
{
bytes memory returndata = _safeExecutionManagerInteraction(
abi.encodeWithSignature(
"ovmEXTCODESIZE(address)",
_contract
)
);
return abi.decode(returndata, (uint256));
}
/**
* Performs a safe ovmCHAINID call.
* @return _CHAINID Result of calling ovmCHAINID.
*/
function safeCHAINID()
internal
returns (
uint256 _CHAINID
)
{
bytes memory returndata = _safeExecutionManagerInteraction(
abi.encodeWithSignature(
"ovmCHAINID()"
)
);
return abi.decode(returndata, (uint256));
}
/**
* Performs a safe ovmCALLER call.
* @return _CALLER Result of calling ovmCALLER.
*/
function safeCALLER()
internal
returns (
address _CALLER
)
{
bytes memory returndata = _safeExecutionManagerInteraction(
abi.encodeWithSignature(
"ovmCALLER()"
)
);
return abi.decode(returndata, (address));
}
/**
* Performs a safe ovmADDRESS call.
* @return _ADDRESS Result of calling ovmADDRESS.
*/
function safeADDRESS()
internal
returns (
address _ADDRESS
)
{
bytes memory returndata = _safeExecutionManagerInteraction(
abi.encodeWithSignature(
"ovmADDRESS()"
)
);
return abi.decode(returndata, (address));
}
/**
* Performs a safe ovmGETNONCE call.
* @return _nonce Result of calling ovmGETNONCE.
*/
function safeGETNONCE()
internal
returns (
uint256 _nonce
)
{
bytes memory returndata = _safeExecutionManagerInteraction(
abi.encodeWithSignature(
"ovmGETNONCE()"
)
);
return abi.decode(returndata, (uint256));
}
/**
* Performs a safe ovmINCREMENTNONCE call.
*/
function safeINCREMENTNONCE()
internal
{
_safeExecutionManagerInteraction(
abi.encodeWithSignature(
"ovmINCREMENTNONCE()"
)
);
}
/**
* Performs a safe ovmCREATEEOA call.
* @param _messageHash Message hash which was signed by EOA
* @param _v v value of signature (0 or 1)
* @param _r r value of signature
* @param _s s value of signature
*/
function safeCREATEEOA(
bytes32 _messageHash,
uint8 _v,
bytes32 _r,
bytes32 _s
)
internal
{
_safeExecutionManagerInteraction(
abi.encodeWithSignature(
"ovmCREATEEOA(bytes32,uint8,bytes32,bytes32)",
_messageHash,
_v,
_r,
_s
)
);
}
/**
* Performs a safe REVERT.
* @param _reason String revert reason to pass along with the REVERT.
*/
function safeREVERT(
string memory _reason
)
internal
{
_safeExecutionManagerInteraction(
abi.encodeWithSignature(
"ovmREVERT(bytes)",
Lib_ErrorUtils.encodeRevertString(
_reason
)
)
);
}
/**
* Performs a safe "require".
* @param _condition Boolean condition that must be true or will revert.
* @param _reason String revert reason to pass along with the REVERT.
*/
function safeREQUIRE(
bool _condition,
string memory _reason
)
internal
{
if (!_condition) {
safeREVERT(
_reason
);
}
}
/**
* Performs a safe ovmSLOAD call.
*/
function safeSLOAD(
bytes32 _key
)
internal
returns (
bytes32
)
{
bytes memory returndata = _safeExecutionManagerInteraction(
abi.encodeWithSignature(
"ovmSLOAD(bytes32)",
_key
)
);
return abi.decode(returndata, (bytes32));
}
/**
* Performs a safe ovmSSTORE call.
*/
function safeSSTORE(
bytes32 _key,
bytes32 _value
)
internal
{
_safeExecutionManagerInteraction(
abi.encodeWithSignature(
"ovmSSTORE(bytes32,bytes32)",
_key,
_value
)
);
}
/*********************
* Private Functions *
*********************/
/**
* Performs an ovm interaction and the necessary safety checks.
* @param _gasLimit Gas limit for the interaction.
* @param _calldata Data to send to the OVM_ExecutionManager (encoded with sighash).
* @return _returndata Data sent back by the OVM_ExecutionManager.
*/
function _safeExecutionManagerInteraction(
uint256 _gasLimit,
bytes memory _calldata
)
private
returns (
bytes memory _returndata
)
{
address ovmExecutionManager = msg.sender;
(
bool success,
bytes memory returndata
) = ovmExecutionManager.call{gas: _gasLimit}(_calldata);
if (success == false) {
assembly {
revert(add(returndata, 0x20), mload(returndata))
}
} else if (returndata.length == 1) {
assembly {
return(0, 1)
}
} else {
return returndata;
}
}
function _safeExecutionManagerInteraction(
bytes memory _calldata
)
private
returns (
bytes memory _returndata
)
{
return _safeExecutionManagerInteraction(
gasleft(),
_calldata
);
}
}
| ************************************** Public Functions: Transition Status /* Retrieves the state transitioner for a given root. @param _preStateRoot State root to query a transitioner for. @return _transitioner Corresponding state transitioner contract./ | {
return transitioners[keccak256(abi.encodePacked(_preStateRoot, _txHash))];
}
| 1,439,441 | [
1,
4782,
15486,
30,
16515,
2685,
342,
20507,
326,
919,
6007,
264,
364,
279,
864,
1365,
18,
225,
389,
1484,
1119,
2375,
3287,
1365,
358,
843,
279,
6007,
264,
364,
18,
327,
389,
14936,
264,
9557,
17863,
310,
919,
6007,
264,
6835,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
288,
203,
3639,
327,
6007,
414,
63,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
24899,
1484,
1119,
2375,
16,
389,
978,
2310,
3719,
15533,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0x7835533ce4A469E09F75AfB9E52bE6414581142b/sources/contracts/character.sol | 10% chance of having a second role | function getRole(uint256 tokenId) public view returns (string memory) {
uint256 rand = random(string(abi.encodePacked("ROLE", toString(tokenId))));
uint8 firstRolePosition = uint8(rand % role.length);
if ((rand % 20) > 17) {
uint256 rand2 = random(string(abi.encodePacked("SECONDROLE", toString(tokenId))));
uint8 secondRolePosition = uint8(rand2 % role.length);
if (firstRolePosition != secondRolePosition) {
return string(abi.encodePacked(role[firstRolePosition], " + ", role[secondRolePosition]));
}
}
return role[firstRolePosition];
}
| 1,849,493 | [
1,
2163,
9,
17920,
434,
7999,
279,
2205,
2478,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
225,
445,
15673,
12,
11890,
5034,
1147,
548,
13,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
565,
2254,
5034,
5605,
273,
2744,
12,
1080,
12,
21457,
18,
3015,
4420,
329,
2932,
16256,
3113,
1762,
12,
2316,
548,
3719,
10019,
203,
565,
2254,
28,
1122,
2996,
2555,
273,
2254,
28,
12,
7884,
738,
2478,
18,
2469,
1769,
203,
203,
565,
309,
14015,
7884,
738,
4200,
13,
405,
8043,
13,
288,
203,
1377,
2254,
5034,
5605,
22,
273,
2744,
12,
1080,
12,
21457,
18,
3015,
4420,
329,
2932,
16328,
16256,
3113,
1762,
12,
2316,
548,
3719,
10019,
203,
1377,
2254,
28,
2205,
2996,
2555,
273,
2254,
28,
12,
7884,
22,
738,
2478,
18,
2469,
1769,
203,
1377,
309,
261,
3645,
2996,
2555,
480,
2205,
2996,
2555,
13,
288,
203,
3639,
327,
533,
12,
21457,
18,
3015,
4420,
329,
12,
4615,
63,
3645,
2996,
2555,
6487,
315,
397,
3104,
2478,
63,
8538,
2996,
2555,
5717,
1769,
203,
1377,
289,
203,
565,
289,
203,
203,
565,
327,
2478,
63,
3645,
2996,
2555,
15533,
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
] |
pragma solidity 0.4.24;
import "./TILM.sol";
import "../extensions/Blacklisted.sol";
import "../extensions/NAutoblock.sol";
/**
* @title Whitelist and Admin token
* @dev ILM token modified with whitelist and Admin list functionalities.
**/
contract BATILM is TILM, Blacklisted, NAutoblock {
constructor() public {}
modifier onlyAutoblockers() {
require(msg.sender==owner || isAutoblocker(msg.sender), "Owner or Autoblocker rights required.");
_;
}
function setBlacklistUnlock(bool _newStatus) public onlyAutoblockers {
super.setBlacklistUnlock(_newStatus);
}
/**
* @dev Allows autoblockers to add people to the blacklist.
* @param _toAdd The address to be added to blacklist.
*/
function addToBlacklist(address _toAdd) public onlyAutoblockers {
super.addToBlacklist(_toAdd);
}
function addListToBlacklist(address[] _toAdd) public onlyAutoblockers {
super.addListToBlacklist(_toAdd);
}
function removeFromBlacklist(address _toRemove) public onlyAutoblockers {
super.removeFromBlacklist(_toRemove);
}
function removeListFromBlacklist(address[] _toRemove) public onlyAutoblockers {
super.removeListFromBlacklist(_toRemove);
}
/**
* @dev Allows autoblockers to add people to the autoblocker list.
* @param _toAdd The address to be added to autoblocker list.
*/
function addToAutoblockers(address _toAdd) public onlyAutoblockers {
super.addToAutoblockers(_toAdd);
}
function addListToAutoblockers(address[] _toAdd) public onlyAutoblockers {
super.addListToAutoblockers(_toAdd);
}
function removeFromAutoblockers(address _toRemove) public onlyAutoblockers {
super.removeFromAutoblockers(_toRemove);
}
function removeListFromAutoblockers(address[] _toRemove) public onlyAutoblockers {
super.removeListFromAutoblockers(_toRemove);
}
/**
* @dev Blacklisted can't transfer tokens. If the sender is an autoblocker, the receiver becomes blacklisted
* @param _to The address where tokens will be sent to
* @param _value The amount of tokens to be sent
*/
function transfer(address _to, uint256 _value) public notBlacklisted returns(bool) {
//If the destination is not blacklisted, try to add it (only autoblockers modifier)
if(isAutoblocker(msg.sender) && !isBlacklisted(_to) && !blacklistUnlocked) addToBlacklist(_to);
return super.transfer(_to, _value);
}
/**
* @dev Blacklisted can't transfer tokens. If the sender is an autoblocker, the receiver becomes blacklisted Also, the msg.sender will need to be approved to do it
* @param _from The address where tokens will be sent from
* @param _to The address where tokens will be sent to
* @param _value The amount of tokens to be sent
*/
function transferFrom(address _from, address _to, uint256 _value) public notBlacklisted returns (bool) {
require(!isBlacklisted(_from), "Source is blacklisted");
//If the destination is not blacklisted, try to add it (only autoblockers modifier)
if(isAutoblocker(msg.sender) && !isBlacklisted(_to) && !blacklistUnlocked) addToBlacklist(_to);
return super.transferFrom(_from, _to, _value);
}
/**
* @dev Allow others to spend tokens from the msg.sender address. The spender can't be blacklisted
* @param _spender The address to be approved
* @param _value The amount of tokens to be approved
*/
function approve(address _spender, uint256 _value) public notBlacklisted returns (bool) {
//If the approve spender is not blacklisted, try to add it (only autoblockers modifier)
require(!isBlacklisted(_spender) || blacklistUnlocked, "Cannot allow blacklisted addresses to spend tokens");
return super.approve(_spender, _value);
}
/**
* @dev transfer token to a specified address
* @param _to The address to transfer to.
* @param _amount The amount to be transferred.
* @param _timestamp Unlock timestamp.
*/
function transferLockedFunds(address _to, uint256 _amount, uint256 _timestamp) public notBlacklisted returns (bool){
//If the approve spender is not blacklisted, try to add it (only autoblockers modifier)
if(isAutoblocker(msg.sender) && !isBlacklisted(_to) && !blacklistUnlocked) addToBlacklist(_to);
return super.transferLockedFunds(_to, _amount, _timestamp);
}
/**
* @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 _amount uint256 the amount of tokens to be transferred
* @param _timestamp Unlock timestamp.
*/
function transferLockedFundsFrom(address _from, address _to, uint256 _amount, uint256 _timestamp) public notBlacklisted returns (bool) {
require(!isBlacklisted(_from), "Source is blacklisted");
//If the destination is not blacklisted, try to add it (only autoblockers modifier)
if(isAutoblocker(msg.sender) && !isBlacklisted(_to) && !blacklistUnlocked) addToBlacklist(_to);
return super.transferLockedFundsFrom(_from, _to, _amount, _timestamp);
}
/**
* @dev transfer token to a specified address
* @param _to The address to transfer to.
* @param _amounts The amounts to be transferred.
* @param _timestamps Unlock timestamps.
*/
function transferListOfLockedFunds(address _to, uint256[] _amounts, uint256[] _timestamps) public notBlacklisted returns (bool) {
//If the approve spender is not blacklisted, try to add it (only autoblockers modifier)
if(isAutoblocker(msg.sender) && !isBlacklisted(_to) && !blacklistUnlocked) addToBlacklist(_to);
return super.transferListOfLockedFunds(_to, _amounts, _timestamps);
}
/**
* @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 _amounts uint256 the amount of tokens to be transferred
* @param _timestamps Unlock timestamps.
*/
function transferListOfLockedFundsFrom(address _from, address _to, uint256[] _amounts, uint256[] _timestamps) public notBlacklisted returns (bool) {
require(!isBlacklisted(_from), "Source is blacklisted");
//If the destination is not blacklisted, try to add it (only autoblockers modifier)
if(isAutoblocker(msg.sender) && !isBlacklisted(_to) && !blacklistUnlocked) addToBlacklist(_to);
return super.transferListOfLockedFundsFrom(_from, _to, _amounts, _timestamps);
}
}
| * @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 _amounts uint256 the amount of tokens to be transferred @param _timestamps Unlock timestamps./If the destination is not blacklisted, try to add it (only autoblockers modifier) | function transferListOfLockedFundsFrom(address _from, address _to, uint256[] _amounts, uint256[] _timestamps) public notBlacklisted returns (bool) {
require(!isBlacklisted(_from), "Source is blacklisted");
if(isAutoblocker(msg.sender) && !isBlacklisted(_to) && !blacklistUnlocked) addToBlacklist(_to);
return super.transferListOfLockedFundsFrom(_from, _to, _amounts, _timestamps);
}
| 12,876,620 | [
1,
5912,
2430,
628,
1245,
1758,
358,
4042,
225,
389,
2080,
1758,
1021,
1758,
1492,
1846,
2545,
358,
1366,
2430,
628,
225,
389,
869,
1758,
1021,
1758,
1492,
1846,
2545,
358,
7412,
358,
225,
389,
8949,
87,
2254,
5034,
326,
3844,
434,
2430,
358,
506,
906,
4193,
225,
389,
25459,
3967,
11267,
18,
19,
2047,
326,
2929,
353,
486,
25350,
16,
775,
358,
527,
518,
261,
3700,
2059,
947,
739,
414,
9606,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
7412,
682,
951,
8966,
42,
19156,
1265,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
5034,
8526,
389,
8949,
87,
16,
2254,
5034,
8526,
389,
25459,
13,
1071,
486,
13155,
18647,
1135,
261,
6430,
13,
288,
203,
1377,
2583,
12,
5,
291,
13155,
18647,
24899,
2080,
3631,
315,
1830,
353,
25350,
8863,
203,
1377,
309,
12,
291,
7150,
947,
739,
264,
12,
3576,
18,
15330,
13,
597,
401,
291,
13155,
18647,
24899,
869,
13,
597,
401,
22491,
7087,
329,
13,
9604,
25811,
24899,
869,
1769,
203,
1377,
327,
2240,
18,
13866,
682,
951,
8966,
42,
19156,
1265,
24899,
2080,
16,
389,
869,
16,
389,
8949,
87,
16,
389,
25459,
1769,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/4/0xe55FDf1fc08771524Ff148B09E7B7323939248Fc/sources/browser/ALWN.sol | * @dev - return address of user @param - _userId - unique number of user in array/ | function getUser(uint256 _userId) public view returns(address) {
return users[_userId];
}
| 652,230 | [
1,
17,
327,
1758,
434,
729,
225,
300,
389,
18991,
300,
3089,
1300,
434,
729,
316,
526,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4735,
12,
11890,
5034,
389,
18991,
13,
1071,
1476,
1135,
12,
2867,
13,
288,
203,
3639,
327,
3677,
63,
67,
18991,
15533,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import {ERC721Full} from "../../.openzeppelin/0.8/token/ERC721/ERC721Full.sol";
import {Counters} from "../../.openzeppelin/0.8/drafts/Counters.sol";
import {IERC721} from "../../.openzeppelin/0.8/token/ERC721/IERC721.sol";
import {Address} from "../../.openzeppelin/0.8/utils/Address.sol";
import {Bytes32} from "../../lib/Bytes32.sol";
import {Adminable} from "../../lib/Adminable.sol";
import {Initializable} from "../../lib/Initializable.sol";
import {DefiPassportStorage} from "./DefiPassportStorage.sol";
import {ISapphirePassportScores} from "../../sapphire/ISapphirePassportScores.sol";
import {SapphireTypes} from "../../sapphire/SapphireTypes.sol";
contract DefiPassport is ERC721Full, Adminable, DefiPassportStorage, Initializable {
/* ========== Libraries ========== */
using Counters for Counters.Counter;
using Address for address;
using Bytes32 for bytes32;
/* ========== Events ========== */
event BaseURISet(string _baseURI);
event ApprovedSkinStatusChanged(
address _skin,
uint256 _skinTokenId,
bool _status
);
event ApprovedSkinsStatusesChanged(
SkinAndTokenIdStatusRecord[] _skinsRecords
);
event DefaultSkinStatusChanged(
address _skin,
bool _status
);
event DefaultActiveSkinChanged(
address _skin,
uint256 _skinTokenId
);
event ActiveSkinSet(
uint256 _tokenId,
SkinRecord _skinRecord
);
event SkinManagerSet(address _skinManager);
event WhitelistSkinSet(address _skin, bool _status);
/* ========== Public variables ========== */
string public override baseURI;
/**
* @dev Deprecated. Including this because this is a proxy implementation.
*/
bytes32 private _proofProtocol;
/* ========== Modifier ========== */
modifier onlySkinManager () {
require(
msg.sender == skinManager,
"DefiPassport: caller is not skin manager"
);
_;
}
/* ========== Restricted Functions ========== */
function init(
string calldata name_,
string calldata symbol_,
address _skinManager
)
external
onlyAdmin
initializer
{
_name = name_;
_symbol = symbol_;
skinManager = _skinManager;
}
/**
* @dev Sets the base URI that is appended as a prefix to the
* token URI.
*/
function setBaseURI(
string calldata _baseURI
)
external
onlyAdmin
{
baseURI = _baseURI;
emit BaseURISet(_baseURI);
}
/**
* @dev Sets the address of the skin manager role
*
* @param _skinManager The new skin manager
*/
function setSkinManager(
address _skinManager
)
external
onlyAdmin
{
require (
_skinManager != skinManager,
"DefiPassport: the same skin manager is already set"
);
skinManager = _skinManager;
emit SkinManagerSet(skinManager);
}
/**
* @notice Registers/unregisters a default skin
*
* @param _skin Address of the skin NFT
* @param _status Wether or not it should be considered as a default
* skin or not
*/
function setDefaultSkin(
address _skin,
bool _status
)
external
onlySkinManager
{
if (!_status) {
require(
defaultActiveSkin.skin != _skin,
"Defi Passport: cannot unregister the default active skin"
);
}
require(
defaultSkins[_skin] != _status,
"DefiPassport: skin already has the same status"
);
require(
_skin.isContract(),
"DefiPassport: the given skin is not a contract"
);
require (
IERC721(_skin).ownerOf(1) != address(0),
"DefiPassport: default skin must at least have tokenId eq 1"
);
if (defaultActiveSkin.skin == address(0)) {
defaultActiveSkin = SkinRecord(address(0), _skin, 1);
}
defaultSkins[_skin] = _status;
emit DefaultSkinStatusChanged(_skin, _status);
}
/**
* @dev Set the default active skin, which will be used instead of
* unavailable user's active one
* @notice Skin should be used as default one (with setDefaultSkin function)
*
* @param _skin Address of the skin NFT
* @param _skinTokenId The NFT token ID
*/
function setDefaultActiveSkin(
address _skin,
uint256 _skinTokenId
)
external
onlySkinManager
{
require(
defaultSkins[_skin],
"DefiPassport: the given skin is not registered as a default"
);
require(
defaultActiveSkin.skin != _skin ||
defaultActiveSkin.skinTokenId != _skinTokenId,
"DefiPassport: the skin is already set as default active"
);
defaultActiveSkin = SkinRecord(address(0), _skin, _skinTokenId);
emit DefaultActiveSkinChanged(_skin, _skinTokenId);
}
/**
* @notice Approves a passport skin.
* Only callable by the skin manager
*/
function setApprovedSkin(
address _skin,
uint256 _skinTokenId,
bool _status
)
external
onlySkinManager
{
approvedSkins[_skin][_skinTokenId] = _status;
emit ApprovedSkinStatusChanged(_skin, _skinTokenId, _status);
}
/**
* @notice Sets the approved status for all skin contracts and their
* token IDs passed into this function.
*/
function setApprovedSkins(
SkinAndTokenIdStatusRecord[] memory _skinsToApprove
)
public
onlySkinManager
{
for (uint256 i = 0; i < _skinsToApprove.length; i++) {
TokenIdStatus[] memory tokensAndStatuses = _skinsToApprove[i].skinTokenIdStatuses;
for (uint256 j = 0; j < tokensAndStatuses.length; j ++) {
TokenIdStatus memory tokenStatusPair = tokensAndStatuses[j];
approvedSkins[_skinsToApprove[i].skin][tokenStatusPair.tokenId] = tokenStatusPair.status;
}
}
emit ApprovedSkinsStatusesChanged(_skinsToApprove);
}
/**
* @notice Adds or removes a skin contract to the whitelist.
* The Defi Passport considers all skins minted by whitelisted contracts
* to be valid skins for applying them on to the passport.
* The user applying the skins must still be their owner though.
*/
function setWhitelistedSkin(
address _skinContract,
bool _status
)
external
onlySkinManager
{
require (
_skinContract.isContract(),
"DefiPassport: address is not a contract"
);
require (
whitelistedSkins[_skinContract] != _status,
"DefiPassport: the skin already has the same whitelist status"
);
whitelistedSkins[_skinContract] = _status;
emit WhitelistSkinSet(_skinContract, _status);
}
/* ========== Public Functions ========== */
/**
* @notice Mints a DeFi passport to the address specified by `_to`. Note:
* - The `_passportSkin` must be an approved or default skin.
* - The token URI will be composed by <baseURI> + `_to`,
* without the "0x" in front
*
* @param _to The receiver of the defi passport
* @param _passportSkin The address of the skin NFT to be applied to the passport
* @param _skinTokenId The ID of the passport skin NFT, owned by the receiver
*/
function mint(
address _to,
address _passportSkin,
uint256 _skinTokenId
)
external
returns (uint256)
{
require (
isSkinAvailable(_to, _passportSkin, _skinTokenId),
"DefiPassport: invalid skin"
);
// A user cannot have two passports
require(
balanceOf(_to) == 0,
"DefiPassport: user already has a defi passport"
);
_tokenIds.increment();
uint256 newTokenId = _tokenIds.current();
_mint(_to, newTokenId);
_setActiveSkin(newTokenId, SkinRecord(_to, _passportSkin, _skinTokenId));
return newTokenId;
}
/**
* @notice Changes the passport skin of the caller's passport
*
* @param _skin The contract address to the skin NFT
* @param _skinTokenId The ID of the skin NFT
*/
function setActiveSkin(
address _skin,
uint256 _skinTokenId
)
external
{
require(
balanceOf(msg.sender) > 0,
"DefiPassport: caller has no passport"
);
require(
isSkinAvailable(msg.sender, _skin, _skinTokenId),
"DefiPassport: invalid skin"
);
uint256 tokenId = tokenOfOwnerByIndex(msg.sender, 0);
_setActiveSkin(tokenId, SkinRecord(msg.sender, _skin, _skinTokenId));
}
function approve(
address,
uint256
)
public
pure
override
{
revert("DefiPassport: defi passports are not transferrable");
}
function setApprovalForAll(
address,
bool
)
public
pure
override
{
revert("DefiPassport: defi passports are not transferrable");
}
function safeTransferFrom(
address,
address,
uint256
)
public
pure
override
{
revert("DefiPassport: defi passports are not transferrable");
}
function safeTransferFrom(
address,
address,
uint256,
bytes memory
)
public
pure
override
{
revert("DefiPassport: defi passports are not transferrable");
}
function transferFrom(
address,
address,
uint256
)
public
pure
override
{
revert("DefiPassport: defi passports are not transferrable");
}
/* ========== Public View Functions ========== */
function name()
external
override
view
returns (string memory)
{
return _name;
}
function symbol()
external
override
view
returns (string memory)
{
return _symbol;
}
/**
* @notice Returns whether a certain skin can be applied to the specified
* user's passport.
*
* @param _user The user for whom to check
* @param _skinContract The address of the skin NFT
* @param _skinTokenId The NFT token ID
*/
function isSkinAvailable(
address _user,
address _skinContract,
uint256 _skinTokenId
)
public
view
returns (bool)
{
if (defaultSkins[_skinContract]) {
return IERC721(_skinContract).ownerOf(_skinTokenId) != address(0);
} else if (
whitelistedSkins[_skinContract] ||
approvedSkins[_skinContract][_skinTokenId]
) {
return _isSkinOwner(_user, _skinContract, _skinTokenId);
}
return false;
}
/**
* @notice Returns the active skin of the given passport ID
*
* @param _tokenId Passport ID
*/
function getActiveSkin(
uint256 _tokenId
)
public
view
returns (SkinRecord memory)
{
SkinRecord memory _activeSkin = _activeSkins[_tokenId];
if (isSkinAvailable(_activeSkin.owner, _activeSkin.skin, _activeSkin.skinTokenId)) {
return _activeSkin;
} else {
return defaultActiveSkin;
}
}
/**
* @dev Returns the URI for a given token ID. May return an empty string.
*
* Reverts if the token ID does not exist.
*/
function tokenURI(
uint256 tokenId
)
public
view
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
address owner = ownerOf(tokenId);
return string(abi.encodePacked(baseURI, "0x", _toAsciiString(owner)));
}
/* ========== Private Functions ========== */
/**
* @dev Converts the given address to string. Used when minting new
* passports.
*/
function _toAsciiString(
address _address
)
private
pure
returns (string memory)
{
bytes memory s = new bytes(40);
for (uint i = 0; i < 20; i++) {
bytes1 b = bytes1(uint8(uint(uint160(_address)) / (2**(8*(19 - i)))));
bytes1 hi = bytes1(uint8(b) / 16);
bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi));
s[2*i] = _char(hi);
s[2*i+1] = _char(lo);
}
return string(s);
}
function _char(
bytes1 b
)
private
pure
returns (bytes1 c)
{
if (uint8(b) < 10) return bytes1(uint8(b) + 0x30);
else return bytes1(uint8(b) + 0x57);
}
/**
* @dev Ensures that the user is the owner of the skin NFT
*/
function _isSkinOwner(
address _user,
address _skin,
uint256 _tokenId
)
internal
view
returns (bool)
{
/**
* It is not sure if the skin contract implements the ERC721 or ERC1155 standard,
* so we must do the check.
*/
bytes memory payload = abi.encodeWithSignature("ownerOf(uint256)", _tokenId);
(bool success, bytes memory returnData) = _skin.staticcall(payload);
if (success) {
(address owner) = abi.decode(returnData, (address));
return owner == _user;
} else {
// The skin contract might be an ERC1155 (like OpenSea)
payload = abi.encodeWithSignature("balanceOf(address,uint256)", _user, _tokenId);
(success, returnData) = _skin.staticcall(payload);
if (success) {
(uint256 balance) = abi.decode(returnData, (uint256));
return balance > 0;
}
}
return false;
}
function _setActiveSkin(
uint256 _tokenId,
SkinRecord memory _skinRecord
)
private
{
SkinRecord memory currentSkin = _activeSkins[_tokenId];
require(
currentSkin.skin != _skinRecord.skin ||
currentSkin.skinTokenId != _skinRecord.skinTokenId,
"DefiPassport: the same skin is already active"
);
_activeSkins[_tokenId] = _skinRecord;
emit ActiveSkinSet(_tokenId, _skinRecord);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC721.sol";
import "./ERC721Enumerable.sol";
import "./ERC721Metadata.sol";
/**
* @title Full ERC721 Token
* @dev This implementation includes all the required and some optional functionality of the ERC721 standard
* Moreover, it includes approve all functionality using operator terminology.
*
* See https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata {
function _transferFrom(
address from,
address to,
uint256 tokenId
)
internal
override(ERC721, ERC721Enumerable)
{
ERC721Enumerable._transferFrom(from, to, tokenId);
}
function _mint(
address to,
uint256 tokenId
)
internal
override(ERC721, ERC721Enumerable)
{
ERC721Enumerable._mint(to, tokenId);
}
function _burn(
address owner,
uint256 tokenId
)
internal
override(ERC721, ERC721Enumerable, ERC721Metadata)
{
// Burn implementation of Metadata
ERC721._burn(owner, tokenId);
ERC721Metadata._burn(owner, tokenId);
ERC721Enumerable._burn(owner, tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of NFTs in `owner`'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the NFT specified by `tokenId`.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
*
*
* Requirements:
* - `from`, `to` cannot be zero.
* - `tokenId` must be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this
* NFT by either {approve} or {setApprovalForAll}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
* Requirements:
* - If the caller is not `from`, it must be approved to move this NFT by
* either {approve} or {setApprovalForAll}.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) external;
}
// 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) {
// 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].
*
* _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-low-level-calls
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
library Bytes32 {
function toString(
bytes32 _bytes
)
internal
pure
returns (string memory)
{
uint8 i = 0;
while (i < 32 && _bytes[i] != 0) {
i++;
}
bytes memory bytesArray = new bytes(i);
for (i = 0; i < 32 && _bytes[i] != 0; i++) {
bytesArray[i] = _bytes[i];
}
return string(bytesArray);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import { Storage } from "./Storage.sol";
/**
* @title Adminable
* @author dYdX
*
* @dev EIP-1967 Proxy Admin contract.
*/
contract Adminable {
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
bytes32 internal constant ADMIN_SLOT =
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Modifier to check whether the `msg.sender` is the admin.
* If it is, it will run the function. Otherwise, it will revert.
*/
modifier onlyAdmin() {
require(
msg.sender == getAdmin(),
"Adminable: caller is not admin"
);
_;
}
/**
* @return The EIP-1967 proxy admin
*/
function getAdmin()
public
view
returns (address)
{
return address(uint160(uint256(Storage.load(ADMIN_SLOT))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
/**
* @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.
*
* Taken from OpenZeppelin
*/
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.4;
import {Counters} from "../../.openzeppelin/0.8/drafts/Counters.sol";
import {ISapphirePassportScores} from "../../sapphire/ISapphirePassportScores.sol";
contract DefiPassportStorage {
/* ========== Structs ========== */
struct SkinRecord {
address owner;
address skin;
uint256 skinTokenId;
}
struct TokenIdStatus {
uint256 tokenId;
bool status;
}
struct SkinAndTokenIdStatusRecord {
address skin;
TokenIdStatus[] skinTokenIdStatuses;
}
// Made these internal because the getters override these variables (because this is an upgrade)
string internal _name;
string internal _symbol;
/**
* @notice The credit score contract used by the passport
*/
ISapphirePassportScores private passportScoresContract;
/* ========== Public Variables ========== */
/**
* @notice Records the whitelisted skins. All tokens minted by these contracts
* will be considered valid to apply on the passport, given they are
* owned by the caller.
*/
mapping (address => bool) public whitelistedSkins;
/**
* @notice Records the approved skins of the passport
*/
mapping (address => mapping (uint256 => bool)) public approvedSkins;
/**
* @notice Records the default skins
*/
mapping (address => bool) public defaultSkins;
/**
* @notice Records the default skins
*/
SkinRecord public defaultActiveSkin;
/**
* @notice The skin manager appointed by the admin, who can
* approve and revoke passport skins
*/
address public skinManager;
/* ========== Internal Variables ========== */
/**
* @notice Maps a passport (tokenId) to its active skin NFT
*/
mapping (uint256 => SkinRecord) internal _activeSkins;
Counters.Counter internal _tokenIds;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import {SapphireTypes} from "./SapphireTypes.sol";
interface ISapphirePassportScores {
function updateMerkleRoot(bytes32 newRoot) external;
function setMerkleRootUpdater(address merkleRootUpdater) external;
/**
* Reverts if proof is invalid
*/
function verify(SapphireTypes.ScoreProof calldata proof) external view returns(bool);
function setMerkleRootDelay(uint256 delay) external;
function setPause(bool status) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
library SapphireTypes {
struct ScoreProof {
address account;
bytes32 protocol;
uint256 score;
bytes32[] merkleProof;
}
struct Vault {
uint256 collateralAmount;
uint256 borrowedAmount;
}
struct RootInfo {
bytes32 merkleRoot;
uint256 timestamp;
}
enum Operation {
Deposit,
Withdraw,
Borrow,
Repay,
Liquidate
}
struct Action {
uint256 amount;
Operation operation;
address userToLiquidate;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../GSN/Context.sol";
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
import "../../drafts/Counters.sol";
import "../../introspection/ERC165.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping (uint256 => address) private _tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => Counters.Counter) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/**
* @dev Gets the balance of the specified address.
* @param owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address owner) public override view returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _ownedTokensCount[owner].current();
}
/**
* @dev Gets the owner of the specified token ID.
* @param tokenId uint256 ID of the token to query the owner of
* @return address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 tokenId) public override view returns (address) {
address owner = _tokenOwner[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) public override virtual {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) public override view returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[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) public override virtual {
require(to != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][to] = approved;
emit ApprovalForAll(_msgSender(), to, approved);
}
/**
* @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 override view returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address.
* Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
* Requires the msg.sender to be the owner, approved, or operator.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address from, address to, uint256 tokenId) public override virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transferFrom(from, to, tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public override virtual {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the _msgSender() to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public override virtual {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransferFrom(from, to, tokenId, _data);
}
/**
* @dev 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.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal {
_transferFrom(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether the specified token exists.
* @param tokenId uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
/**
* @dev Returns whether the given spender can transfer a given token ID.
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* 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.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _safeMint(address to, uint256 tokenId) internal {
_safeMint(to, tokenId, "");
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* 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.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
* @param _data bytes data to send along with a safe transfer check
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
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");
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].increment();
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {_burn} instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal virtual {
require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own");
_clearApproval(tokenId);
_ownedTokensCount[owner].decrement();
_tokenOwner[tokenId] = address(0);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* @param tokenId uint256 ID of the token being burned
*/
function _burn(uint256 tokenId) internal {
_burn(ownerOf(tokenId), tokenId);
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transferFrom(address from, address to, uint256 tokenId) internal virtual {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_clearApproval(tokenId);
_ownedTokensCount[from].decrement();
_ownedTokensCount[to].increment();
_tokenOwner[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* This is an internal detail of the `ERC721` contract and its use is deprecated.
* @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)
internal returns (bool)
{
if (!to.isContract()) {
return true;
}
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = to.call(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
));
if (!success) {
if (returndata.length > 0) {
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert("ERC721: transfer to non ERC721Receiver implementer");
}
} else {
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
}
/**
* @dev Private function to clear current approval of a given token ID.
* @param tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(uint256 tokenId) private {
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../GSN/Context.sol";
import "./IERC721Enumerable.sol";
import "./ERC721.sol";
import "../../introspection/ERC165.sol";
/**
* @title ERC-721 Non-Fungible Token with optional enumeration extension logic
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// 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;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner.
* @param owner address owning the tokens list to be accessed
* @param index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public override view returns (uint256) {
require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev Gets the total amount of tokens stored by the contract.
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public override view returns (uint256) {
return _allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens.
* @param index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 index) public override view returns (uint256) {
require(index < totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to transferFrom, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transferFrom(address from, address to, uint256 tokenId) internal override virtual {
super._transferFrom(from, to, tokenId);
_removeTokenFromOwnerEnumeration(from, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to address the beneficiary that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, uint256 tokenId) internal override virtual {
super._mint(to, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
_addTokenToAllTokensEnumeration(tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {ERC721-_burn} instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal override virtual {
_removeTokenFromOwnerEnumeration(owner, tokenId);
// Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund
_ownedTokensIndex[tokenId] = 0;
_removeTokenFromAllTokensEnumeration(tokenId);
}
/**
* @dev Gets the list of token IDs of the requested owner.
* @param owner address owning the tokens
* @return uint256[] List of token IDs owned by the requested address
*/
function _tokensOfOwner(address owner) internal view returns (uint256[] storage) {
return _ownedTokens[owner];
}
/**
* @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 {
_ownedTokensIndex[tokenId] = _ownedTokens[to].length;
_ownedTokens[to].push(tokenId);
}
/**
* @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 = _ownedTokens[from].length - 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
_ownedTokens[from].pop();
// Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by
// lastTokenId, or just over the end of the array if the token was the last one).
}
/**
* @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
_allTokens.pop();
_allTokensIndex[tokenId] = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../GSN/Context.sol";
import "./ERC721.sol";
import "./IERC721Metadata.sol";
import "../../introspection/ERC165.sol";
contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Base URI
string private _baseURI;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/**
* @dev Gets the token name.
* @return string representing the token name
*/
function name() external override virtual view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/
function symbol() external override virtual view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the URI for a given token ID. May return an empty string.
*
* If the token's URI is non-empty and a base URI was set (via
* {_setBaseURI}), it will be added to the token ID's URI as a prefix.
*
* Reverts if the token ID does not exist.
*/
function tokenURI(uint256 tokenId) external override virtual view returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
// Even if there is a base URI, it is only appended to non-empty token-specific URIs
if (bytes(_tokenURI).length == 0) {
return "";
} else {
// abi.encodePacked is being used to concatenate strings
return string(abi.encodePacked(_baseURI, _tokenURI));
}
}
/**
* @dev Internal function to set the token URI for a given token.
*
* Reverts if the token ID does not exist.
*
* TIP: if all token IDs share a prefix (e.g. if your URIs look like
* `http://api.myproject.com/token/<id>`), use {_setBaseURI} to store
* it and save gas.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI}.
*
* _Available since v2.5.0._
*/
function _setBaseURI(string memory baseURI_) internal {
_baseURI = baseURI_;
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a preffix in {tokenURI} to each token's URI, when
* they are non-empty.
*
* _Available since v2.5.0._
*/
function baseURI() external virtual view returns (string memory) {
return _baseURI;
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use _burn(uint256) instead.
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address, uint256 tokenId) internal override virtual {
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// 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 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 returns (address) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// 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 {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a {IERC721-safeTransferFrom}. 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 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data)
external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external override view returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// 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 "./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 {
function totalSupply() external view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
library Storage {
/**
* @dev Performs an SLOAD and returns the data in the slot.
*/
function load(
bytes32 slot
)
internal
view
returns (bytes32)
{
bytes32 result;
/* solhint-disable-next-line no-inline-assembly */
assembly {
result := sload(slot)
}
return result;
}
/**
* @dev Performs an SSTORE to save the value to the slot.
*/
function store(
bytes32 slot,
bytes32 value
)
internal
{
/* solhint-disable-next-line no-inline-assembly */
assembly {
sstore(slot, value)
}
}
} | * @dev Approves another address to transfer the given token ID The zero address indicates there is no approved address. There can only be one approved address per token at a given time. Can only be called by the token owner or an approved operator. @param to address to be approved for the given token ID @param tokenId uint256 ID of the token to be approved/ | function approve(address to, uint256 tokenId) public override virtual {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
| 11,896,619 | [
1,
12053,
3324,
4042,
1758,
358,
7412,
326,
864,
1147,
1599,
1021,
3634,
1758,
8527,
1915,
353,
1158,
20412,
1758,
18,
6149,
848,
1338,
506,
1245,
20412,
1758,
1534,
1147,
622,
279,
864,
813,
18,
4480,
1338,
506,
2566,
635,
326,
1147,
3410,
578,
392,
20412,
3726,
18,
225,
358,
1758,
358,
506,
20412,
364,
326,
864,
1147,
1599,
225,
1147,
548,
2254,
5034,
1599,
434,
326,
1147,
358,
506,
20412,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
6617,
537,
12,
2867,
358,
16,
2254,
5034,
1147,
548,
13,
1071,
3849,
5024,
288,
203,
3639,
1758,
3410,
273,
3410,
951,
12,
2316,
548,
1769,
203,
3639,
2583,
12,
869,
480,
3410,
16,
315,
654,
39,
27,
5340,
30,
23556,
358,
783,
3410,
8863,
203,
203,
3639,
2583,
24899,
3576,
12021,
1435,
422,
3410,
747,
353,
31639,
1290,
1595,
12,
8443,
16,
389,
3576,
12021,
1435,
3631,
203,
5411,
315,
654,
39,
27,
5340,
30,
6617,
537,
4894,
353,
486,
3410,
12517,
20412,
364,
777,
6,
203,
3639,
11272,
203,
203,
3639,
389,
2316,
12053,
4524,
63,
2316,
548,
65,
273,
358,
31,
203,
3639,
3626,
1716,
685,
1125,
12,
8443,
16,
358,
16,
1147,
548,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@rarible/lib-broken-line/contracts/LibBrokenLine.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
contract StakingBase is OwnableUpgradeable {
using SafeMathUpgradeable for uint;
using LibBrokenLine for LibBrokenLine.BrokenLine;
uint256 constant WEEK = 604800; //seconds one week
uint256 constant STARTING_POINT_WEEK = 2676; //starting point week (Staking Epoch start)
uint256 constant TWO_YEAR_WEEKS = 104; //two year weeks
uint256 constant ST_FORMULA_MULTIPLIER = 10816; //stFormula multiplier = TWO_YEAR_WEEKS^2
uint256 constant ST_FORMULA_DIVIDER = 1000; //stFormula divider
uint256 constant ST_FORMULA_COMPENSATE = 11356800; //stFormula compensate = (0.7 + 0.35) * ST_FORMULA_MULTIPLIER * 1000
uint256 constant ST_FORMULA_SLOPE_MULTIPLIER = 4650; //stFormula slope multiplier = 9.3 * 0.5 * 1000
uint256 constant ST_FORMULA_CLIFF_MULTIPLIER = 9300; //stFormula cliff multiplier = 9.3 * 1000
/**
* @dev ERC20 token to lock
*/
IERC20Upgradeable public token;
/**
* @dev counter for Stake identifiers
*/
uint public counter;
/**
* @dev true if contract entered stopped state
*/
bool public stopped;
/**
* @dev address to migrate Stakes to (zero if not in migration state)
*/
address public migrateTo;
/**
* @dev represents one user Stake
*/
struct Stake {
address account;
address delegate;
}
/**
* @dev describes state of accounts's balance.
* balance - broken line describes stake
* locked - broken line describes how many tokens are locked
* amount - total currently locked tokens (including tokens which can be withdrawed)
*/
struct Account {
LibBrokenLine.BrokenLine balance;
LibBrokenLine.BrokenLine locked;
uint amount;
}
mapping(address => Account) accounts;
mapping(uint => Stake) stakes;
LibBrokenLine.BrokenLine public totalSupplyLine;
/**
* @dev Emitted when create Lock with parameters (account, delegate, amount, slope, cliff)
*/
event StakeCreate(uint indexed id, address indexed account, address indexed delegate, uint time, uint amount, uint slope, uint cliff);
/**
* @dev Emitted when change Lock parameters (newDelegate, newAmount, newSlope, newCliff) for Lock with given id
*/
event Restake(uint indexed id, address indexed account, address indexed delegate, uint counter, uint time, uint amount, uint slope, uint cliff);
/**
* @dev Emitted when to set newDelegate address for Lock with given id
*/
event Delegate(uint indexed id, address indexed account, address indexed delegate, uint time);
/**
* @dev Emitted when withdraw amount of Rari, account - msg.sender, amount - amount Rari
*/
event Withdraw(address indexed account, uint amount);
/**
* @dev Emitted when migrate Locks with given id, account - msg.sender
*/
event Migrate(address indexed account, uint[] id);
/**
* @dev Stop run contract functions, accept withdraw, account - msg.sender
*/
event StopStaking(address indexed account);
/**
* @dev StartMigration initiate migration to another contract, account - msg.sender, to - address delegate to
*/
event StartMigration(address indexed account, address indexed to);
function __StakingBase_init_unchained(IERC20Upgradeable _token) internal initializer {
token = _token;
}
function addLines(address account, address delegate, uint amount, uint slope, uint cliff, uint time) internal {
updateLines(account, delegate, time);
(uint stAmount, uint stSlope) = getStake(amount, slope, cliff);
LibBrokenLine.Line memory line = LibBrokenLine.Line(time, stAmount, stSlope);
totalSupplyLine.add(counter, line, cliff);
accounts[delegate].balance.add(counter, line, cliff);
line = LibBrokenLine.Line(time, amount, slope);
accounts[account].locked.add(counter, line, cliff);
stakes[counter].account = account;
stakes[counter].delegate = delegate;
}
function updateLines(address account, address delegate, uint time) internal {
totalSupplyLine.update(time);
accounts[delegate].balance.update(time);
accounts[account].locked.update(time);
}
/**
* Сalculate and return (newAmount, newSlope), using formula:
* k = (ST_FORMULA_COMPENSATE + ST_FORMULA_CLIFF_MULTIPLIER * (cliffPeriod)^2 + ST_FORMULA_SLOPE_MULTIPLIER * (slopePeriod)^2) / ST_FORMULA_MULTIPLIER
* newAmount = k * amount / ST_FORMULA_DIVIDER
* newSlope = newAmount / slopePeriod
**/
function getStake(uint amount, uint slope, uint cliff) public pure returns (uint stakeAmount, uint stakeSlope) {
uint cliffSide = cliff.mul(cliff).mul(ST_FORMULA_CLIFF_MULTIPLIER);
uint slopePeriod = divUp(amount, slope);
uint slopeSide = slopePeriod.mul(slopePeriod).mul(ST_FORMULA_SLOPE_MULTIPLIER);
uint multiplier = cliffSide.add(slopeSide).add(ST_FORMULA_COMPENSATE).div(ST_FORMULA_MULTIPLIER);
stakeAmount = amount.mul(multiplier).div(ST_FORMULA_DIVIDER);
stakeSlope = divUp(stakeAmount, slopePeriod);
}
function divUp(uint a, uint b) internal pure returns (uint) {
return ((a.sub(1)).div(b)).add(1);
}
function roundTimestamp(uint ts) pure internal returns (uint) {
return ts.div(WEEK).sub(STARTING_POINT_WEEK);
}
function verifyStakeOwner(uint id) internal view returns (address account) {
account = stakes[id].account;
require(account == msg.sender, "caller not a stake owner");
}
/**
* @dev Throws if stopped
*/
modifier notStopped() {
require(!stopped, "stopped");
_;
}
modifier notMigrating() {
require(migrateTo == address(0), "migrating");
_;
}
uint256[50] private __gap;
}
| * @dev StartMigration initiate migration to another contract, account - msg.sender, to - address delegate to/ | event StartMigration(address indexed account, address indexed to);
| 12,570,416 | [
1,
1685,
10224,
18711,
6333,
358,
4042,
6835,
16,
2236,
300,
1234,
18,
15330,
16,
358,
300,
1758,
7152,
358,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
871,
3603,
10224,
12,
2867,
8808,
2236,
16,
1758,
8808,
358,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/4/0xacfD1f6002938B156Aa186827985742Da4FA0ca2/sources/Rookie_v6.sol | set the staking status to true | hasStaked[staker] = true;
| 8,517,767 | [
1,
542,
326,
384,
6159,
1267,
358,
638,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
711,
510,
9477,
63,
334,
6388,
65,
273,
638,
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/3/0xc09b8c84d6785f4D5f973D0C0D7085D98d1aeB38/sources/contracts/SwapCalc.sol | exact out amount and get in amount it's technically possible to not receive the full output amount, so if no price limit has been specified, require this possibility away | function exactOutputInternal(address tokenIn, address tokenOut, uint24 fee, uint256 amountOut, uint160 sqrtPriceLimitX96) private view returns (uint256 amountIn, uint256 amountExactOut) {
IUniswapV3Pool pool = IUniswapV3Pool(getPool(tokenOut, tokenIn, fee));
bool zeroForOne = tokenIn < tokenOut;
(int256 amount0Delta, int256 amount1Delta) = swap(
pool,
zeroForOne,
int256(amountOut),
sqrtPriceLimitX96 == 0 ? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1) : sqrtPriceLimitX96);
uint256 amountOutReceived;
(amountIn, amountOutReceived) = zeroForOne
? (uint256(amount0Delta), uint256(-amount1Delta))
: (uint256(amount1Delta), uint256(-amount0Delta));
if (sqrtPriceLimitX96 == 0) require(amountOutReceived == amountOut);
amountExactOut = amountOutReceived;
}
| 8,177,841 | [
1,
17165,
596,
3844,
471,
336,
316,
3844,
518,
1807,
17734,
6478,
3323,
358,
486,
6798,
326,
1983,
876,
3844,
16,
1427,
309,
1158,
6205,
1800,
711,
2118,
1269,
16,
2583,
333,
25547,
10804,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
5565,
1447,
3061,
12,
2867,
1147,
382,
16,
1758,
1147,
1182,
16,
2254,
3247,
14036,
16,
2254,
5034,
3844,
1182,
16,
2254,
16874,
5700,
5147,
3039,
60,
10525,
13,
3238,
1476,
1135,
261,
11890,
5034,
3844,
382,
16,
2254,
5034,
3844,
14332,
1182,
13,
288,
203,
3639,
467,
984,
291,
91,
438,
58,
23,
2864,
2845,
273,
467,
984,
291,
91,
438,
58,
23,
2864,
12,
588,
2864,
12,
2316,
1182,
16,
1147,
382,
16,
14036,
10019,
203,
3639,
1426,
3634,
1290,
3335,
273,
1147,
382,
411,
1147,
1182,
31,
203,
3639,
261,
474,
5034,
3844,
20,
9242,
16,
509,
5034,
3844,
21,
9242,
13,
273,
7720,
12,
203,
5411,
2845,
16,
7010,
5411,
3634,
1290,
3335,
16,
7010,
5411,
509,
5034,
12,
8949,
1182,
3631,
7010,
5411,
5700,
5147,
3039,
60,
10525,
422,
374,
692,
261,
7124,
1290,
3335,
692,
13588,
10477,
18,
6236,
67,
55,
53,
12185,
67,
54,
789,
4294,
397,
404,
294,
13588,
10477,
18,
6694,
67,
55,
53,
12185,
67,
54,
789,
4294,
300,
404,
13,
294,
5700,
5147,
3039,
60,
10525,
1769,
203,
3639,
2254,
5034,
3844,
1182,
8872,
31,
203,
3639,
261,
8949,
382,
16,
3844,
1182,
8872,
13,
273,
3634,
1290,
3335,
203,
5411,
692,
261,
11890,
5034,
12,
8949,
20,
9242,
3631,
2254,
5034,
19236,
8949,
21,
9242,
3719,
203,
5411,
294,
261,
11890,
5034,
12,
8949,
21,
9242,
3631,
2254,
5034,
19236,
8949,
20,
9242,
10019,
203,
3639,
309,
261,
24492,
5147,
3039,
60,
10525,
422,
374,
13,
2583,
12,
8949,
1182,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../interface/IERC20.sol";
import "../interface/ILToken.sol";
import "./ERC20.sol";
import "../math/UnsignedSafeMath.sol";
/**
* @title Deri Protocol liquidity provider token implementation
*/
contract LToken is IERC20, ILToken, ERC20 {
using UnsignedSafeMath for uint256;
// Pool address this LToken associated with
address private _pool;
modifier _pool_() {
require(msg.sender == _pool, "LToken: called by non-associative pool, probably the original pool has been migrated");
_;
}
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token
*/
constructor(string memory name_, string memory symbol_, address pool_) ERC20(name_, symbol_) {
require(pool_ != address(0), "LToken: construct with 0 address pool");
_pool = pool_;
}
/**
* @dev See {ILToken}.{setPool}
*/
function setPool(address newPool) public override {
require(newPool != address(0), "LToken: setPool to 0 address");
require(msg.sender == _pool, "LToken: setPool caller is not current pool");
_pool = newPool;
}
/**
* @dev See {ILToken}.{pool}
*/
function pool() public view override returns (address) {
return _pool;
}
/**
* @dev See {ILToken}.{mint}
*/
function mint(address account, uint256 amount) public override _pool_ {
require(account != address(0), "LToken: mint to 0 address");
_balances[account] = _balances[account].add(amount);
_totalSupply = _totalSupply.add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev See {ILToken}.{burn}
*/
function burn(address account, uint256 amount) public override _pool_ {
require(account != address(0), "LToken: burn from 0 address");
require(_balances[account] >= amount, "LToken: burn amount exceeds balance");
_balances[account] = _balances[account].sub(amount);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
}
// 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 Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `amount` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @dev Emitted when `amount` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `amount` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 amount);
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the name.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, 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() external view returns (uint8);
/**
* @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 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 the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the allowance mechanism.
* `amount` is then deducted from the caller's allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC20.sol";
/**
* @title Deri Protocol liquidity provider token interface
*/
interface ILToken is IERC20 {
/**
* @dev Set the pool address of this LToken
* pool is the only controller of this contract
* can only be called by current pool
*/
function setPool(address newPool) external;
/**
* @dev Returns address of pool
*/
function pool() external view returns (address);
/**
* @dev Mint LToken to `account` of `amount`
*
* Can only be called by pool
* `account` cannot be zero address
*/
function mint(address account, uint256 amount) external;
/**
* @dev Burn `amount` LToken of `account`
*
* Can only be called by pool
* `account` cannot be zero address
* `account` must owns at least `amount` LToken
*/
function burn(address account, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../interface/IERC20.sol";
import "../math/UnsignedSafeMath.sol";
/**
* @title ERC20 Implementation
*/
contract ERC20 is IERC20 {
using UnsignedSafeMath for uint256;
string _name;
string _symbol;
uint8 _decimals = 18;
uint256 _totalSupply;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) _allowances;
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC20}.{name}
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev See {IERC20}.{symbol}
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC20}.{decimals}
*/
function decimals() public view override 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}.{allowance}
*/
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20}.{approve}
*/
function approve(address spender, uint256 amount) public override returns (bool) {
require(spender != address(0), "ERC20: approve to 0 address");
_approve(msg.sender, spender, amount);
return true;
}
/**
* @dev See {IERC20}.{transfer}
*/
function transfer(address to, uint256 amount) public override returns (bool) {
require(to != address(0), "ERC20: transfer to 0 address");
require(_balances[msg.sender] >= amount, "ERC20: transfer amount exceeds balance");
_transfer(msg.sender, to, amount);
return true;
}
/**
* @dev See {IERC20}.{transferFrom}
*/
function transferFrom(address from, address to, uint256 amount) public override returns (bool) {
require(to != address(0), "ERC20: transferFrom to 0 address");
if (_allowances[from][msg.sender] != uint256(-1)) {
require(_allowances[from][msg.sender] >= amount, "ERC20: transferFrom not approved");
_allowances[from][msg.sender] = _allowances[from][msg.sender].sub(amount);
}
_transfer(from, to, amount);
return true;
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`.
* Emits an {Approval} event.
*
* Parameters check should be carried out before calling this function.
*/
function _approve(address owner, address spender, uint256 amount) internal {
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Moves tokens `amount` from `from` to `to`.
* Emits a {Transfer} event.
*
* Parameters check should be carried out before calling this function.
*/
function _transfer(address from, address to, uint256 amount) internal {
_balances[from] = _balances[from].sub(amount);
_balances[to] = _balances[to].add(amount);
emit Transfer(from, to, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @title Unsigned safe math
*/
library UnsignedSafeMath {
/**
* @dev Addition of unsigned integers, counterpart to `+`
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "UnsignedSafeMath: addition overflow");
return c;
}
/**
* @dev Subtraction of unsigned integers, counterpart to `-`
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(a >= b, "UnsignedSafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Multiplication of unsigned integers, counterpart to `*`
*/
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, "UnsignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Division of unsigned integers, counterpart to `/`
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "UnsignedSafeMath: division by zero");
uint256 c = a / b;
return c;
}
/**
* @dev Modulo of unsigned integers, counterpart to `%`
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "UnsignedSafeMath: modulo by zero");
uint256 c = a % b;
return c;
}
} | * @title ERC20 Implementation/ | contract ERC20 is IERC20 {
using UnsignedSafeMath for uint256;
string _name;
string _symbol;
uint8 _decimals = 18;
uint256 _totalSupply;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) _allowances;
}
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
function name() public view override returns (string memory) {
return _name;
}
function symbol() public view override returns (string memory) {
return _symbol;
}
function decimals() public view override returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
require(spender != address(0), "ERC20: approve to 0 address");
_approve(msg.sender, spender, amount);
return true;
}
function transfer(address to, uint256 amount) public override returns (bool) {
require(to != address(0), "ERC20: transfer to 0 address");
require(_balances[msg.sender] >= amount, "ERC20: transfer amount exceeds balance");
_transfer(msg.sender, to, amount);
return true;
}
function transferFrom(address from, address to, uint256 amount) public override returns (bool) {
require(to != address(0), "ERC20: transferFrom to 0 address");
if (_allowances[from][msg.sender] != uint256(-1)) {
require(_allowances[from][msg.sender] >= amount, "ERC20: transferFrom not approved");
_allowances[from][msg.sender] = _allowances[from][msg.sender].sub(amount);
}
_transfer(from, to, amount);
return true;
}
function transferFrom(address from, address to, uint256 amount) public override returns (bool) {
require(to != address(0), "ERC20: transferFrom to 0 address");
if (_allowances[from][msg.sender] != uint256(-1)) {
require(_allowances[from][msg.sender] >= amount, "ERC20: transferFrom not approved");
_allowances[from][msg.sender] = _allowances[from][msg.sender].sub(amount);
}
_transfer(from, to, amount);
return true;
}
function _approve(address owner, address spender, uint256 amount) internal {
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address from, address to, uint256 amount) internal {
_balances[from] = _balances[from].sub(amount);
_balances[to] = _balances[to].add(amount);
emit Transfer(from, to, amount);
}
}
| 10,376,704 | [
1,
654,
39,
3462,
25379,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
4232,
39,
3462,
353,
467,
654,
39,
3462,
288,
203,
203,
565,
1450,
1351,
5679,
9890,
10477,
364,
2254,
5034,
31,
203,
203,
565,
533,
389,
529,
31,
203,
565,
533,
389,
7175,
31,
203,
565,
2254,
28,
389,
31734,
273,
6549,
31,
203,
565,
2254,
5034,
389,
4963,
3088,
1283,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
389,
70,
26488,
31,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
389,
5965,
6872,
31,
203,
203,
97,
203,
203,
565,
3885,
261,
1080,
3778,
508,
67,
16,
533,
3778,
3273,
67,
13,
288,
203,
3639,
389,
529,
273,
508,
67,
31,
203,
3639,
389,
7175,
273,
3273,
67,
31,
203,
565,
289,
203,
203,
565,
445,
508,
1435,
1071,
1476,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
529,
31,
203,
565,
289,
203,
203,
565,
445,
3273,
1435,
1071,
1476,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
7175,
31,
203,
565,
289,
203,
203,
565,
445,
15105,
1435,
1071,
1476,
3849,
1135,
261,
11890,
28,
13,
288,
203,
3639,
327,
389,
31734,
31,
203,
565,
289,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
31,
203,
565,
289,
203,
203,
565,
445,
11013,
951,
12,
2867,
2236,
13,
1071,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
70,
26488,
63,
4631,
15533,
203,
565,
289,
203,
2
] |
// 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 "../../BaseStrategy.sol";
import "../../interfaces/ISushiSwap.sol";
import "../../interfaces/IDynamicSubLPStrategy.sol";
import "../../interfaces/IOracle.sol";
import "../../libraries/Babylonian.sol";
/// @notice DynamicSubLPStrategy sub-strategy for uniswap-forks with 0.3% fees
/// @dev For gas saving, the strategy directly transfers to bentobox instead
/// of transfering to DynamicLPStrategy. This contract is made abstract so we can
/// implements fork specificities.
abstract contract DynamicSubLPStrategy is IDynamicSubLPStrategy, Ownable {
using SafeTransferLib for ERC20;
event LpMinted(uint256 total, uint256 strategyAmount, uint256 feeAmount);
struct RouterInfo {
address factory;
ISushiSwap router;
bytes32 pairCodeHash;
}
address public immutable override dynamicStrategy;
address public immutable override strategyTokenIn;
address public immutable override strategyTokenOut;
IOracle public immutable oracle;
address public immutable bentoBox;
uint8 public immutable pid;
/// @notice When true, the _rewardToken will be swapped to the pair's
/// token0 for one-sided liquidity providing, otherwise, the pair's token1.
bool public usePairToken0;
/// @notice cache of the strategyTokenOut token used to first swap the token rewards to before
/// splitting the liquidity in half for minting strategyTokenIn
address public immutable pairInputToken;
/// @notice the token farmed by staking strategyTokenIn in masterchef
address public immutable rewardToken;
RouterInfo public strategyTokenInInfo;
RouterInfo public strategyTokenOutInfo;
event LogSetStrategyExecutor(address indexed executor, bool allowed);
/**
@param _bentoBox BentoBox address.
@param _dynamicStrategy The dynamic strategy this sub strategy belongs to
@param _strategyTokenIn Address of the LP token the strategy is farming with
@param _strategyTokenOut Address of the LP token the strategy is swapping the rewardTokens to
@param _oracle The oracle to price the strategyTokenOut. peekSpot needs to send the inverse price in USD
@param _rewardToken The token the staking is farming
@param _pid The masterchef pool id for strategyTokenIn staking
@param _usePairToken0 When true, the _rewardToken will be swapped to the pair's token0 for one-sided liquidity
providing, otherwise, the pair's token1.
@param _strategyTokenInInfo The router information to wrap strategyTokenIn from token0 and token1
@param _strategyTokenOutInfo The router information to swap the reward tokens for more strategyTokenOut
*/
constructor(
address _bentoBox,
address _dynamicStrategy,
address _strategyTokenIn,
address _strategyTokenOut,
IOracle _oracle,
address _rewardToken,
uint8 _pid,
bool _usePairToken0,
RouterInfo memory _strategyTokenInInfo,
RouterInfo memory _strategyTokenOutInfo
) {
bentoBox = _bentoBox;
dynamicStrategy = _dynamicStrategy;
strategyTokenIn = _strategyTokenIn;
strategyTokenOut = _strategyTokenOut;
oracle = _oracle;
rewardToken = _rewardToken;
pid = _pid;
usePairToken0 = _usePairToken0;
strategyTokenInInfo = _strategyTokenInInfo;
strategyTokenOutInfo = _strategyTokenOutInfo;
ERC20(_strategyTokenIn).safeApprove(address(_strategyTokenInInfo.router), type(uint256).max);
// For wrapping from token0 and token1 to strategyTokenIn
address token0 = ISushiSwap(_strategyTokenIn).token0();
address token1 = ISushiSwap(_strategyTokenIn).token1();
ERC20(token0).safeApprove(address(_strategyTokenInInfo.router), type(uint256).max);
ERC20(token1).safeApprove(address(_strategyTokenInInfo.router), type(uint256).max);
// For swapping the reward tokens to strategyTokenOut
token0 = ISushiSwap(_strategyTokenOut).token0();
token1 = ISushiSwap(_strategyTokenOut).token1();
ERC20(token0).safeApprove(address(_strategyTokenOutInfo.router), type(uint256).max);
ERC20(token1).safeApprove(address(_strategyTokenOutInfo.router), type(uint256).max);
pairInputToken = _usePairToken0 ? token0 : token1;
}
modifier onlyDynamicStrategy() {
require(msg.sender == dynamicStrategy, "unauthorized");
_;
}
function skim(uint256 amount) external override onlyDynamicStrategy {
_deposit(amount);
}
/// @dev harvest the rewardToken from masterchef and send the strategyTokenOut to bentobox.
/// strategyTokenOut can be obtained by calling swapToLP to swap the reward token for
/// more strategyTokenOut. In this case, a subsequent call to harvest is necessary for the
/// strategyTokenOut tokens to be available for transfer.
function harvest() external override onlyDynamicStrategy returns (uint256 amountAdded) {
_claimRewards();
/// @dev transfer the strategyTokenOut to bentobox directly and
/// report the amount added.
amountAdded = ERC20(strategyTokenOut).balanceOf(address(this));
ERC20(strategyTokenOut).safeTransfer(bentoBox, amountAdded);
}
/// @dev withdraw the specified amount from masterchef.
/// Only to be used when the strategyTokenIn matches the dyanmic strategyToken.
/// (validated inside DynamicLPStrategy.withdraw)
function withdraw(uint256 amount) external override onlyDynamicStrategy returns (uint256 actualAmount) {
_withdraw(amount);
actualAmount = ERC20(strategyTokenIn).balanceOf(address(this));
ERC20(strategyTokenIn).safeTransfer(bentoBox, actualAmount);
}
/// @dev exit everything from masterchef.
/// Only to be used when the strategyTokenIn matches the dyanmic strategyToken.
/// (validated inside DynamicLPStrategy.exit)
function exit() external override onlyDynamicStrategy returns (uint256 actualAmount) {
_emergencyWithdraw();
actualAmount = ERC20(strategyTokenIn).balanceOf(address(this));
ERC20(strategyTokenIn).safeTransfer(bentoBox, actualAmount);
}
/// @notice Swap token0 and token1 in the contract for deposits them to address(this)
function swapToLP(
uint256 amountOutMin,
uint256 feePercent,
address feeTo
) public override onlyDynamicStrategy returns (uint256 amountOut) {
RouterInfo memory _strategyTokenOutInfo = strategyTokenOutInfo;
uint256 tokenInAmount = _swapTokens(rewardToken, pairInputToken, _strategyTokenOutInfo.factory, _strategyTokenOutInfo.pairCodeHash);
(uint256 reserve0, uint256 reserve1, ) = ISushiSwap(strategyTokenOut).getReserves();
address token0 = ISushiSwap(strategyTokenOut).token0();
address token1 = ISushiSwap(strategyTokenOut).token1();
// The pairInputToken amount to swap to get the equivalent pair second token amount
uint256 swapAmountIn = _calculateSwapInAmount(usePairToken0 ? reserve0 : reserve1, tokenInAmount);
address[] memory path = new address[](2);
if (usePairToken0) {
path[0] = token0;
path[1] = token1;
} else {
path[0] = token1;
path[1] = token0;
}
uint256[] memory amounts = UniswapV2Library.getAmountsOut(
_strategyTokenOutInfo.factory,
swapAmountIn,
path,
_strategyTokenOutInfo.pairCodeHash
);
ERC20(path[0]).safeTransfer(strategyTokenOut, amounts[0]);
_swap(amounts, path, address(this), _strategyTokenOutInfo.factory, _strategyTokenOutInfo.pairCodeHash);
uint256 amountStrategyLpBefore = ERC20(strategyTokenOut).balanceOf(address(this));
// Minting liquidity with optimal token balances but is still leaving some
// dust because of rounding. The dust will be used the next time the function
// is called.
_strategyTokenOutInfo.router.addLiquidity(
token0,
token1,
ERC20(token0).balanceOf(address(this)),
ERC20(token1).balanceOf(address(this)),
1,
1,
address(this),
type(uint256).max
);
uint256 total = ERC20(strategyTokenOut).balanceOf(address(this)) - amountStrategyLpBefore;
require(total >= amountOutMin, "INSUFFICIENT_AMOUNT_OUT");
uint256 feeAmount = (total * feePercent) / 100;
if (feeAmount > 0) {
amountOut = total - feeAmount;
ERC20(strategyTokenOut).safeTransfer(feeTo, feeAmount);
}
emit LpMinted(total, amountOut, feeAmount);
}
/// @notice wrap the token0 and token1 deposited into the contract from a previous withdrawAndUnwrapTo
/// and wrap into a strategyTokenIn lp token.
/// @param minDustAmount0 the minimum token0 left after the first addLiquidity to consider
/// swapping into more strategyTokenIn Lps
/// @param minDustAmount1 same as `minDustAmount0` but for token1
function wrapAndDeposit(uint256 minDustAmount0, uint256 minDustAmount1)
external
override
onlyDynamicStrategy
returns (uint256 amount, uint256 priceAmount)
{
RouterInfo memory _strategyTokenInInfo = strategyTokenInInfo;
address token0 = ISushiSwap(strategyTokenIn).token0();
address token1 = ISushiSwap(strategyTokenIn).token1();
uint256 token0Balance = ERC20(token0).balanceOf(address(this));
uint256 token1Balance = ERC20(token1).balanceOf(address(this));
// swap ideal amount of token0 and token1. This is likely leave some
// token0 or token1
(uint256 idealAmount0, uint256 idealAmount1, uint256 lpAmount) = _strategyTokenInInfo.router.addLiquidity(
token0,
token1,
token0Balance,
token1Balance,
1,
1,
address(this),
type(uint256).max
);
(uint256 reserve0, uint256 reserve1, ) = ISushiSwap(strategyTokenIn).getReserves();
// take the remaining token0 or token1 left from addliquidity and one
// side liquidity provide with it
token0Balance = token0Balance - idealAmount0;
token1Balance = token1Balance - idealAmount1;
if (token0Balance >= minDustAmount0 && token1Balance >= minDustAmount1) {
// swap remaining token0 in the contract
if (token0Balance > 0) {
uint256 swapAmountIn = _calculateSwapInAmount(reserve0, token0Balance);
token0Balance -= swapAmountIn;
token1Balance = _getAmountOut(swapAmountIn, reserve0, reserve1);
ERC20(token0).safeTransfer(strategyTokenIn, swapAmountIn);
ISushiSwap(strategyTokenIn).swap(0, token1Balance, address(this), "");
}
// swap remaining token1 in the contract
else {
uint256 swapAmountIn = _calculateSwapInAmount(reserve1, token1Balance);
token1Balance -= swapAmountIn;
token0Balance = _getAmountOut(swapAmountIn, reserve1, reserve0);
ERC20(token1).safeTransfer(strategyTokenIn, swapAmountIn);
ISushiSwap(strategyTokenIn).swap(token0Balance, 0, address(this), "");
}
if (token0Balance > 0 && token1Balance > 0) {
(, , uint256 lpAmountFromRemaining) = _strategyTokenInInfo.router.addLiquidity(
token0,
token1,
token0Balance,
token1Balance,
1,
1,
address(this),
type(uint256).max
);
lpAmount += lpAmountFromRemaining;
}
}
amount = lpAmount;
_deposit(lpAmount);
priceAmount = (amount * 1e18) / oracle.peekSpot("");
emit LpMinted(lpAmount, lpAmount, 0);
}
/// @notice withdraw from masterchef and unwrap token0 and token1 to recipient, so that
/// the next strategy can use the liquidity and wrap it back.
/// Note: this function will potentially leave out some reward tokens, so the harvest/swapToLp/harvest routine
/// should be run beforehand.
function withdrawAndUnwrapTo(IDynamicSubLPStrategy recipient)
external
override
onlyDynamicStrategy
returns (uint256 amount, uint256 priceAmount)
{
(uint256 stakedAmount, ) = _userInfo();
_withdraw(stakedAmount);
address token0 = ISushiSwap(strategyTokenIn).token0();
address token1 = ISushiSwap(strategyTokenIn).token1();
amount = ERC20(strategyTokenIn).balanceOf(address(this));
/// @dev calculate the price before removing the liquidity
priceAmount = (amount * 1e18) / oracle.peekSpot("");
ISushiSwap(strategyTokenInInfo.router).removeLiquidity(token0, token1, amount, 0, 0, address(recipient), type(uint256).max);
}
/// @notice emergency function in case of fund locked.
function rescueTokens(
address token,
address to,
uint256 amount
) external override onlyOwner {
ERC20(token).safeTransfer(to, amount);
}
function _swap(
uint256[] memory amounts,
address[] memory path,
address _to,
address _factory,
bytes32 _pairCodeHash
) private {
for (uint256 i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
address token0 = input < output ? input : output;
uint256 amountOut = amounts[i + 1];
(uint256 amount0Out, uint256 amount1Out) = input == token0 ? (uint256(0), amountOut) : (amountOut, uint256(0));
address to = i < path.length - 2 ? UniswapV2Library.pairFor(_factory, output, path[i + 2], _pairCodeHash) : _to;
IUniswapV2Pair(UniswapV2Library.pairFor(_factory, input, output, _pairCodeHash)).swap(amount0Out, amount1Out, to, new bytes(0));
}
}
function _swapTokens(
address tokenIn,
address tokenOut,
address _factory,
bytes32 _pairCodeHash
) private returns (uint256 amountOut) {
address[] memory path = new address[](2);
path[0] = tokenIn;
path[path.length - 1] = tokenOut;
uint256 amountIn = ERC20(path[0]).balanceOf(address(this));
uint256[] memory amounts = UniswapV2Library.getAmountsOut(_factory, amountIn, path, _pairCodeHash);
amountOut = amounts[amounts.length - 1];
ERC20(path[0]).safeTransfer(UniswapV2Library.pairFor(_factory, path[0], path[1], _pairCodeHash), amounts[0]);
_swap(amounts, path, address(this), _factory, _pairCodeHash);
}
function _calculateSwapInAmount(uint256 reserveIn, uint256 amountIn) internal pure returns (uint256) {
return (Babylonian.sqrt(reserveIn * ((amountIn * 3988000) + (reserveIn * 3988009))) - (reserveIn * 1997)) / 1994;
}
function _getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
uint256 amountInWithFee = amountIn * 997;
uint256 numerator = amountInWithFee * reserveOut;
uint256 denominator = (reserveIn * 1000) + amountInWithFee;
amountOut = numerator / denominator;
}
/// @dev force to reimplement masterchef interface for common staking interface
function _deposit(uint256 amount) internal virtual;
function _claimRewards() internal virtual;
function _withdraw(uint256 amount) internal virtual;
function _userInfo() internal view virtual returns (uint256 amount, uint256 rewardDebt);
function _emergencyWithdraw() internal virtual;
}
| @notice When true, the _rewardToken will be swapped to the pair's token0 for one-sided liquidity providing, otherwise, the pair's token1. | bool public usePairToken0;
| 1,029,222 | [
1,
9434,
638,
16,
326,
389,
266,
2913,
1345,
903,
506,
7720,
1845,
358,
326,
3082,
1807,
1147,
20,
364,
1245,
17,
7722,
785,
4501,
372,
24237,
17721,
16,
3541,
16,
326,
3082,
1807,
1147,
21,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
1426,
1071,
999,
4154,
1345,
20,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.6.8;
import "./ProtoBufRuntime.sol";
import "./GoogleProtobufAny.sol";
library BorrowingIssuanceProperty {
//struct definition
struct Data {
address borrowingTokenAddress;
address collateralTokenAddress;
uint256 borrowingAmount;
uint256 collateralRatio;
uint256 collateralAmount;
uint256 interestRate;
uint256 interestAmount;
uint256 tenorDays;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[9] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_borrowingTokenAddress(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_collateralTokenAddress(pointer, bs, r, counters);
}
else if (fieldId == 3) {
pointer += _read_borrowingAmount(pointer, bs, r, counters);
}
else if (fieldId == 4) {
pointer += _read_collateralRatio(pointer, bs, r, counters);
}
else if (fieldId == 5) {
pointer += _read_collateralAmount(pointer, bs, r, counters);
}
else if (fieldId == 6) {
pointer += _read_interestRate(pointer, bs, r, counters);
}
else if (fieldId == 7) {
pointer += _read_interestAmount(pointer, bs, r, counters);
}
else if (fieldId == 8) {
pointer += _read_tenorDays(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_borrowingTokenAddress(
uint256 p,
bytes memory bs,
Data memory r,
uint[9] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(address x, uint256 sz) = ProtoBufRuntime._decode_sol_address(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.borrowingTokenAddress = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_collateralTokenAddress(
uint256 p,
bytes memory bs,
Data memory r,
uint[9] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(address x, uint256 sz) = ProtoBufRuntime._decode_sol_address(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.collateralTokenAddress = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_borrowingAmount(
uint256 p,
bytes memory bs,
Data memory r,
uint[9] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs);
if (isNil(r)) {
counters[3] += 1;
} else {
r.borrowingAmount = x;
if (counters[3] > 0) counters[3] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_collateralRatio(
uint256 p,
bytes memory bs,
Data memory r,
uint[9] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs);
if (isNil(r)) {
counters[4] += 1;
} else {
r.collateralRatio = x;
if (counters[4] > 0) counters[4] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_collateralAmount(
uint256 p,
bytes memory bs,
Data memory r,
uint[9] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs);
if (isNil(r)) {
counters[5] += 1;
} else {
r.collateralAmount = x;
if (counters[5] > 0) counters[5] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_interestRate(
uint256 p,
bytes memory bs,
Data memory r,
uint[9] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs);
if (isNil(r)) {
counters[6] += 1;
} else {
r.interestRate = x;
if (counters[6] > 0) counters[6] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_interestAmount(
uint256 p,
bytes memory bs,
Data memory r,
uint[9] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs);
if (isNil(r)) {
counters[7] += 1;
} else {
r.interestAmount = x;
if (counters[7] > 0) counters[7] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_tenorDays(
uint256 p,
bytes memory bs,
Data memory r,
uint[9] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs);
if (isNil(r)) {
counters[8] += 1;
} else {
r.tenorDays = x;
if (counters[8] > 0) counters[8] -= 1;
}
return sz;
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_sol_address(r.borrowingTokenAddress, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_sol_address(r.collateralTokenAddress, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_sol_uint256(r.borrowingAmount, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
4,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_sol_uint256(r.collateralRatio, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
5,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_sol_uint256(r.collateralAmount, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
6,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_sol_uint256(r.interestRate, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
7,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_sol_uint256(r.interestAmount, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
8,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_sol_uint256(r.tenorDays, pointer, bs);
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory /* r */
) internal pure returns (uint) {
uint256 e;
e += 1 + 23;
e += 1 + 23;
e += 1 + 35;
e += 1 + 35;
e += 1 + 35;
e += 1 + 35;
e += 1 + 35;
e += 1 + 35;
return e;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.borrowingTokenAddress = input.borrowingTokenAddress;
output.collateralTokenAddress = input.collateralTokenAddress;
output.borrowingAmount = input.borrowingAmount;
output.collateralRatio = input.collateralRatio;
output.collateralAmount = input.collateralAmount;
output.interestRate = input.interestRate;
output.interestAmount = input.interestAmount;
output.tenorDays = input.tenorDays;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library BorrowingIssuanceProperty
library BorrowingEngagementProperty {
//enum definition
// Solidity enum definitions
enum LoanState {
LoanStateUnknown,
Unpaid,
Repaid,
Delinquent
}
// Solidity enum encoder
function encode_LoanState(LoanState x) internal pure returns (int64) {
if (x == LoanState.LoanStateUnknown) {
return 0;
}
if (x == LoanState.Unpaid) {
return 1;
}
if (x == LoanState.Repaid) {
return 2;
}
if (x == LoanState.Delinquent) {
return 3;
}
revert();
}
// Solidity enum decoder
function decode_LoanState(int64 x) internal pure returns (LoanState) {
if (x == 0) {
return LoanState.LoanStateUnknown;
}
if (x == 1) {
return LoanState.Unpaid;
}
if (x == 2) {
return LoanState.Repaid;
}
if (x == 3) {
return LoanState.Delinquent;
}
revert();
}
//struct definition
struct Data {
BorrowingEngagementProperty.LoanState loanState;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[2] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_loanState(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_loanState(
uint256 p,
bytes memory bs,
Data memory r,
uint[2] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs);
BorrowingEngagementProperty.LoanState x = decode_LoanState(tmp);
if (isNil(r)) {
counters[1] += 1;
} else {
r.loanState = x;
if(counters[1] > 0) counters[1] -= 1;
}
return sz;
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
int64 _enum_loanState = encode_LoanState(r.loanState);
pointer += ProtoBufRuntime._encode_enum(_enum_loanState, pointer, bs);
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_enum(encode_LoanState(r.loanState));
return e;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.loanState = input.loanState;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library BorrowingEngagementProperty | * @dev The decoder for reading a field @param p The offset of bytes array to start decode @param bs The bytes array to be decoded @param r The in-memory struct @param counters The counters for repeated fields @return The number of bytes decoded/* if `r` is NULL, then only counting the number of fields./ | function _read_collateralTokenAddress(
uint256 p,
bytes memory bs,
Data memory r,
uint[9] memory counters
) internal pure returns (uint) {
(address x, uint256 sz) = ProtoBufRuntime._decode_sol_address(p, bs);
if (isNil(r)) {
counters[2] += 1;
r.collateralTokenAddress = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
| 6,490,014 | [
1,
1986,
8320,
364,
6453,
279,
652,
225,
293,
1021,
1384,
434,
1731,
526,
358,
787,
2495,
225,
7081,
1021,
1731,
526,
358,
506,
6383,
225,
436,
1021,
316,
17,
7858,
1958,
225,
13199,
1021,
13199,
364,
12533,
1466,
327,
1021,
1300,
434,
1731,
6383,
19,
309,
1375,
86,
68,
353,
3206,
16,
1508,
1338,
22075,
326,
1300,
434,
1466,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
389,
896,
67,
12910,
2045,
287,
1345,
1887,
12,
203,
565,
2254,
5034,
293,
16,
203,
565,
1731,
3778,
7081,
16,
203,
565,
1910,
3778,
436,
16,
203,
565,
2254,
63,
29,
65,
3778,
13199,
203,
225,
262,
2713,
16618,
1135,
261,
11890,
13,
288,
203,
565,
261,
2867,
619,
16,
2254,
5034,
11262,
13,
273,
7440,
5503,
5576,
6315,
3922,
67,
18281,
67,
2867,
12,
84,
16,
7081,
1769,
203,
565,
309,
261,
291,
12616,
12,
86,
3719,
288,
203,
1377,
13199,
63,
22,
65,
1011,
404,
31,
203,
1377,
436,
18,
12910,
2045,
287,
1345,
1887,
273,
619,
31,
203,
1377,
309,
261,
23426,
63,
22,
65,
405,
374,
13,
13199,
63,
22,
65,
3947,
404,
31,
203,
565,
289,
203,
565,
327,
11262,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.25;
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
// File: openzeppelin-solidity/contracts/AddressUtils.sol
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param _addr address to check
* @return whether the target address is a contract
*/
function isContract(address _addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(_addr) }
return size > 0;
}
}
// File: contracts/VestingPrivateSale.sol
/**
* Vesting smart contract for the private sale. Vesting period is 18 months in total.
* All 6 months 33% percent of the vested tokens will be released - step function.
*/
contract VestingPrivateSale is Ownable {
uint256 constant public sixMonth = 182 days;
uint256 constant public twelveMonth = 365 days;
uint256 constant public eighteenMonth = sixMonth + twelveMonth;
ERC20Basic public erc20Contract;
struct Locking {
uint256 bucket1;
uint256 bucket2;
uint256 bucket3;
uint256 startDate;
}
mapping(address => Locking) public lockingMap;
event ReleaseVestingEvent(address indexed to, uint256 value);
/**
* @dev Constructor. With the reference to the ERC20 contract
*/
constructor(address _erc20) public {
require(AddressUtils.isContract(_erc20), "Address is not a smart contract");
erc20Contract = ERC20Basic(_erc20);
}
/**
* @dev Adds vested tokens to this contract. ERC20 contract has assigned the tokens.
* @param _tokenHolder The token holder.
* @param _bucket1 The first bucket. Will be available after 6 months.
* @param _bucket2 The second bucket. Will be available after 12 months.
* @param _bucket3 The third bucket. Will be available after 18 months.
* @return True if accepted.
*/
function addVested(
address _tokenHolder,
uint256 _bucket1,
uint256 _bucket2,
uint256 _bucket3
)
public
returns (bool)
{
require(msg.sender == address(erc20Contract), "ERC20 contract required");
require(lockingMap[_tokenHolder].startDate == 0, "Address is already vested");
lockingMap[_tokenHolder].startDate = block.timestamp;
lockingMap[_tokenHolder].bucket1 = _bucket1;
lockingMap[_tokenHolder].bucket2 = _bucket2;
lockingMap[_tokenHolder].bucket3 = _bucket3;
return true;
}
/**
* @dev Calculates the amount of the total assigned tokens of a tokenholder.
* @param _tokenHolder The address to query the balance of.
* @return The total amount of owned tokens (vested + available).
*/
function balanceOf(
address _tokenHolder
)
public
view
returns (uint256)
{
return lockingMap[_tokenHolder].bucket1 + lockingMap[_tokenHolder].bucket2 + lockingMap[_tokenHolder].bucket3;
}
/**
* @dev Calculates the amount of currently available (unlocked) tokens. This amount can be unlocked.
* @param _tokenHolder The address to query the balance of.
* @return The total amount of owned and available tokens.
*/
function availableBalanceOf(
address _tokenHolder
)
public
view
returns (uint256)
{
uint256 startDate = lockingMap[_tokenHolder].startDate;
uint256 tokens = 0;
if (startDate + sixMonth <= block.timestamp) {
tokens = lockingMap[_tokenHolder].bucket1;
}
if (startDate + twelveMonth <= block.timestamp) {
tokens = tokens + lockingMap[_tokenHolder].bucket2;
}
if (startDate + eighteenMonth <= block.timestamp) {
tokens = tokens + lockingMap[_tokenHolder].bucket3;
}
return tokens;
}
/**
* @dev Releases unlocked tokens of the transaction sender.
* @dev This function will transfer unlocked tokens to the owner.
* @return The total amount of released tokens.
*/
function releaseBuckets()
public
returns (uint256)
{
return _releaseBuckets(msg.sender);
}
/**
* @dev Admin function.
* @dev Releases unlocked tokens of the _tokenHolder.
* @dev This function will transfer unlocked tokens to the _tokenHolder.
* @param _tokenHolder Address of the token owner to release tokens.
* @return The total amount of released tokens.
*/
function releaseBuckets(
address _tokenHolder
)
public
onlyOwner
returns (uint256)
{
return _releaseBuckets(_tokenHolder);
}
function _releaseBuckets(
address _tokenHolder
)
private
returns (uint256)
{
require(lockingMap[_tokenHolder].startDate != 0, "Is not a locked address");
uint256 startDate = lockingMap[_tokenHolder].startDate;
uint256 tokens = 0;
if (startDate + sixMonth <= block.timestamp) {
tokens = lockingMap[_tokenHolder].bucket1;
lockingMap[_tokenHolder].bucket1 = 0;
}
if (startDate + twelveMonth <= block.timestamp) {
tokens = tokens + lockingMap[_tokenHolder].bucket2;
lockingMap[_tokenHolder].bucket2 = 0;
}
if (startDate + eighteenMonth <= block.timestamp) {
tokens = tokens + lockingMap[_tokenHolder].bucket3;
lockingMap[_tokenHolder].bucket3 = 0;
}
require(erc20Contract.transfer(_tokenHolder, tokens), "Transfer failed");
emit ReleaseVestingEvent(_tokenHolder, tokens);
return tokens;
}
}
// File: contracts/VestingTreasury.sol
/**
* Treasury vesting smart contract. Vesting period is over 36 months.
* Tokens are locked for 6 months. After that releasing the tokens over 30 months with a linear function.
*/
contract VestingTreasury {
using SafeMath for uint256;
uint256 constant public sixMonths = 182 days;
uint256 constant public thirtyMonths = 912 days;
ERC20Basic public erc20Contract;
struct Locking {
uint256 startDate; // date when the release process of the vesting will start.
uint256 initialized; // initialized amount of tokens
uint256 released; // already released tokens
}
mapping(address => Locking) public lockingMap;
event ReleaseVestingEvent(address indexed to, uint256 value);
/**
* @dev Constructor. With the reference to the ERC20 contract
*/
constructor(address _erc20) public {
require(AddressUtils.isContract(_erc20), "Address is not a smart contract");
erc20Contract = ERC20Basic(_erc20);
}
/**
* @dev Adds vested tokens to this contract. ERC20 contract has assigned the tokens.
* @param _tokenHolder The token holder.
* @param _value The amount of tokens to protect.
* @return True if accepted.
*/
function addVested(
address _tokenHolder,
uint256 _value
)
public
returns (bool)
{
require(msg.sender == address(erc20Contract), "ERC20 contract required");
require(lockingMap[_tokenHolder].startDate == 0, "Address is already vested");
lockingMap[_tokenHolder].startDate = block.timestamp + sixMonths;
lockingMap[_tokenHolder].initialized = _value;
lockingMap[_tokenHolder].released = 0;
return true;
}
/**
* @dev Calculates the amount of the total currently vested and available tokens.
* @param _tokenHolder The address to query the balance of.
* @return The total amount of owned tokens (vested + available).
*/
function balanceOf(
address _tokenHolder
)
public
view
returns (uint256)
{
return lockingMap[_tokenHolder].initialized.sub(lockingMap[_tokenHolder].released);
}
/**
* @dev Calculates the amount of currently available (unlocked) tokens. This amount can be unlocked.
* @param _tokenHolder The address to query the balance of.
* @return The total amount of owned and available tokens.
*/
function availableBalanceOf(
address _tokenHolder
)
public
view
returns (uint256)
{
uint256 startDate = lockingMap[_tokenHolder].startDate;
if (block.timestamp <= startDate) {
return 0;
}
uint256 tmpAvailableTokens = 0;
if (block.timestamp >= startDate + thirtyMonths) {
tmpAvailableTokens = lockingMap[_tokenHolder].initialized;
} else {
uint256 timeDiff = block.timestamp - startDate;
uint256 totalBalance = lockingMap[_tokenHolder].initialized;
tmpAvailableTokens = totalBalance.mul(timeDiff).div(thirtyMonths);
}
uint256 availableTokens = tmpAvailableTokens.sub(lockingMap[_tokenHolder].released);
require(availableTokens <= lockingMap[_tokenHolder].initialized, "Max value exceeded");
return availableTokens;
}
/**
* @dev Releases unlocked tokens of the transaction sender.
* @dev This function will transfer unlocked tokens to the owner.
* @return The total amount of released tokens.
*/
function releaseTokens()
public
returns (uint256)
{
require(lockingMap[msg.sender].startDate != 0, "Sender is not a vested address");
uint256 tokens = availableBalanceOf(msg.sender);
lockingMap[msg.sender].released = lockingMap[msg.sender].released.add(tokens);
require(lockingMap[msg.sender].released <= lockingMap[msg.sender].initialized, "Max value exceeded");
require(erc20Contract.transfer(msg.sender, tokens), "Transfer failed");
emit ReleaseVestingEvent(msg.sender, tokens);
return tokens;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
uint256 internal totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender)
public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/MintableToken.sol
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address _to,
uint256 _amount
)
public
hasMintPermission
canMint
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() public onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/CappedToken.sol
/**
* @title Capped token
* @dev Mintable token with a token cap.
*/
contract CappedToken is MintableToken {
uint256 public cap;
constructor(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address _to,
uint256 _amount
)
public
returns (bool)
{
require(totalSupply_.add(_amount) <= cap);
return super.mint(_to, _amount);
}
}
// File: contracts/LockedToken.sol
contract LockedToken is CappedToken {
bool public transferActivated = false;
event TransferActivatedEvent();
constructor(uint256 _cap) public CappedToken(_cap) {
}
/**
* @dev Admin function.
* @dev Activates the token transfer. This action cannot be undone.
* @dev This function should be called after the ICO.
* @return True if ok.
*/
function activateTransfer()
public
onlyOwner
returns (bool)
{
require(transferActivated == false, "Already activated");
transferActivated = true;
emit TransferActivatedEvent();
return true;
}
/**
* @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(transferActivated, "Transfer is not activated");
require(_to != address(this), "Invalid _to address");
return super.transfer(_to, _value);
}
/**
* @dev Transfer tokens from one address to another.
* @param _from The address which you want to send tokens from.
* @param _to The address which you want to transfer to.
* @param _value The amount of tokens to be transferred.
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(transferActivated, "TransferFrom is not activated");
require(_to != address(this), "Invalid _to address");
return super.transferFrom(_from, _to, _value);
}
}
// File: contracts/AlprockzToken.sol
/**
* @title The Alprockz ERC20 Token
*/
contract AlprockzToken is LockedToken {
string public constant name = "AlpRockz";
string public constant symbol = "APZ";
uint8 public constant decimals = 18;
VestingPrivateSale public vestingPrivateSale;
VestingTreasury public vestingTreasury;
constructor() public LockedToken(175 * 1000000 * (10 ** uint256(decimals))) {
}
/**
* @dev Admin function.
* @dev Inits the VestingPrivateSale functionality.
* @dev Precondition: VestingPrivateSale smart contract must be deployed!
* @param _vestingContractAddr The address of the vesting contract for the function 'mintPrivateSale(...)'.
* @return True if everything is ok.
*/
function initMintVestingPrivateSale(
address _vestingContractAddr
)
external
onlyOwner
returns (bool)
{
require(address(vestingPrivateSale) == address(0x0), "Already initialized");
require(address(this) != _vestingContractAddr, "Invalid address");
require(AddressUtils.isContract(_vestingContractAddr), "Address is not a smart contract");
vestingPrivateSale = VestingPrivateSale(_vestingContractAddr);
require(address(this) == address(vestingPrivateSale.erc20Contract()), "Vesting link address not match");
return true;
}
/**
* @dev Admin function.
* @dev Inits the VestingTreasury functionality.
* @dev Precondition: VestingTreasury smart contract must be deployed!
* @param _vestingContractAddr The address of the vesting contract for the function 'mintTreasury(...)'.
* @return True if everything is ok.
*/
function initMintVestingTreasury(
address _vestingContractAddr
)
external
onlyOwner
returns (bool)
{
require(address(vestingTreasury) == address(0x0), "Already initialized");
require(address(this) != _vestingContractAddr, "Invalid address");
require(AddressUtils.isContract(_vestingContractAddr), "Address is not a smart contract");
vestingTreasury = VestingTreasury(_vestingContractAddr);
require(address(this) == address(vestingTreasury.erc20Contract()), "Vesting link address not match");
return true;
}
/**
* @dev Admin function.
* @dev Bulk mint function to save gas.
* @dev both arrays requires to have the same length.
* @param _recipients List of recipients.
* @param _tokens List of tokens to assign to the recipients.
*/
function mintArray(
address[] _recipients,
uint256[] _tokens
)
external
onlyOwner
returns (bool)
{
require(_recipients.length == _tokens.length, "Array length not match");
require(_recipients.length <= 40, "Too many recipients");
for (uint256 i = 0; i < _recipients.length; i++) {
require(super.mint(_recipients[i], _tokens[i]), "Mint failed");
}
return true;
}
/**
* @dev Admin function.
* @dev Bulk mintPrivateSale function to save gas.
* @dev both arrays are required to have the same length.
* @dev Vesting: 25% directly available, 25% after 6, 25% after 12 and 25% after 18 months.
* @param _recipients List of recipients.
* @param _tokens List of tokens to assign to the recipients.
*/
function mintPrivateSale(
address[] _recipients,
uint256[] _tokens
)
external
onlyOwner
returns (bool)
{
require(address(vestingPrivateSale) != address(0x0), "Init required");
require(_recipients.length == _tokens.length, "Array length not match");
require(_recipients.length <= 10, "Too many recipients");
for (uint256 i = 0; i < _recipients.length; i++) {
address recipient = _recipients[i];
uint256 token = _tokens[i];
uint256 first;
uint256 second;
uint256 third;
uint256 fourth;
(first, second, third, fourth) = splitToFour(token);
require(super.mint(recipient, first), "Mint failed");
uint256 totalVested = second + third + fourth;
require(super.mint(address(vestingPrivateSale), totalVested), "Mint failed");
require(vestingPrivateSale.addVested(recipient, second, third, fourth), "Vesting failed");
}
return true;
}
/**
* @dev Admin function.
* @dev Bulk mintTreasury function to save gas.
* @dev both arrays are required to have the same length.
* @dev Vesting: Tokens are locked for 6 months. After that the tokens are released in a linear way.
* @param _recipients List of recipients.
* @param _tokens List of tokens to assign to the recipients.
*/
function mintTreasury(
address[] _recipients,
uint256[] _tokens
)
external
onlyOwner
returns (bool)
{
require(address(vestingTreasury) != address(0x0), "Init required");
require(_recipients.length == _tokens.length, "Array length not match");
require(_recipients.length <= 10, "Too many recipients");
for (uint256 i = 0; i < _recipients.length; i++) {
address recipient = _recipients[i];
uint256 token = _tokens[i];
require(super.mint(address(vestingTreasury), token), "Mint failed");
require(vestingTreasury.addVested(recipient, token), "Vesting failed");
}
return true;
}
function splitToFour(
uint256 _amount
)
private
pure
returns (
uint256 first,
uint256 second,
uint256 third,
uint256 fourth
)
{
require(_amount >= 4, "Minimum amount");
uint256 rest = _amount % 4;
uint256 quarter = (_amount - rest) / 4;
first = quarter + rest;
second = quarter;
third = quarter;
fourth = quarter;
}
} | * @dev Admin function. @dev Releases unlocked tokens of the _tokenHolder. @dev This function will transfer unlocked tokens to the _tokenHolder. @param _tokenHolder Address of the token owner to release tokens. @return The total amount of released tokens./ | function releaseBuckets(
address _tokenHolder
)
public
onlyOwner
returns (uint256)
{
return _releaseBuckets(_tokenHolder);
}
| 2,507,591 | [
1,
4446,
445,
18,
225,
4275,
73,
3304,
25966,
2430,
434,
326,
389,
2316,
6064,
18,
225,
1220,
445,
903,
7412,
25966,
2430,
358,
326,
389,
2316,
6064,
18,
225,
389,
2316,
6064,
5267,
434,
326,
1147,
3410,
358,
3992,
2430,
18,
327,
1021,
2078,
3844,
434,
15976,
2430,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
3992,
14517,
12,
203,
3639,
1758,
389,
2316,
6064,
203,
565,
262,
7010,
3639,
1071,
7010,
3639,
1338,
5541,
203,
3639,
1135,
261,
11890,
5034,
13,
7010,
565,
288,
203,
3639,
327,
389,
9340,
14517,
24899,
2316,
6064,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.2;
// produced by the Solididy File SCC(c) Danny Hwang 2018
// contact : [email protected]
// released under Apache 2.0 licence
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.
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;
}
}
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);
}
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @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 Transfer token to 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) {
_transfer(msg.sender, 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) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @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) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][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
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][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
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses.
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
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;
}
/**
* @return the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
contract ERC20Burnable is ERC20 {
/**
* @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);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance.
* @param from address The account whose tokens will be burned.
* @param value uint256 The amount of token to be burned.
*/
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
contract MINIAI is ERC20, ERC20Detailed, ERC20Burnable {
uint8 public constant DECIMALS = 18;
uint256 public constant INITIAL_SUPPLY = 2000000000 * (10 ** uint256(DECIMALS));
/**
* @dev Constructor that gives msg.sender all of existing tokens.
*/
constructor () public ERC20Detailed("MINI AI", "MNA", DECIMALS) {
_mint(msg.sender, INITIAL_SUPPLY);
}
} | produced by the Solididy File SCC(c) Danny Hwang 2018 contact : [email protected] released under Apache 2.0 licence | library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(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);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
| 2,161 | [
1,
11776,
3263,
635,
326,
348,
7953,
29609,
1387,
348,
6743,
12,
71,
13,
463,
1072,
93,
670,
91,
539,
14863,
5388,
294,
302,
1072,
93,
20701,
539,
18,
87,
952,
36,
75,
4408,
18,
832,
15976,
3613,
24840,
576,
18,
20,
328,
335,
802,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
12083,
14060,
10477,
288,
203,
225,
445,
14064,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
565,
309,
261,
69,
422,
374,
13,
288,
203,
1377,
327,
374,
31,
203,
565,
289,
203,
565,
2254,
5034,
276,
273,
279,
380,
324,
31,
203,
565,
2583,
12,
71,
342,
279,
422,
324,
1769,
203,
565,
327,
276,
31,
203,
225,
289,
203,
203,
225,
445,
14064,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
565,
309,
261,
69,
422,
374,
13,
288,
203,
1377,
327,
374,
31,
203,
565,
289,
203,
565,
2254,
5034,
276,
273,
279,
380,
324,
31,
203,
565,
2583,
12,
71,
342,
279,
422,
324,
1769,
203,
565,
327,
276,
31,
203,
225,
289,
203,
203,
225,
445,
3739,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
565,
2583,
12,
70,
405,
374,
1769,
203,
565,
2254,
5034,
276,
273,
279,
342,
324,
31,
203,
565,
327,
276,
31,
203,
225,
289,
203,
203,
225,
445,
720,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
565,
2583,
12,
70,
1648,
279,
1769,
203,
565,
2254,
5034,
276,
273,
279,
300,
324,
31,
203,
565,
327,
276,
31,
203,
225,
289,
203,
203,
225,
445,
527,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
2
] |
pragma solidity ^0.4.24;
library Math {
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract TokenTransferProxy is Ownable {
/// @dev Only authorized addresses can invoke functions with this modifier.
modifier onlyAuthorized {
require(authorized[msg.sender]);
_;
}
modifier targetAuthorized(address target) {
require(authorized[target]);
_;
}
modifier targetNotAuthorized(address target) {
require(!authorized[target]);
_;
}
mapping (address => bool) public authorized;
address[] public authorities;
event LogAuthorizedAddressAdded(address indexed target, address indexed caller);
event LogAuthorizedAddressRemoved(address indexed target, address indexed caller);
/*
* Public functions
*/
/// @dev Authorizes an address.
/// @param target Address to authorize.
function addAuthorizedAddress(address target)
public
onlyOwner
targetNotAuthorized(target)
{
authorized[target] = true;
authorities.push(target);
emit LogAuthorizedAddressAdded(target, msg.sender);
}
/// @dev Removes authorizion of an address.
/// @param target Address to remove authorization from.
function removeAuthorizedAddress(address target)
public
onlyOwner
targetAuthorized(target)
{
delete authorized[target];
for (uint i = 0; i < authorities.length; i++) {
if (authorities[i] == target) {
authorities[i] = authorities[authorities.length - 1];
authorities.length -= 1;
break;
}
}
emit LogAuthorizedAddressRemoved(target, msg.sender);
}
/// @dev Calls into ERC20 Token contract, invoking transferFrom.
/// @param token Address of token to transfer.
/// @param from Address to transfer token from.
/// @param to Address to transfer token to.
/// @param value Amount of token to transfer.
/// @return Success of transfer.
function transferFrom(
address token,
address from,
address to,
uint value)
public
onlyAuthorized
returns (bool)
{
return Token(token).transferFrom(from, to, value);
}
/*
* Public constant functions
*/
/// @dev Gets all authorized addresses.
/// @return Array of authorized addresses.
function getAuthorizedAddresses()
public
constant
returns (address[])
{
return authorities;
}
}
/// @title Interface for all exchange handler contracts
interface ExchangeHandler {
/// @dev Get the available amount left to fill for an order
/// @param orderAddresses Array of address values needed for this DEX order
/// @param orderValues Array of uint values needed for this DEX order
/// @param exchangeFee Value indicating the fee for this DEX order
/// @param v ECDSA signature parameter v
/// @param r ECDSA signature parameter r
/// @param s ECDSA signature parameter s
/// @return Available amount left to fill for this order
function getAvailableAmount(
address[8] orderAddresses,
uint256[6] orderValues,
uint256 exchangeFee,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256);
/// @dev Perform a buy order at the exchange
/// @param orderAddresses Array of address values needed for each DEX order
/// @param orderValues Array of uint values needed for each DEX order
/// @param exchangeFee Value indicating the fee for this DEX order
/// @param amountToFill Amount to fill in this order
/// @param v ECDSA signature parameter v
/// @param r ECDSA signature parameter r
/// @param s ECDSA signature parameter s
/// @return Amount filled in this order
function performBuy(
address[8] orderAddresses,
uint256[6] orderValues,
uint256 exchangeFee,
uint256 amountToFill,
uint8 v,
bytes32 r,
bytes32 s
) external payable returns (uint256);
/// @dev Perform a sell order at the exchange
/// @param orderAddresses Array of address values needed for each DEX order
/// @param orderValues Array of uint values needed for each DEX order
/// @param exchangeFee Value indicating the fee for this DEX order
/// @param amountToFill Amount to fill in this order
/// @param v ECDSA signature parameter v
/// @param r ECDSA signature parameter r
/// @param s ECDSA signature parameter s
/// @return Amount filled in this order
function performSell(
address[8] orderAddresses,
uint256[6] orderValues,
uint256 exchangeFee,
uint256 amountToFill,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256);
}
contract Token {
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);
}
/// @title The primary contract for Totle Inc
contract TotlePrimary is Ownable {
// Constants
string public constant CONTRACT_VERSION = "0";
uint256 public constant MAX_EXCHANGE_FEE_PERCENTAGE = 0.01 * 10**18; // 1%
bool constant BUY = false;
bool constant SELL = true;
// State variables
mapping(address => bool) public handlerWhitelist;
address tokenTransferProxy;
// Structs
struct Tokens {
address[] tokenAddresses;
bool[] buyOrSell;
uint256[] amountToObtain;
uint256[] amountToGive;
}
struct DEXOrders {
address[] tokenForOrder;
address[] exchanges;
address[8][] orderAddresses;
uint256[6][] orderValues;
uint256[] exchangeFees;
uint8[] v;
bytes32[] r;
bytes32[] s;
}
/// @dev Constructor
/// @param proxy Address of the TokenTransferProxy
constructor(address proxy) public {
tokenTransferProxy = proxy;
}
/*
* Public functions
*/
/// @dev Set an exchange handler address to true/false
/// @notice - onlyOwner modifier only allows the contract owner to run the code
/// @param handler Address of the exchange handler which permission needs changing
/// @param allowed Boolean value to set whether an exchange handler is allowed/denied
function setHandler(address handler, bool allowed) public onlyOwner {
handlerWhitelist[handler] = allowed;
}
/// @dev Synchronously executes an array of orders
/// @notice The first four parameters relate to Token orders, the last eight relate to DEX orders
/// @param tokenAddresses Array of addresses of ERC20 Token contracts for each Token order
/// @param buyOrSell Array indicating whether each Token order is a buy or sell
/// @param amountToObtain Array indicating the amount (in ether or tokens) to obtain in the order
/// @param amountToGive Array indicating the amount (in ether or tokens) to give in the order
/// @param tokenForOrder Array of addresses of ERC20 Token contracts for each DEX order
/// @param exchanges Array of addresses of exchange handler contracts
/// @param orderAddresses Array of address values needed for each DEX order
/// @param orderValues Array of uint values needed for each DEX order
/// @param exchangeFees Array indicating the fee for each DEX order (percentage of fill amount as decimal * 10**18)
/// @param v ECDSA signature parameter v
/// @param r ECDSA signature parameter r
/// @param s ECDSA signature parameter s
function executeOrders(
// Tokens
address[] tokenAddresses,
bool[] buyOrSell,
uint256[] amountToObtain,
uint256[] amountToGive,
// DEX Orders
address[] tokenForOrder,
address[] exchanges,
address[8][] orderAddresses,
uint256[6][] orderValues,
uint256[] exchangeFees,
uint8[] v,
bytes32[] r,
bytes32[] s
) public payable {
require(
tokenAddresses.length == buyOrSell.length &&
buyOrSell.length == amountToObtain.length &&
amountToObtain.length == amountToGive.length
);
require(
tokenForOrder.length == exchanges.length &&
exchanges.length == orderAddresses.length &&
orderAddresses.length == orderValues.length &&
orderValues.length == exchangeFees.length &&
exchangeFees.length == v.length &&
v.length == r.length &&
r.length == s.length
);
// Wrapping order in structs to reduce local variable count
internalOrderExecution(
Tokens(
tokenAddresses,
buyOrSell,
amountToObtain,
amountToGive
),
DEXOrders(
tokenForOrder,
exchanges,
orderAddresses,
orderValues,
exchangeFees,
v,
r,
s
)
);
}
/*
* Internal functions
*/
/// @dev Synchronously executes an array of orders
/// @notice The orders in this function have been wrapped in structs to reduce the local variable count
/// @param tokens Struct containing the arrays of token orders
/// @param orders Struct containing the arrays of DEX orders
function internalOrderExecution(Tokens tokens, DEXOrders orders) internal {
transferTokens(tokens);
uint256 tokensLength = tokens.tokenAddresses.length;
uint256 ordersLength = orders.tokenForOrder.length;
uint256 etherBalance = msg.value;
uint256 orderIndex = 0;
for(uint256 tokenIndex = 0; tokenIndex < tokensLength; tokenIndex++) {
// NOTE - check for repetitions in the token list?
uint256 amountRemaining = tokens.amountToGive[tokenIndex];
uint256 amountObtained = 0;
while(orderIndex < ordersLength) {
require(tokens.tokenAddresses[tokenIndex] == orders.tokenForOrder[orderIndex]);
require(handlerWhitelist[orders.exchanges[orderIndex]]);
if(amountRemaining > 0) {
if(tokens.buyOrSell[tokenIndex] == BUY) {
require(etherBalance >= amountRemaining);
}
(amountRemaining, amountObtained) = performTrade(
tokens.buyOrSell[tokenIndex],
amountRemaining,
amountObtained,
orders, // NOTE - unable to send pointer to order values individually, as run out of stack space!
orderIndex
);
}
orderIndex = SafeMath.add(orderIndex, 1);
// If this is the last order for this token
if(orderIndex == ordersLength || orders.tokenForOrder[SafeMath.sub(orderIndex, 1)] != orders.tokenForOrder[orderIndex]) {
break;
}
}
uint256 amountGiven = SafeMath.sub(tokens.amountToGive[tokenIndex], amountRemaining);
require(orderWasValid(amountObtained, amountGiven, tokens.amountToObtain[tokenIndex], tokens.amountToGive[tokenIndex]));
if(tokens.buyOrSell[tokenIndex] == BUY) {
// Take away spent ether from refund balance
etherBalance = SafeMath.sub(etherBalance, amountGiven);
// Transfer back tokens acquired
if(amountObtained > 0) {
require(Token(tokens.tokenAddresses[tokenIndex]).transfer(msg.sender, amountObtained));
}
} else {
// Add ether to refund balance
etherBalance = SafeMath.add(etherBalance, amountObtained);
// Transfer back un-sold tokens
if(amountRemaining > 0) {
require(Token(tokens.tokenAddresses[tokenIndex]).transfer(msg.sender, amountRemaining));
}
}
}
// Send back acquired/unspent ether - throw on failure
if(etherBalance > 0) {
msg.sender.transfer(etherBalance);
}
}
/// @dev Iterates through a list of token orders, transfer the SELL orders to this contract & calculates if we have the ether needed
/// @param tokens Struct containing the arrays of token orders
function transferTokens(Tokens tokens) internal {
uint256 expectedEtherAvailable = msg.value;
uint256 totalEtherNeeded = 0;
for(uint256 i = 0; i < tokens.tokenAddresses.length; i++) {
if(tokens.buyOrSell[i] == BUY) {
totalEtherNeeded = SafeMath.add(totalEtherNeeded, tokens.amountToGive[i]);
} else {
expectedEtherAvailable = SafeMath.add(expectedEtherAvailable, tokens.amountToObtain[i]);
require(TokenTransferProxy(tokenTransferProxy).transferFrom(
tokens.tokenAddresses[i],
msg.sender,
this,
tokens.amountToGive[i]
));
}
}
// Make sure we have will have enough ETH after SELLs to cover our BUYs
require(expectedEtherAvailable >= totalEtherNeeded);
}
/// @dev Performs a single trade via the requested exchange handler
/// @param buyOrSell Boolean value stating whether this is a buy or sell order
/// @param initialRemaining The remaining value we have left to trade
/// @param totalObtained The total amount we have obtained so far
/// @param orders Struct containing all DEX orders
/// @param index Value indicating the index of the specific DEX order we wish to execute
/// @return Remaining value left after trade
/// @return Total value obtained after trade
function performTrade(bool buyOrSell, uint256 initialRemaining, uint256 totalObtained, DEXOrders orders, uint256 index)
internal returns (uint256, uint256) {
uint256 obtained = 0;
uint256 remaining = initialRemaining;
require(orders.exchangeFees[index] < MAX_EXCHANGE_FEE_PERCENTAGE);
uint256 amountToFill = getAmountToFill(remaining, orders, index);
if(amountToFill > 0) {
remaining = SafeMath.sub(remaining, amountToFill);
if(buyOrSell == BUY) {
obtained = ExchangeHandler(orders.exchanges[index]).performBuy.value(amountToFill)(
orders.orderAddresses[index],
orders.orderValues[index],
orders.exchangeFees[index],
amountToFill,
orders.v[index],
orders.r[index],
orders.s[index]
);
} else {
require(Token(orders.tokenForOrder[index]).transfer(
orders.exchanges[index],
amountToFill
));
obtained = ExchangeHandler(orders.exchanges[index]).performSell(
orders.orderAddresses[index],
orders.orderValues[index],
orders.exchangeFees[index],
amountToFill,
orders.v[index],
orders.r[index],
orders.s[index]
);
}
}
return (obtained == 0 ? initialRemaining: remaining, SafeMath.add(totalObtained, obtained));
}
/// @dev Get the amount of this order we are able to fill
/// @param remaining Amount we have left to spend
/// @param orders Struct containing all DEX orders
/// @param index Value indicating the index of the specific DEX order we wish to execute
/// @return Minimum of the amount we have left to spend and the available amount at the exchange
function getAmountToFill(uint256 remaining, DEXOrders orders, uint256 index) internal returns (uint256) {
uint256 availableAmount = ExchangeHandler(orders.exchanges[index]).getAvailableAmount(
orders.orderAddresses[index],
orders.orderValues[index],
orders.exchangeFees[index],
orders.v[index],
orders.r[index],
orders.s[index]
);
return Math.min256(remaining, availableAmount);
}
/// @dev Checks whether a given order was valid
/// @param amountObtained Amount of the order which was obtained
/// @param amountGiven Amount given in return for amountObtained
/// @param amountToObtain Amount we intended to obtain
/// @param amountToGive Amount we intended to give in return for amountToObtain
/// @return Boolean value indicating whether this order was valid
function orderWasValid(uint256 amountObtained, uint256 amountGiven, uint256 amountToObtain, uint256 amountToGive) internal pure returns (bool) {
if(amountObtained > 0 && amountGiven > 0) {
// NOTE - Check the edge cases here
if(amountObtained > amountGiven) {
return SafeMath.div(amountToObtain, amountToGive) <= SafeMath.div(amountObtained, amountGiven);
} else {
return SafeMath.div(amountToGive, amountToObtain) >= SafeMath.div(amountGiven, amountObtained);
}
}
return false;
}
function() public payable {
// Check in here that the sender is a contract! (to stop accidents)
uint256 size;
address sender = msg.sender;
assembly {
size := extcodesize(sender)
}
require(size > 0);
}
} | Make sure we have will have enough ETH after SELLs to cover our BUYs | require(expectedEtherAvailable >= totalEtherNeeded);
| 7,912,454 | [
1,
6464,
3071,
732,
1240,
903,
1240,
7304,
512,
2455,
1839,
20853,
48,
87,
358,
5590,
3134,
10937,
61,
87,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2583,
12,
3825,
41,
1136,
5268,
1545,
2078,
41,
1136,
11449,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/utils/Counters.sol
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
// 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);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// 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);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// 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);
}
// File: @openzeppelin/contracts/interfaces/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)
pragma solidity ^0.8.0;
// File: @openzeppelin/contracts/interfaces/IERC2981.sol
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/IERC2981.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface for the NFT Royalty Standard.
*
* A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
* support for royalty payments across all NFT marketplaces and ecosystem participants.
*
* _Available since v4.5._
*/
interface IERC2981 is IERC165 {
/**
* @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
* exchange. The royalty amount is denominated and should be payed in that same unit of exchange.
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: contracts/StandWithUkraine.sol
pragma solidity 0.8.4;
contract WeStandWithUkraine is ERC721, Ownable, IERC2981 {
using Strings for uint256;
using Counters for Counters.Counter;
using SafeERC20 for IERC20;
Counters.Counter private supply;
string private contractUri;
uint256 public maxSupply = 10;
uint256 public cost = 0.5 ether;
uint256 public maxMintAmount = 3;
string public baseURI;
string public baseExtension = ".json";
event RoyaltiesReceived(
address indexed _royaltyRecipient,
address indexed _buyer,
uint256 indexed _tokenId,
address _tokenPaid,
uint256 _amount,
bytes32 _metadata
);
constructor(string memory initBaseURI, string memory initContractUri)
ERC721("We Stand With Ukraine", "WSWU")
{
contractUri = initContractUri;
baseURI = initBaseURI;
}
/**
* @notice get contract uri
* @return contract uri
*/
function contractURI() external view returns (string memory) {
return contractUri;
}
/**
* @notice get token uri
* @param tokenId token id to get uri
* @return token uri
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(_exists(tokenId), "URI query for nonexistent token");
string memory currentBaseURI = _baseURI();
return
bytes(currentBaseURI).length > 0
? string(
abi.encodePacked(
currentBaseURI,
tokenId.toString(),
baseExtension
)
)
: "";
}
/**
* @notice mint tokens
* @param amount qty to mint
*/
function mint(uint256 amount) external payable {
require(amount > 0, "Mint amount should be > 0");
require(amount <= maxMintAmount, "Max mint amount overflow");
require(supply.current() + amount <= maxSupply, "Max supply overflow");
require(msg.value == cost * amount, "Wrong ETH amount");
for (uint256 i = 1; i <= amount; i++) {
supply.increment();
uint256 newTokenId = supply.current();
_mint(msg.sender, newTokenId);
}
}
/**
* @notice mint tokens by owner
* @param amount qty to mint
* @dev callable only by contract owner
*/
function mintWithOwner(uint256 amount) external onlyOwner {
require(maxSupply > supply.current(), "Max supply is reached");
if (maxSupply - supply.current() > amount) {
for (uint256 i = 1; i <= amount; i++) {
supply.increment();
uint256 newTokenId = supply.current();
_mint(owner(), newTokenId);
}
} else {
for (uint256 i = 1; i <= maxSupply - supply.current(); i++) {
supply.increment();
uint256 newTokenId = supply.current();
_mint(owner(), newTokenId);
}
}
}
/**
* @notice get total supply
* @return total supply of tokens
*/
function totalSupply() external view returns (uint256) {
return supply.current();
}
/**
* @notice get account tokens
* @param _owner account adderess to get tokens for
* @return array of tokens
*/
function tokensOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount);
uint256 currentTokenId = 1;
uint256 ownedTokenIndex = 0;
while (
ownedTokenIndex < ownerTokenCount &&
currentTokenId <= supply.current()
) {
address currentTokenOwner = ownerOf(currentTokenId);
if (currentTokenOwner == _owner) {
ownedTokenIds[ownedTokenIndex] = currentTokenId;
ownedTokenIndex++;
}
currentTokenId++;
}
return ownedTokenIds;
}
/**
* @notice update contract uri
* @param newURI new contract uri
* @dev callable only by contract owner
*/
function setContractURI(string memory newURI) external onlyOwner {
contractUri = newURI;
}
/**
* @notice update base uri
* @param newBaseURI new base uri
* @dev callable only by contract owner
*/
function setBaseURI(string memory newBaseURI) public onlyOwner {
baseURI = newBaseURI;
}
/**
* @notice update base extension
* @param newBaseExtension new base extension
* @dev callable only by contract owner
*/
function setBaseExtension(string memory newBaseExtension) public onlyOwner {
baseExtension = newBaseExtension;
}
/**
* @notice update max supply
* @param newMaxSupply new max supply
* @dev callable only by contract owner
*/
function setMaxSupply(uint256 newMaxSupply) external onlyOwner {
maxSupply = newMaxSupply;
}
/**
* @notice update mint cost
* @param newCost new cost to mint
* @dev callable only by contract owner
*/
function setCost(uint256 newCost) external onlyOwner {
cost = newCost;
}
/**
* @notice update max mint amount
* @param newMaxMintAmount new max mint amount
* @dev callable only by contract owner
*/
function setMaxMintAmount(uint256 newMaxMintAmount) external onlyOwner {
maxMintAmount = newMaxMintAmount;
}
/**
* @notice get base uri, internal
*/
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
/**
* @notice withdraw ETH
* @dev callable only by contract owner
*/
function withdraw() external onlyOwner {
require(
payable(msg.sender).send(address(this).balance),
"Can not withdraw"
);
}
/**
* @notice check if contract supports interface id
* @param interfaceId interface Id
* @dev callable only by contract owner
*/
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, IERC165)
returns (bool)
{
return
interfaceId == type(IERC2981).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @notice Returns royalty reciever address and royalty amount
* @param _tokenId Token Id
* @param _salePrice Value to calculate royalty from
* @return receiver Royalty reciever address
* @return amount Royalty amount
*/
function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
external
view
override
returns (address receiver, uint256 amount)
{
require(_tokenId > 0, "Query for nonexistent token");
receiver = this.owner();
if (_salePrice <= 10000) {
amount = 0;
} else {
amount = (_salePrice * 1000) / 10000;
}
}
/**
* @notice Calls when royalty recieved
*/
function onRoyaltiesReceived(
address _royaltyRecipient,
address _buyer,
uint256 _tokenId,
address _tokenPaid,
uint256 _amount,
bytes32 _metadata
) external returns (bytes4) {
emit RoyaltiesReceived(
_royaltyRecipient,
_buyer,
_tokenId,
_tokenPaid,
_amount,
_metadata
);
return
bytes4(
keccak256(
"onRoyaltiesReceived(address,address,uint256,address,uint256,bytes32)"
)
);
}
/**
* @notice It allows the admins to get tokens sent to the contract
* @param tokenAddress: the address of the token to withdraw
* @param tokenAmount: the number of token amount to withdraw
* @dev Only callable by contract owner.
*/
function recoverTokens(address tokenAddress, uint256 tokenAmount) external onlyOwner {
require(tokenAddress != address(0), "address can not be zero!");
IERC20(tokenAddress).safeTransfer(address(msg.sender), tokenAmount);
}
} | * @notice withdraw ETH @dev callable only by contract owner/ | function withdraw() external onlyOwner {
require(
payable(msg.sender).send(address(this).balance),
"Can not withdraw"
);
}
| 14,670,112 | [
1,
1918,
9446,
512,
2455,
225,
4140,
1338,
635,
6835,
3410,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1435,
3903,
1338,
5541,
288,
203,
3639,
2583,
12,
203,
5411,
8843,
429,
12,
3576,
18,
15330,
2934,
4661,
12,
2867,
12,
2211,
2934,
12296,
3631,
203,
5411,
315,
2568,
486,
598,
9446,
6,
203,
3639,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/421613/0xd206B4f8992B87E489E141DbCC26A6007484c379/sources/src/Games/Race.sol | @notice Resolves the bet using the Chainlink randomness. @param _id The bet ID. @param _randomNumbers Random numbers list. Contains only one for this game.*/Generate a Pseudo Random number between 50 and 99 transaction & nft manage | function _callback(
uint256 _id,
uint256[] calldata _randomNumbers
) external {
require(
msg.sender == address(supraRouter),
"only supra router can call this function"
);
uint256 _raceId = randIdToRaceId[_id];
Race storage race = races[_raceId];
require(race.isDone == false, "race is already done");
race.isDone = true;
Logic for determining the winner
uint256 maxSpeed = 0;
uint32 winnerSpeed;
uint16 winnerIndex;
uint256 winnerTokenId;
uint256 numOfPlayers = race.playerTokenIds.length;
uint256 betUnit = race.betUnit;
for (uint16 i = 0; i < uint16(numOfPlayers); i++) {
uint256 tokenId = race.playerTokenIds[i];
uint256 level = nftManager.getLevel(tokenId);
uint32 randomGen = 50 + uint32(_randomNumbers[i] % (99 - 50 + 1));
uint32 playerSpeed = randomGen + uint32(level) * 3;
if (playerSpeed > maxSpeed) {
maxSpeed = playerSpeed;
winnerSpeed = playerSpeed;
winnerIndex = i;
}
}
winnerTokenId = race.playerTokenIds[winnerIndex];
race.winnerTokenId = winnerTokenId;
race.endTime = block.timestamp;
uint256 fee = _getFees(numOfPlayers * betUnit);
uint256 betAmountFee = _getFees(betUnit);
address winnerAddress = pachi721.ownerOf(winnerTokenId);
uint256 totalInput = numOfPlayers * betUnit;
address _token = race.token;
bool isGasToken = _token == address(0);
uint256[] memory playerIds = race.playerTokenIds;
if (isGasToken) {
(bool sent, ) = payable(address(bank)).call{
value: totalInput - betUnit
}("");
require(sent, "Failed to send Ether");
IERC20(_token).safeTransfer(address(bank), totalInput - betUnit);
}
for (uint16 i = 0; i < uint16(numOfPlayers); i++) {
nftManager.updatePendingStatus(playerIds[i], false);
if (i == winnerIndex) {
if (isGasToken) {
(bool sent, ) = payable(winnerAddress).call{
value: betUnit - betAmountFee
}("");
require(sent, "Failed to send Ether");
IERC20(_token).safeTransfer(
winnerAddress,
betUnit - betAmountFee
}
winnerAddress,
_token,
betAmountFee
);
nftManager.writeMatchResult(playerIds[i], true);
continue;
bank.cashIn(
pachi721.ownerOf(playerIds[i]),
_token,
0,
betAmountFee
);
nftManager.writeMatchResult(playerIds[i], false);
}
}
removeOpenRace(_raceId);
_raceId,
race.endTime,
winnerTokenId,
totalInput - fee,
playerIds
);
}
| 11,582,588 | [
1,
17453,
326,
2701,
1450,
326,
7824,
1232,
2744,
4496,
18,
225,
389,
350,
1021,
2701,
1599,
18,
225,
389,
9188,
10072,
8072,
5600,
666,
18,
8398,
1338,
1245,
364,
333,
7920,
18,
19,
4625,
279,
453,
9091,
8072,
1300,
3086,
6437,
471,
14605,
2492,
473,
290,
1222,
10680,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
3394,
12,
203,
3639,
2254,
5034,
389,
350,
16,
203,
3639,
2254,
5034,
8526,
745,
892,
389,
9188,
10072,
203,
565,
262,
3903,
288,
203,
3639,
2583,
12,
203,
5411,
1234,
18,
15330,
422,
1758,
12,
2859,
354,
8259,
3631,
203,
5411,
315,
3700,
1169,
354,
4633,
848,
745,
333,
445,
6,
203,
3639,
11272,
203,
3639,
2254,
5034,
389,
9963,
548,
273,
5605,
28803,
54,
623,
548,
63,
67,
350,
15533,
203,
3639,
534,
623,
2502,
17996,
273,
767,
764,
63,
67,
9963,
548,
15533,
203,
3639,
2583,
12,
9963,
18,
291,
7387,
422,
629,
16,
315,
9963,
353,
1818,
2731,
8863,
203,
3639,
17996,
18,
291,
7387,
273,
638,
31,
203,
203,
5411,
10287,
364,
23789,
326,
5657,
1224,
203,
3639,
2254,
5034,
943,
16562,
273,
374,
31,
203,
3639,
2254,
1578,
5657,
1224,
16562,
31,
203,
3639,
2254,
2313,
5657,
1224,
1016,
31,
203,
3639,
2254,
5034,
5657,
1224,
1345,
548,
31,
203,
3639,
2254,
5034,
23153,
1749,
3907,
273,
17996,
18,
14872,
1345,
2673,
18,
2469,
31,
203,
3639,
2254,
5034,
2701,
2802,
273,
17996,
18,
70,
278,
2802,
31,
203,
203,
3639,
364,
261,
11890,
2313,
277,
273,
374,
31,
277,
411,
2254,
2313,
12,
2107,
951,
1749,
3907,
1769,
277,
27245,
288,
203,
5411,
2254,
5034,
1147,
548,
273,
17996,
18,
14872,
1345,
2673,
63,
77,
15533,
203,
5411,
2254,
5034,
1801,
273,
290,
1222,
1318,
18,
588,
2355,
12,
2316,
548,
1769,
203,
203,
5411,
2254,
1578,
2744,
7642,
273,
6437,
397,
2254,
1578,
2
] |
pragma solidity ^0.4.24;
contract POOHMOevents {
// fired whenever a player registers a name
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
// fired at end of buy or reload
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 POOHAmount,
uint256 genAmount,
uint256 potAmount
);
// fired whenever theres a withdraw
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
// fired whenever a withdraw forces end round to be ran
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 POOHAmount,
uint256 genAmount
);
// fired whenever a player tries a buy after round timer
// hit zero, and causes end round to be ran.
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 POOHAmount,
uint256 genAmount
);
// fired whenever a player tries a reload after round timer
// hit zero, and causes end round to be ran.
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 POOHAmount,
uint256 genAmount
);
// fired whenever an affiliate is paid
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
// received pot swap deposit
event onPotSwapDeposit
(
uint256 roundID,
uint256 amountAddedToPot
);
}
//==============================================================================
// _ _ _ _|_ _ _ __|_ _ _ _|_ _ .
// (_(_)| | | | (_|(_ | _\(/_ | |_||_) .
//====================================|=========================================
contract POOHMO is POOHMOevents {
using SafeMath for *;
using NameFilter for string;
using KeysCalc for uint256;
PlayerBookInterface private PlayerBook;
//==============================================================================
// _ _ _ |`. _ _ _ |_ | _ _ .
// (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings)
//=================_|===========================================================
address private admin = msg.sender;
address private flushDivs;
string constant public name = "POOHMO";
string constant public symbol = "POOHMO";
uint256 private rndExtra_ = 1 minutes; // length of the very first ICO
uint256 private rndGap_ = 1 minutes; // length of ICO phase, set to 1 year for EOS.
uint256 private rndInit_ = 30 minutes; // round timer starts at this
uint256 constant private rndInc_ = 10 seconds; // every full key purchased adds this much to the timer
uint256 private rndMax_ = 6 hours; // max length a round timer can be
uint256[6] private timerLengths = [30 minutes,60 minutes,120 minutes,360 minutes,720 minutes,1440 minutes];
//==============================================================================
// _| _ _|_ _ _ _ _|_ _ .
// (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes)
//=============================|================================================
uint256 public rID_; // round id number / total rounds that have happened
//****************
// PLAYER DATA
//****************
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => POOHMODatasets.Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (uint256 => POOHMODatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own)
//****************
// ROUND DATA
//****************
mapping (uint256 => POOHMODatasets.Round) public round_; // (rID => data) round data
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id
//****************
// TEAM FEE DATA
//****************
mapping (uint256 => POOHMODatasets.TeamFee) public fees_; // (team => fees) fee distribution by team
mapping (uint256 => POOHMODatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team
//==============================================================================
// _ _ _ __|_ _ __|_ _ _ .
// (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy)
//==============================================================================
constructor(address whaleContract, address playerbook)
public
{
flushDivs = whaleContract;
PlayerBook = PlayerBookInterface(playerbook);
//no teams... only POOH-heads
// Referrals / Community rewards are mathematically designed to come from the winner's share of the pot.
fees_[0] = POOHMODatasets.TeamFee(47,10); //30% to pot, 10% to aff, 2% to com, 1% potSwap
potSplit_[0] = POOHMODatasets.PotSplit(15,10); //48% to winner, 25% to next round, 2% to com
}
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (these are safety checks)
//==============================================================================
/**
* @dev used to make sure no one can interact with contract until it has
* been activated.
*/
modifier isActivated() {
require(activated_ == true);
_;
}
/**
* @dev prevents contracts from interacting with fomo3d
*/
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0);
require(_addr == tx.origin);
_;
}
/**
* @dev sets boundaries for incoming tx
*/
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000);
require(_eth <= 100000000000000000000000);
_;
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)
//====|=========================================================================
/**
* @dev emergency buy uses last stored affiliate ID
*/
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
POOHMODatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// buy core
buyCore(_pID, plyr_[_pID].laff, _eventData_);
}
/**
* @dev converts all incoming ethereum to keys.
* -functionhash- 0x8f38f309 (using ID for affiliate)
* -functionhash- 0x98a0871d (using address for affiliate)
* -functionhash- 0xa65b37a1 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
*/
function buyXid(uint256 _affCode)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
POOHMODatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// buy core
buyCore(_pID, _affCode, _eventData_);
}
function buyXaddr(address _affCode)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
POOHMODatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// buy core
buyCore(_pID, _affID, _eventData_);
}
function buyXname(bytes32 _affCode)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
POOHMODatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// buy core
buyCore(_pID, _affID, _eventData_);
}
/**
* @dev essentially the same as buy, but instead of you sending ether
* from your wallet, it uses your unwithdrawn earnings.
* -functionhash- 0x349cdcac (using ID for affiliate)
* -functionhash- 0x82bfc739 (using address for affiliate)
* -functionhash- 0x079ce327 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _eth amount of earnings to use (remainder returned to gen vault)
*/
function reLoadXid(uint256 _affCode, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
POOHMODatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// reload core
reLoadCore(_pID, _affCode, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
POOHMODatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// reload core
reLoadCore(_pID, _affID, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
POOHMODatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// reload core
reLoadCore(_pID, _affID, _eth, _eventData_);
}
/**
* @dev withdraws all of your earnings.
* -functionhash- 0x3ccfd60b
*/
function withdraw()
isActivated()
isHuman()
public
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// setup temp var for player eth
uint256 _eth;
// check to see if round has ended and no one has run round end yet
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// set up our tx event data
POOHMODatasets.EventReturns memory _eventData_;
// end the round (distributes pot)
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire withdraw and distribute event
emit POOHMOevents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.POOHAmount,
_eventData_.genAmount
);
// in any other situation
} else {
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// fire withdraw event
emit POOHMOevents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
/**
* @dev use these to register names. they are just wrappers that will send the
* registration requests to the PlayerBook contract. So registering here is the
* same as registering there. UI will always display the last name you registered.
* but you will still own all previously registered names to use as affiliate
* links.
* - must pay a registration fee.
* - name must be unique
* - names will be converted to lowercase
* - name cannot start or end with a space
* - cannot have more than 1 space in a row
* - cannot be only numbers
* - cannot start with 0x
* - name must be at least 1 char
* - max length of 32 characters long
* - allowed characters: a-z, 0-9, and space
* -functionhash- 0x921dec21 (using ID for affiliate)
* -functionhash- 0x3ddd4698 (using address for affiliate)
* -functionhash- 0x685ffd83 (using name for affiliate)
* @param _nameString players desired name
* @param _affCode affiliate ID, address, or name of who referred you
* @param _all set to true if you want this to push your info to all games
* (this might cost a lot of gas)
*/
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit POOHMOevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit POOHMOevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit POOHMOevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
//==============================================================================
// _ _ _|__|_ _ _ _ .
// (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan)
//=====_|=======================================================================
/**
* @dev return the price buyer will pay for next 1 individual key.
* -functionhash- 0x018a25e8
* @return price for next key bought (in wei format)
*/
function getBuyPrice()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else // rounds over. need price for new round
return ( 75000000000000 ); // init
}
/**
* @dev returns time left. dont spam this, you'll ddos yourself from your node
* provider
* -functionhash- 0xc7e284b8
* @return time left in seconds
*/
function getTimeLeft()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt + rndGap_)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt + rndGap_).sub(_now) );
else
return(0);
}
/**
* @dev returns player earnings per vaults
* -functionhash- 0x63066434
* @return winnings vault
* @return general vault
* @return affiliate vault
*/
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
// if round has ended. but round end has not been run (so contract has not distributed winnings)
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// if player is winner
if (round_[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
// if player is not the winner
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
}
// if round is still going on, or round has ended and round end has been ran
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff
);
}
}
/**
* solidity hates stack limits. this lets us avoid that hate
*/
function getPlayerVaultsHelper(uint256 _pID, uint256 _rID)
private
view
returns(uint256)
{
return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) );
}
/**
* @dev returns all current round info needed for front end
* -functionhash- 0x747dff42
* @return eth invested during ICO phase
* @return round id
* @return total keys for round
* @return time round ends
* @return time round started
* @return current pot
* @return current team ID & player ID in lead
* @return current player in leads address
* @return current player in leads name
* @return whales eth in for round
* @return bears eth in for round
* @return sneks eth in for round
* @return bulls eth in for round
* @return airdrop tracker # & airdrop pot
*/
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
return
(
round_[_rID].ico, //0
_rID, //1
round_[_rID].keys, //2
round_[_rID].end, //3
round_[_rID].strt, //4
round_[_rID].pot, //5
(round_[_rID].team + (round_[_rID].plyr * 10)), //6
plyr_[round_[_rID].plyr].addr, //7
plyr_[round_[_rID].plyr].name, //8
rndTmEth_[_rID][0], //9
rndTmEth_[_rID][1], //10
rndTmEth_[_rID][2], //11
rndTmEth_[_rID][3] //12
);
}
/**
* @dev returns player info based on address. if no address is given, it will
* use msg.sender
* -functionhash- 0xee0b5d8b
* @param _addr address of the player you want to lookup
* @return player ID
* @return player name
* @return keys owned (current round)
* @return winnings vault
* @return general vault
* @return affiliate vault
* @return player round eth
*/
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID, //0
plyr_[_pID].name, //1
plyrRnds_[_pID][_rID].keys, //2
plyr_[_pID].win, //3
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4
plyr_[_pID].aff, //5
plyrRnds_[_pID][_rID].eth //6
);
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine)
//=====================_|=======================================================
/**
* @dev logic runs whenever a buy order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function buyCore(uint256 _pID, uint256 _affID, POOHMODatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// call core
core(_rID, _pID, msg.value, _affID, 0, _eventData_);
// if round is not active
} else {
// check to see if end round needs to be ran
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit POOHMOevents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.POOHAmount,
_eventData_.genAmount
);
}
// put eth in players vault
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
/**
* @dev logic runs whenever a reload order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _eth, POOHMODatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// get earnings from all vaults and return unused to gen vault
// because we use a custom safemath library. this will throw if player
// tried to spend more eth than they have.
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
// call core
core(_rID, _pID, _eth, _affID, 0, _eventData_);
// if round is not active and end round needs to be ran
} else if (_now > round_[_rID].end && round_[_rID].ended == false) {
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit POOHMOevents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.POOHAmount,
_eventData_.genAmount
);
}
}
/**
* @dev this is the core logic for any buy/reload that happens while a round
* is live.
*/
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, POOHMODatasets.EventReturns memory _eventData_)
private
{
// if player is new to round
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
// early round eth limiter
if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 5000000000000000000)
{
uint256 _availableLimit = (5000000000000000000).sub(plyrRnds_[_pID][_rID].eth);
uint256 _refund = _eth.sub(_availableLimit);
plyr_[_pID].gen = plyr_[_pID].gen.add(_refund);
_eth = _availableLimit;
}
// if eth left is greater than min eth allowed (sorry no pocket lint)
if (_eth > 1000000000)
{
// mint the new keys
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
// if they bought at least 1 whole key
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID);
// set new leaders
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
// set the new leader bool to true
_eventData_.compressedData = _eventData_.compressedData + 100;
}
// update player
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
// update round
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
rndTmEth_[_rID][0] = _eth.add(rndTmEth_[_rID][0]);
// distribute eth
_eventData_ = distributeExternal(_rID, _pID, _eth, _affID, 0, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, 0, _keys, _eventData_);
// call end tx function to fire end tx event.
endTx(_pID, 0, _eth, _keys, _eventData_);
}
}
//==============================================================================
// _ _ | _ | _ _|_ _ _ _ .
// (_(_||(_|_||(_| | (_)| _\ .
//==============================================================================
/**
* @dev calculates unmasked earnings (just calculates, does not update mask)
* @return earnings in wei format
*/
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
}
/**
* @dev returns the amount of keys you would get given an amount of eth.
* -functionhash- 0xce89c80c
* @param _rID round ID you want price for
* @param _eth amount of eth sent in
* @return keys received
*/
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns(uint256)
{
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].eth).keysRec(_eth) );
else // rounds over. need keys for new round
return ( (_eth).keys() );
}
/**
* @dev returns current eth price for X keys.
* -functionhash- 0xcf808000
* @param _keys number of keys desired (in 18 decimal format)
* @return amount of eth needed to send
*/
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );
else // rounds over. need price for new round
return ( (_keys).eth() );
}
//==============================================================================
// _|_ _ _ | _ .
// | (_)(_)|_\ .
//==============================================================================
/**
* @dev receives name/player info from names contract
*/
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(PlayerBook));
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev receives entire player name list
*/
function receivePlayerNameList(uint256 _pID, bytes32 _name)
external
{
require (msg.sender == address(PlayerBook));
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev gets existing or registers new pID. use this when a player may be new
* @return pID
*/
function determinePID(POOHMODatasets.EventReturns memory _eventData_)
private
returns (POOHMODatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
// if player is new to this version of fomo3d
if (_pID == 0)
{
// grab their player ID, name and last aff ID, from player names contract
_pID = PlayerBook.getPlayerID(msg.sender);
bytes32 _name = PlayerBook.getPlayerName(_pID);
uint256 _laff = PlayerBook.getPlayerLAff(_pID);
// set up player account
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if (_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
// set the new player bool to true
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
/**
* @dev decides if round end needs to be run & new round started. and if
* player unmasked earnings from previously played rounds need to be moved.
*/
function managePlayer(uint256 _pID, POOHMODatasets.EventReturns memory _eventData_)
private
returns (POOHMODatasets.EventReturns)
{
// if player has played a previous round, move their unmasked earnings
// from that round to gen vault.
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
// update player's last round played
plyr_[_pID].lrnd = rID_;
// set the joined round bool to true
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
/**
* @dev ends the round. manages paying out winner/splitting up pot
*/
function endRound(POOHMODatasets.EventReturns memory _eventData_)
private
returns (POOHMODatasets.EventReturns)
{
// setup local rID
uint256 _rID = rID_;
// grab our winning player and team id's
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
// grab our pot amount
uint256 _pot = round_[_rID].pot;
// calculate our winner share, community rewards, gen share,
// p3d share, and amount reserved for next pot
uint256 _win = (_pot.mul(48)) / 100; //48%
uint256 _dev = (_pot / 50); //2%
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
uint256 _POOH = (_pot.mul(potSplit_[_winTID].pooh)) / 100;
uint256 _res = (((_pot.sub(_win)).sub(_dev)).sub(_gen)).sub(_POOH);
// calculate ppt for round mask
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
// pay our winner
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
// community rewards
admin.transfer(_dev);
flushDivs.transfer((_POOH.sub(_POOH / 3)).mul(2)); // 2/3
round_[_rID].pot = _pot.add(_POOH / 3); // 1/3
// distribute gen portion to key holders
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// prepare event data
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.POOHAmount = _POOH;
_eventData_.newPot = _res;
// start next round
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(timerLengths[determineNextRoundLength()]);
round_[_rID].pot = _res;
rndMax_ = round_[_rID].end;
return(_eventData_);
}
function determineNextRoundLength() internal view returns(uint256 time)
{
uint256 roundTime = uint256(keccak256(abi.encodePacked(blockhash(block.number - 1)))) % 6;
return roundTime;
}
/**
* @dev moves any unmasked earnings to gen vault. updates earnings mask
*/
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
// put in gen vault
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
// zero out their earnings by updating mask
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
/**
* @dev updates round timer based on number of whole keys bought.
*/
function updateTimer(uint256 _keys, uint256 _rID)
private
{
// grab time
uint256 _now = now;
// calculate time based on number of keys bought
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
// compare to max and set new end time
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
/**
* @dev distributes eth based on fees to com, aff, and pooh
*/
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, POOHMODatasets.EventReturns memory _eventData_)
private
returns(POOHMODatasets.EventReturns)
{
// pay 1% out to dev
uint256 _dev = _eth / 100; // 1%
uint256 _POOH;
if (!address(admin).call.value(_dev)())
{
_POOH = _dev;
_dev = 0;
}
// distribute share to affiliate
uint256 _aff = _eth / 10;
// decide what to do with affiliate share of fees
// affiliate must not be self, and must have a name registered
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit POOHMOevents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
} else {
_POOH = _aff;
}
// pay out POOH
_POOH = _POOH.add((_eth.mul(fees_[_team].pooh)) / (100));
if (_POOH > 0)
{
// deposit to divies contract
uint256 _potAmount = _POOH / 2;
flushDivs.transfer(_POOH.sub(_potAmount));
round_[_rID].pot = round_[_rID].pot.add(_potAmount);
// set up event data
_eventData_.POOHAmount = _POOH.add(_eventData_.POOHAmount);
}
return(_eventData_);
}
function potSwap()
external
payable
{
// setup local rID
uint256 _rID = rID_ + 1;
round_[_rID].pot = round_[_rID].pot.add(msg.value);
emit POOHMOevents.onPotSwapDeposit(_rID, msg.value);
}
/**
* @dev distributes eth based on fees to gen and pot
*/
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, POOHMODatasets.EventReturns memory _eventData_)
private
returns(POOHMODatasets.EventReturns)
{
// calculate gen share
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
// update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share))
_eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].pooh)) / 100));
// calculate pot
uint256 _pot = _eth.sub(_gen);
// distribute gen share (thats what updateMasks() does) and adjust
// balances for dust.
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
// add eth to pot
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
// set up event data
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
/**
* @dev updates masks for round and player when keys are bought
* @return dust left over
*/
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
/* MASKING NOTES
earnings masks are a tricky thing for people to wrap their minds around.
the basic thing to understand here. is were going to have a global
tracker based on profit per share for each round, that increases in
relevant proportion to the increase in share supply.
the player will have an additional mask that basically says "based
on the rounds mask, my shares, and how much i've already withdrawn,
how much is still owed to me?"
*/
// calc profit per key & round mask based on this buy: (dust goes to pot)
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// calculate player earning from their own buy (only based on the keys
// they just bought). & update player earnings mask
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
// calculate & return dust
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
/**
* @dev adds up unmasked earnings, & vault earnings, sets them all to 0
* @return earnings in wei format
*/
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
// update gen vault
updateGenVault(_pID, plyr_[_pID].lrnd);
// from vaults
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
/**
* @dev prepares compression data and fires event for buy or reload tx's
*/
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, POOHMODatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit POOHMOevents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.POOHAmount,
_eventData_.genAmount,
_eventData_.potAmount
);
}
//==============================================================================
// (~ _ _ _._|_ .
// _)(/_(_|_|| | | \/ .
//====================/=========================================================
/** upon contract deploy, it will be deactivated. this is a one time
* use function that will activate the contract. we do this so devs
* have time to set things up on the web end **/
bool public activated_ = false;
function activate()
public
{
// only team just can activate
require(msg.sender == admin);
// can only be ran once
require(activated_ == false);
// activate the contract
activated_ = true;
// lets start first round
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
}
//==============================================================================
// __|_ _ __|_ _ .
// _\ | | |_|(_ | _\ .
//==============================================================================
library POOHMODatasets {
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr; // winner address
bytes32 winnerName; // winner name
uint256 amountWon; // amount won
uint256 newPot; // amount in new pot
uint256 POOHAmount; // amount distributed to p3d
uint256 genAmount; // amount distributed to gen
uint256 potAmount; // amount added to pot
}
struct Player {
address addr; // player address
bytes32 name; // player name
uint256 win; // winnings vault
uint256 gen; // general vault
uint256 aff; // affiliate vault
uint256 lrnd; // last round played
uint256 laff; // last affiliate id used
}
struct PlayerRounds {
uint256 eth; // eth player has added to round (used for eth limiter)
uint256 keys; // keys
uint256 mask; // player mask
uint256 ico; // ICO phase investment
}
struct Round {
uint256 plyr; // pID of player in lead
uint256 team; // tID of team in lead
uint256 end; // time ends/ended
bool ended; // has round end function been ran
uint256 strt; // time round started
uint256 keys; // keys
uint256 eth; // total eth in
uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends)
uint256 mask; // global mask
uint256 ico; // total eth sent in during ICO phase
uint256 icoGen; // total eth for gen during ICO phase
uint256 icoAvg; // average key price for ICO phase
}
struct TeamFee {
uint256 gen; // % of buy in thats paid to key holders of current round
uint256 pooh; // % of buy in thats paid to POOH holders
}
struct PotSplit {
uint256 gen; // % of pot thats paid to key holders of current round
uint256 pooh; // % of pot thats paid to POOH holders
}
}
//==============================================================================
// | _ _ _ | _ .
// |<(/_\/ (_(_||(_ .
//=======/======================================================================
library KeysCalc {
using SafeMath for *;
/**
* @dev calculates number of keys received given X eth
* @param _curEth current amount of eth in contract
* @param _newEth eth being spent
* @return amount of ticket purchased
*/
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
/**
* @dev calculates amount of eth received if you sold X keys
* @param _curKeys current amount of keys that exist
* @param _sellKeys amount of keys you wish to sell
* @return amount of eth received
*/
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
/**
* @dev calculates how many keys would exist with given an amount of eth
* @param _eth eth "in contract"
* @return number of keys that would exist
*/
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000);
}
/**
* @dev calculates how much eth would be in contract given a number of keys
* @param _keys number of keys "in contract"
* @return eth that would exists
*/
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
//==============================================================================
// . _ _|_ _ _ |` _ _ _ _ .
// || | | (/_| ~|~(_|(_(/__\ .
//==============================================================================
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
library NameFilter {
/**
* @dev filters name strings
* -converts uppercase to lower case.
* -makes sure it does not start/end with a space
* -makes sure it does not contain multiple spaces in a row
* -cannot be only numbers
* -cannot start with 0x
* -restricts characters to A-Z, a-z, 0-9, and space.
* @return reprocessed string in bytes32 format
*/
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//sorry limited to 32 characters
require (_length <= 32 && _length > 0);
// make sure it doesnt start with or end with space
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20);
// make sure first two characters are not 0x
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78);
require(_temp[1] != 0x58);
}
// create a bool to track if we have a non number character
bool _hasNonNumber;
// convert & check
for (uint256 i = 0; i < _length; i++)
{
// if its uppercase A-Z
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
// convert to lower case a-z
_temp[i] = byte(uint(_temp[i]) + 32);
// we have a non number
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
// require character is a space
_temp[i] == 0x20 ||
// OR lowercase a-z
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
// or 0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a));
// make sure theres not 2x spaces in a row
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20);
// see if we have a character other than a number
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true);
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
/**
* @title SafeMath v0.1.9
* @dev Math operations with safety checks that throw on error
* change notes: original SafeMath library from OpenZeppelin modified by Inventor
* - added sqrt
* - added sq
* - added pwr
* - changed asserts to requires with error log outputs
* - removed div, its useless
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
} | no teams... only POOH-heads Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. | {
flushDivs = whaleContract;
PlayerBook = PlayerBookInterface(playerbook);
}
| 9,997,467 | [
1,
2135,
21475,
2777,
1338,
13803,
51,
44,
17,
20263,
3941,
370,
1031,
342,
16854,
13352,
283,
6397,
854,
4233,
351,
2126,
1230,
26584,
358,
12404,
628,
326,
5657,
1224,
1807,
7433,
434,
326,
5974,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
288,
203,
3639,
3663,
7244,
87,
273,
600,
5349,
8924,
31,
203,
3639,
19185,
9084,
273,
19185,
9084,
1358,
12,
14872,
3618,
1769,
203,
203,
3639,
203,
203,
202,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2020-11-04
*/
// File: contracts\modules\Ownable.sol
pragma solidity =0.5.16;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address internal _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts\modules\Managerable.sol
pragma solidity =0.5.16;
contract Managerable is Ownable {
address private _managerAddress;
/**
* @dev modifier, Only manager can be granted exclusive access to specific functions.
*
*/
modifier onlyManager() {
require(_managerAddress == msg.sender,"Managerable: caller is not the Manager");
_;
}
/**
* @dev set manager by owner.
*
*/
function setManager(address managerAddress)
public
onlyOwner
{
_managerAddress = managerAddress;
}
/**
* @dev get manager address.
*
*/
function getManager()public view returns (address) {
return _managerAddress;
}
}
// File: contracts\modules\Halt.sol
pragma solidity =0.5.16;
contract Halt is Ownable {
bool private halted ; //inject UNINIT LOCAL/STATE VAR
modifier notHalted() {
require(!halted,"This contract is halted");
_;
}
modifier isHalted() {
require(halted,"This contract is not halted");
_;
}
/// @notice function Emergency situation that requires
/// @notice contribution period to stop or not.
function setHalt(bool halt)
public
onlyOwner
{
halted = halt;
}
}
// File: contracts\modules\whiteList.sol
pragma solidity =0.5.16;
/**
* @dev Implementation of a whitelist which filters a eligible uint32.
*/
library whiteListUint32 {
/**
* @dev add uint32 into white list.
* @param whiteList the storage whiteList.
* @param temp input value
*/
function addWhiteListUint32(uint32[] storage whiteList,uint32 temp) internal{
if (!isEligibleUint32(whiteList,temp)){
whiteList.push(temp);
}
}
/**
* @dev remove uint32 from whitelist.
*/
function removeWhiteListUint32(uint32[] storage whiteList,uint32 temp)internal returns (bool) {
uint256 len ; //inject UNINIT LOCAL/STATE VAR
uint256 i; //inject UNINIT LOCAL/STATE VAR
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
if (i<len){
if (i!=len-1) {
whiteList[i] = whiteList[len-1];
}
whiteList.length--;
return true;
}
return false;
}
function isEligibleUint32(uint32[] memory whiteList,uint32 temp) internal pure returns (bool){
uint256 len ; //inject UNINIT LOCAL/STATE VAR
for (uint256 i;i<len;i++){ //inject UNINIT LOCAL/STATE VAR
if (whiteList[i] == temp)
return true;
}
return false;
}
function _getEligibleIndexUint32(uint32[] memory whiteList,uint32 temp) internal pure returns (uint256){
uint256 len ; //inject UNINIT LOCAL/STATE VAR
uint256 i; //inject UNINIT LOCAL/STATE VAR
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
return i;
}
}
/**
* @dev Implementation of a whitelist which filters a eligible uint256.
*/
library whiteListUint256 {
// add whiteList
function addWhiteListUint256(uint256[] storage whiteList,uint256 temp) internal{
if (!isEligibleUint256(whiteList,temp)){
whiteList.push(temp);
}
}
function removeWhiteListUint256(uint256[] storage whiteList,uint256 temp)internal returns (bool) {
uint256 len ; //inject UNINIT LOCAL/STATE VAR
uint256 i; //inject UNINIT LOCAL/STATE VAR
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
if (i<len){
if (i!=len-1) {
whiteList[i] = whiteList[len-1];
}
whiteList.length--;
return true;
}
return false;
}
function isEligibleUint256(uint256[] memory whiteList,uint256 temp) internal pure returns (bool){
uint256 len ; //inject UNINIT LOCAL/STATE VAR
for (uint256 i;i<len;i++){ //inject UNINIT LOCAL/STATE VAR
if (whiteList[i] == temp)
return true;
}
return false;
}
function _getEligibleIndexUint256(uint256[] memory whiteList,uint256 temp) internal pure returns (uint256){
uint256 len ; //inject UNINIT LOCAL/STATE VAR
uint256 i; //inject UNINIT LOCAL/STATE VAR
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
return i;
}
}
/**
* @dev Implementation of a whitelist which filters a eligible address.
*/
library whiteListAddress {
// add whiteList
function addWhiteListAddress(address[] storage whiteList,address temp) internal{
if (!isEligibleAddress(whiteList,temp)){
whiteList.push(temp);
}
}
function removeWhiteListAddress(address[] storage whiteList,address temp)internal returns (bool) {
uint256 len ; //inject UNINIT LOCAL/STATE VAR
uint256 i; //inject UNINIT LOCAL/STATE VAR
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
if (i<len){
if (i!=len-1) {
whiteList[i] = whiteList[len-1];
}
whiteList.length--;
return true;
}
return false;
}
function isEligibleAddress(address[] memory whiteList,address temp) internal pure returns (bool){
uint256 len ; //inject UNINIT LOCAL/STATE VAR
for (uint256 i;i<len;i++){ //inject UNINIT LOCAL/STATE VAR
if (whiteList[i] == temp)
return true;
}
return false;
}
function _getEligibleIndexAddress(address[] memory whiteList,address temp) internal pure returns (uint256){
uint256 len ; //inject UNINIT LOCAL/STATE VAR
uint256 i; //inject UNINIT LOCAL/STATE VAR
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
return i;
}
}
// File: contracts\modules\AddressWhiteList.sol
pragma solidity =0.5.16;
/**
* @dev Implementation of a whitelist filters a eligible address.
*/
contract AddressWhiteList is Halt {
using whiteListAddress for address[];
uint256 constant internal allPermission = 0xffffffff;
uint256 constant internal allowBuyOptions = 1;
uint256 constant internal allowSellOptions = 1<<1;
uint256 constant internal allowExerciseOptions = 1<<2;
uint256 constant internal allowAddCollateral = 1<<3;
uint256 constant internal allowRedeemCollateral = 1<<4;
// The eligible adress list
address[] internal whiteList;
mapping(address => uint256) internal addressPermission;
/**
* @dev Implementation of add an eligible address into the whitelist.
* @param addAddress new eligible address.
*/
function addWhiteList(address addAddress)public onlyOwner{
whiteList.addWhiteListAddress(addAddress);
addressPermission[addAddress] = allPermission;
}
function modifyPermission(address addAddress,uint256 permission)public onlyOwner{
addressPermission[addAddress] = permission;
}
/**
* @dev Implementation of revoke an invalid address from the whitelist.
* @param removeAddress revoked address.
*/
function removeWhiteList(address removeAddress)public onlyOwner returns (bool){
addressPermission[removeAddress] = 0;
return whiteList.removeWhiteListAddress(removeAddress);
}
/**
* @dev Implementation of getting the eligible whitelist.
*/
function getWhiteList()public view returns (address[] memory){
return whiteList;
}
/**
* @dev Implementation of testing whether the input address is eligible.
* @param tmpAddress input address for testing.
*/
function isEligibleAddress(address tmpAddress) public view returns (bool){
return whiteList.isEligibleAddress(tmpAddress);
}
function checkAddressPermission(address tmpAddress,uint256 state) public view returns (bool){
return (addressPermission[tmpAddress]&state) == state;
}
}
// File: contracts\modules\ReentrancyGuard.sol
pragma solidity =0.5.16;
contract ReentrancyGuard {
/**
* @dev We use a single lock for the whole contract.
*/
bool private reentrancyLock ; //inject UNINIT LOCAL/STATE VAR
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* @notice If you mark a function `nonReentrant`, you should also
* mark it `external`. Calling one nonReentrant function from
* another is not supported. Instead, you can implement a
* `private` function doing the actual work, and a `external`
* wrapper marked as `nonReentrant`.
*/
modifier nonReentrant() {
require(!reentrancyLock);
reentrancyLock = true;
_;
reentrancyLock = false;
}
}
// File: contracts\FNXMinePool\MinePoolData.sol
pragma solidity =0.5.16;
/**
* @title FPTCoin mine pool, which manager contract is FPTCoin.
* @dev A smart-contract which distribute some mine coins by FPTCoin balance.
*
*/
contract MinePoolData is Managerable,AddressWhiteList,ReentrancyGuard {
//Special decimals for calculation
uint256 constant calDecimals = 1e18;
// miner's balance
// map mineCoin => user => balance
mapping(address=>mapping(address=>uint256)) internal minerBalances;
// miner's origins, specially used for mine distribution
// map mineCoin => user => balance
mapping(address=>mapping(address=>uint256)) internal minerOrigins;
// mine coins total worth, specially used for mine distribution
mapping(address=>uint256) internal totalMinedWorth;
// total distributed mine coin amount
mapping(address=>uint256) internal totalMinedCoin;
// latest time to settlement
mapping(address=>uint256) internal latestSettleTime;
//distributed mine amount
mapping(address=>uint256) internal mineAmount;
//distributed time interval
mapping(address=>uint256) internal mineInterval;
//distributed mine coin amount for buy options user.
mapping(address=>uint256) internal buyingMineMap;
// user's Opterator indicator
uint256 constant internal opBurnCoin = 1;
uint256 constant internal opMintCoin = 2;
uint256 constant internal opTransferCoin = 3;
/**
* @dev Emitted when `account` mint `amount` miner shares.
*/
event MintMiner(address indexed account,uint256 amount);
/**
* @dev Emitted when `account` burn `amount` miner shares.
*/
event BurnMiner(address indexed account,uint256 amount);
/**
* @dev Emitted when `from` redeem `value` mineCoins.
*/
event RedeemMineCoin(address indexed from, address indexed mineCoin, uint256 value);
/**
* @dev Emitted when `from` transfer to `to` `amount` mineCoins.
*/
event TranserMiner(address indexed from, address indexed to, uint256 amount);
/**
* @dev Emitted when `account` buying options get `amount` mineCoins.
*/
event BuyingMiner(address indexed account,address indexed mineCoin,uint256 amount);
}
// File: contracts\Proxy\baseProxy.sol
pragma solidity =0.5.16;
/**
* @title baseProxy Contract
*/
contract baseProxy is Ownable {
address public implementation;
constructor(address implementation_) public {
// Creator of the contract is admin during initialization
implementation = implementation_;
(bool success,) = implementation_.delegatecall(abi.encodeWithSignature("initialize()"));
require(success);
}
function getImplementation()public view returns(address){
return implementation;
}
function setImplementation(address implementation_)public onlyOwner{
implementation = implementation_;
(bool success,) = implementation_.delegatecall(abi.encodeWithSignature("update()"));
require(success);
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
(bool success, bytes memory returnData) = implementation.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
function delegateToViewAndReturn() internal view returns (bytes memory) {
(bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(add(free_mem_ptr, 0x40), returndatasize) }
}
}
function delegateAndReturn() internal returns (bytes memory) {
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
}
// File: contracts\FNXMinePool\MinePoolProxy.sol
pragma solidity =0.5.16;
/**
* @title FPTCoin mine pool, which manager contract is FPTCoin.
* @dev A smart-contract which distribute some mine coins by FPTCoin balance.
*
*/
contract MinePoolProxy is MinePoolData,baseProxy {
constructor (address implementation_) baseProxy(implementation_) public{
}
/**
* @dev default function for foundation input miner coins.
*/
function()external payable{
}
/**
* @dev foundation redeem out mine coins.
* mineCoin mineCoin address
* amount redeem amount.
*/
function redeemOut(address /*mineCoin*/,uint256 /*amount*/)public{
delegateAndReturn();
}
/**
* @dev retrieve total distributed mine coins.
* mineCoin mineCoin address
*/
function getTotalMined(address /*mineCoin*/)public view returns(uint256){
delegateToViewAndReturn();
}
/**
* @dev retrieve minecoin distributed informations.
* mineCoin mineCoin address
* @return distributed amount and distributed time interval.
*/
function getMineInfo(address /*mineCoin*/)public view returns(uint256,uint256){
delegateToViewAndReturn();
}
/**
* @dev retrieve user's mine balance.
* account user's account
* mineCoin mineCoin address
*/
function getMinerBalance(address /*account*/,address /*mineCoin*/)public view returns(uint256){
delegateToViewAndReturn();
}
/**
* @dev Set mineCoin mine info, only foundation owner can invoked.
* mineCoin mineCoin address
* _mineAmount mineCoin distributed amount
* _mineInterval mineCoin distributied time interval
*/
function setMineCoinInfo(address /*mineCoin*/,uint256 /*_mineAmount*/,uint256 /*_mineInterval*/)public {
delegateAndReturn();
}
/**
* @dev Set the reward for buying options.
* mineCoin mineCoin address
* _mineAmount mineCoin reward amount
*/
function setBuyingMineInfo(address /*mineCoin*/,uint256 /*_mineAmount*/)public {
delegateAndReturn();
}
/**
* @dev Get the reward for buying options.
* mineCoin mineCoin address
*/
function getBuyingMineInfo(address /*mineCoin*/)public view returns(uint256){
delegateToViewAndReturn();
}
/**
* @dev Get the all rewards for buying options.
*/
function getBuyingMineInfoAll()public view returns(address[] memory,uint256[] memory){
delegateToViewAndReturn();
}
/**
* @dev transfer mineCoin to recieptor when account transfer amount FPTCoin to recieptor, only manager contract can modify database.
* account the account transfer from
* recieptor the account transfer to
* amount the mine shared amount
*/
function transferMinerCoin(address /*account*/,address /*recieptor*/,uint256 /*amount*/) public {
delegateAndReturn();
}
/**
* @dev mint mineCoin to account when account add collateral to collateral pool, only manager contract can modify database.
* account user's account
* amount the mine shared amount
*/
function mintMinerCoin(address /*account*/,uint256 /*amount*/) public {
delegateAndReturn();
}
/**
* @dev Burn mineCoin to account when account redeem collateral to collateral pool, only manager contract can modify database.
* account user's account
* amount the mine shared amount
*/
function burnMinerCoin(address /*account*/,uint256 /*amount*/) public {
delegateAndReturn();
}
/**
* @dev give amount buying reward to account, only manager contract can modify database.
* account user's account
* amount the buying shared amount
*/
function addMinerBalance(address /*account*/,uint256 /*amount*/) public {
delegateAndReturn();
}
/**
* @dev changer mine coin distributed amount , only foundation owner can modify database.
* mineCoin mine coin address
* _mineAmount the distributed amount.
*/
function setMineAmount(address /*mineCoin*/,uint256 /*_mineAmount*/)public {
delegateAndReturn();
}
/**
* @dev changer mine coin distributed time interval , only foundation owner can modify database.
* mineCoin mine coin address
* _mineInterval the distributed time interval.
*/
function setMineInterval(address /*mineCoin*/,uint256 /*_mineInterval*/)public {
delegateAndReturn();
}
/**
* @dev user redeem mine rewards.
* mineCoin mine coin address
* amount redeem amount.
*/
function redeemMinerCoin(address /*mineCoin*/,uint256 /*amount*/)public{
delegateAndReturn();
}
} | * @dev retrieve minecoin distributed informations. mineCoin mineCoin address @return distributed amount and distributed time interval./ | function getMineInfo(address /*mineCoin*/)public view returns(uint256,uint256){
delegateToViewAndReturn();
}
| 991,495 | [
1,
17466,
1131,
557,
885,
16859,
26978,
18,
225,
312,
558,
27055,
312,
558,
27055,
1758,
327,
16859,
3844,
471,
16859,
813,
3673,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2108,
558,
966,
12,
2867,
1748,
3081,
27055,
5549,
13,
482,
1476,
1135,
12,
11890,
5034,
16,
11890,
5034,
15329,
203,
3639,
7152,
774,
1767,
1876,
990,
5621,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
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";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "./GovernanceToken.sol";
import "./Authorizable.sol";
// MasterSupplier is the master supplier of whatever supplier the GovernanceToken represents.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once GovernanceToken is sufficiently
// distributed and the community can show to govern itself.
//
contract MasterSupplier is Ownable, Authorizable, ReentrancyGuard {
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.
uint256 rewardDebtAtBlock; // the last block user stake
uint256 lastWithdrawBlock; // the last block a user withdrew at.
uint256 firstDepositBlock; // the last block a user deposited at.
uint256 blockdelta; //time passed since withdrawals
uint256 lastDepositBlock;
//
// We do some fancy math here. Basically, any point in time, the amount of GovernanceTokens
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accGovTokenPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accGovTokenPerShare` (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.
}
struct UserGlobalInfo {
uint256 globalAmount;
mapping(address => uint256) referrals;
uint256 totalReferals;
uint256 globalRefAmount;
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. GovernanceTokens to distribute per block.
uint256 lastRewardBlock; // Last block number that GovernanceTokens distribution occurs.
uint256 accGovTokenPerShare; // Accumulated GovernanceTokens per share, times 1e12. See below.
}
// The Governance token
GovernanceToken public govToken;
//An ETH/USDC Oracle (Chainlink)
address public usdOracle;
// Dev address.
address public devaddr;
// LP address
address public liquidityaddr;
// Community Fund Address
address public comfundaddr;
// Founder Reward
address public founderaddr;
// GovernanceTokens created per block.
uint256 public REWARD_PER_BLOCK;
// Bonus muliplier for early GovernanceToken makers.
uint256[] public REWARD_MULTIPLIER; // init in constructor function
uint256[] public HALVING_AT_BLOCK; // init in constructor function
uint256[] public blockDeltaStartStage;
uint256[] public blockDeltaEndStage;
uint256[] public userFeeStage;
uint256[] public devFeeStage;
uint256 public FINISH_BONUS_AT_BLOCK;
uint256 public userDepFee;
uint256 public devDepFee;
// The block number when GovernanceToken mining starts.
uint256 public START_BLOCK;
uint256 public PERCENT_LOCK_BONUS_REWARD; // lock xx% of bounus reward in 3 year
uint256 public PERCENT_FOR_DEV; // dev bounties + partnerships
uint256 public PERCENT_FOR_LP; // LP fund
uint256 public PERCENT_FOR_COM; // community fund
uint256 public PERCENT_FOR_FOUNDERS; // founders fund
// Info of each pool.
PoolInfo[] public poolInfo;
mapping(address => uint256) public poolId1; // poolId1 count from 1, subtraction 1 before using with poolInfo
// Info of each user that stakes LP tokens. pid => user address => info
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
mapping(address => UserGlobalInfo) public userGlobalInfo;
mapping(IERC20 => bool) public poolExistence;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
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
);
event SendGovernanceTokenReward(
address indexed user,
uint256 indexed pid,
uint256 amount,
uint256 lockAmount
);
modifier nonDuplicated(IERC20 _lpToken) {
require(poolExistence[_lpToken] == false, "MasterSupplier::nonDuplicated: duplicated");
_;
}
constructor(
GovernanceToken _govToken,
address _devaddr,
address _liquidityaddr,
address _comfundaddr,
address _founderaddr,
uint256 _rewardPerBlock,
uint256 _startBlock,
uint256 _halvingAfterBlock,
uint256 _userDepFee,
uint256 _devDepFee,
uint256[] memory _rewardMultiplier,
uint256[] memory _blockDeltaStartStage,
uint256[] memory _blockDeltaEndStage,
uint256[] memory _userFeeStage,
uint256[] memory _devFeeStage
) public {
govToken = _govToken;
devaddr = _devaddr;
liquidityaddr = _liquidityaddr;
comfundaddr = _comfundaddr;
founderaddr = _founderaddr;
REWARD_PER_BLOCK = _rewardPerBlock;
START_BLOCK = _startBlock;
userDepFee = _userDepFee;
devDepFee = _devDepFee;
REWARD_MULTIPLIER = _rewardMultiplier;
blockDeltaStartStage = _blockDeltaStartStage;
blockDeltaEndStage = _blockDeltaEndStage;
userFeeStage = _userFeeStage;
devFeeStage = _devFeeStage;
for (uint256 i = 0; i < REWARD_MULTIPLIER.length - 1; i++) {
uint256 halvingAtBlock = _halvingAfterBlock.mul(i+1).add(_startBlock).add(1);
HALVING_AT_BLOCK.push(halvingAtBlock);
}
FINISH_BONUS_AT_BLOCK = _halvingAfterBlock
.mul(REWARD_MULTIPLIER.length - 1)
.add(_startBlock);
HALVING_AT_BLOCK.push(uint256(-1));
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
function add(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner nonDuplicated(_lpToken) {
require(
poolId1[address(_lpToken)] == 0,
"MasterSupplier::add: lp is already in pool"
);
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock =
block.number > START_BLOCK ? block.number : START_BLOCK;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolId1[address(_lpToken)] = poolInfo.length + 1;
poolExistence[_lpToken] = true;
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accGovTokenPerShare: 0
})
);
}
// Update the given pool's GovernanceToken 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;
}
// Update reward variables 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 GovTokenForDev;
uint256 GovTokenForFarmer;
uint256 GovTokenForLP;
uint256 GovTokenForCom;
uint256 GovTokenForFounders;
(
GovTokenForDev,
GovTokenForFarmer,
GovTokenForLP,
GovTokenForCom,
GovTokenForFounders
) = getPoolReward(pool.lastRewardBlock, block.number, pool.allocPoint);
govToken.mint(address(this), GovTokenForFarmer);
pool.accGovTokenPerShare = pool.accGovTokenPerShare.add(
GovTokenForFarmer.mul(1e12).div(lpSupply)
);
pool.lastRewardBlock = block.number;
if (GovTokenForDev > 0) {
govToken.mint(address(devaddr), GovTokenForDev);
//Dev fund has xx% locked during the starting bonus period. After which locked funds drip out linearly each block over 3 years.
if (block.number <= FINISH_BONUS_AT_BLOCK) {
govToken.lock(address(devaddr), GovTokenForDev.mul(75).div(100));
}
}
if (GovTokenForLP > 0) {
govToken.mint(liquidityaddr, GovTokenForLP);
//LP + Partnership fund has only xx% locked over time as most of it is needed early on for incentives and listings. The locked amount will drip out linearly each block after the bonus period.
if (block.number <= FINISH_BONUS_AT_BLOCK) {
govToken.lock(address(liquidityaddr), GovTokenForLP.mul(45).div(100));
}
}
if (GovTokenForCom > 0) {
govToken.mint(comfundaddr, GovTokenForCom);
//Community Fund has xx% locked during bonus period and then drips out linearly over 3 years.
if (block.number <= FINISH_BONUS_AT_BLOCK) {
govToken.lock(address(comfundaddr), GovTokenForCom.mul(85).div(100));
}
}
if (GovTokenForFounders > 0) {
govToken.mint(founderaddr, GovTokenForFounders);
//The Founders reward has xx% of their funds locked during the bonus period which then drip out linearly per block over 3 years.
if (block.number <= FINISH_BONUS_AT_BLOCK) {
govToken.lock(address(founderaddr), GovTokenForFounders.mul(95).div(100));
}
}
}
// |--------------------------------------|
// [20, 30, 40, 50, 60, 70, 80, 99999999]
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to)
public
view
returns (uint256)
{
uint256 result = 0;
if (_from < START_BLOCK) return 0;
for (uint256 i = 0; i < HALVING_AT_BLOCK.length; i++) {
uint256 endBlock = HALVING_AT_BLOCK[i];
if (i > REWARD_MULTIPLIER.length-1) return 0;
if (_to <= endBlock) {
uint256 m = _to.sub(_from).mul(REWARD_MULTIPLIER[i]);
return result.add(m);
}
if (_from < endBlock) {
uint256 m = endBlock.sub(_from).mul(REWARD_MULTIPLIER[i]);
_from = endBlock;
result = result.add(m);
}
}
return result;
}
function getPoolReward(
uint256 _from,
uint256 _to,
uint256 _allocPoint
)
public
view
returns (
uint256 forDev,
uint256 forFarmer,
uint256 forLP,
uint256 forCom,
uint256 forFounders
)
{
uint256 multiplier = getMultiplier(_from, _to);
uint256 amount =
multiplier.mul(REWARD_PER_BLOCK).mul(_allocPoint).div(
totalAllocPoint
);
uint256 GovernanceTokenCanMint = govToken.cap().sub(govToken.totalSupply());
if (GovernanceTokenCanMint < amount) {
forDev = 0;
forFarmer = GovernanceTokenCanMint;
forLP = 0;
forCom = 0;
forFounders = 0;
} else {
forDev = amount.mul(PERCENT_FOR_DEV).div(100);
forFarmer = amount;
forLP = amount.mul(PERCENT_FOR_LP).div(100);
forCom = amount.mul(PERCENT_FOR_COM).div(100);
forFounders = amount.mul(PERCENT_FOR_FOUNDERS).div(100);
}
}
// View function to see pending GovernanceTokens on frontend.
function pendingReward(uint256 _pid, address _user)
external
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accGovTokenPerShare = pool.accGovTokenPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply > 0) {
uint256 GovTokenForFarmer;
(, GovTokenForFarmer, , , ) = getPoolReward(
pool.lastRewardBlock,
block.number,
pool.allocPoint
);
accGovTokenPerShare = accGovTokenPerShare.add(
GovTokenForFarmer.mul(1e12).div(lpSupply)
);
}
return user.amount.mul(accGovTokenPerShare).div(1e12).sub(user.rewardDebt);
}
function claimRewards(uint256[] memory _pids) public {
for (uint256 i = 0; i < _pids.length; i++) {
claimReward(_pids[i]);
}
}
function claimReward(uint256 _pid) public {
updatePool(_pid);
_harvest(_pid);
}
// lock 95% of reward if it comes from bonus time
function _harvest(uint256 _pid) internal {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if (user.amount > 0) {
uint256 pending =
user.amount.mul(pool.accGovTokenPerShare).div(1e12).sub(
user.rewardDebt
);
uint256 masterBal = govToken.balanceOf(address(this));
if (pending > masterBal) {
pending = masterBal;
}
if (pending > 0) {
govToken.transfer(msg.sender, pending);
uint256 lockAmount = 0;
if (user.rewardDebtAtBlock <= FINISH_BONUS_AT_BLOCK) {
lockAmount = pending.mul(PERCENT_LOCK_BONUS_REWARD).div(
100
);
govToken.lock(msg.sender, lockAmount);
}
user.rewardDebtAtBlock = block.number;
emit SendGovernanceTokenReward(msg.sender, _pid, pending, lockAmount);
}
user.rewardDebt = user.amount.mul(pool.accGovTokenPerShare).div(1e12);
}
}
function getGlobalAmount(address _user) public view returns (uint256) {
UserGlobalInfo memory current = userGlobalInfo[_user];
return current.globalAmount;
}
function getGlobalRefAmount(address _user) public view returns (uint256) {
UserGlobalInfo memory current = userGlobalInfo[_user];
return current.globalRefAmount;
}
function getTotalRefs(address _user) public view returns (uint256) {
UserGlobalInfo memory current = userGlobalInfo[_user];
return current.totalReferals;
}
function getRefValueOf(address _user, address _user2)
public
view
returns (uint256)
{
UserGlobalInfo storage current = userGlobalInfo[_user];
uint256 a = current.referrals[_user2];
return a;
}
// Deposit LP tokens to MasterSupplier for GovernanceToken allocation.
function deposit(
uint256 _pid,
uint256 _amount,
address _ref
) public nonReentrant {
require(
_amount > 0,
"MasterSupplier::deposit: amount must be greater than 0"
);
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
UserInfo storage devr = userInfo[_pid][devaddr];
UserGlobalInfo storage refer = userGlobalInfo[_ref];
UserGlobalInfo storage current = userGlobalInfo[msg.sender];
if (refer.referrals[msg.sender] > 0) {
refer.referrals[msg.sender] = refer.referrals[msg.sender] + _amount;
refer.globalRefAmount = refer.globalRefAmount + _amount;
} else {
refer.referrals[msg.sender] = refer.referrals[msg.sender] + _amount;
refer.totalReferals = refer.totalReferals + 1;
refer.globalRefAmount = refer.globalRefAmount + _amount;
}
current.globalAmount =
current.globalAmount +
_amount.mul(userDepFee).div(100);
updatePool(_pid);
_harvest(_pid);
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
if (user.amount == 0) {
user.rewardDebtAtBlock = block.number;
}
user.amount = user.amount.add(
_amount.sub(_amount.mul(userDepFee).div(10000))
);
user.rewardDebt = user.amount.mul(pool.accGovTokenPerShare).div(1e12);
devr.amount = devr.amount.add(
_amount.sub(_amount.mul(devDepFee).div(10000))
);
devr.rewardDebt = devr.amount.mul(pool.accGovTokenPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
if (user.firstDepositBlock > 0) {} else {
user.firstDepositBlock = block.number;
}
user.lastDepositBlock = block.number;
}
// Withdraw LP tokens from MasterSupplier.
function withdraw(
uint256 _pid,
uint256 _amount,
address _ref
) public nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
UserGlobalInfo storage refer = userGlobalInfo[_ref];
UserGlobalInfo storage current = userGlobalInfo[msg.sender];
require(user.amount >= _amount, "MasterSupplier::withdraw: not good");
if (_ref != address(0)) {
refer.referrals[msg.sender] = refer.referrals[msg.sender] - _amount;
refer.globalRefAmount = refer.globalRefAmount - _amount;
}
current.globalAmount = current.globalAmount - _amount;
updatePool(_pid);
_harvest(_pid);
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
if (user.lastWithdrawBlock > 0) {
user.blockdelta = block.number - user.lastWithdrawBlock;
} else {
user.blockdelta = block.number - user.firstDepositBlock;
}
if (
user.blockdelta == blockDeltaStartStage[0] ||
block.number == user.lastDepositBlock
) {
//25% fee for withdrawals of LP tokens in the same block this is to prevent abuse from flashloans
pool.lpToken.safeTransfer(
address(msg.sender),
_amount.mul(userFeeStage[0]).div(100)
);
pool.lpToken.safeTransfer(
address(devaddr),
_amount.mul(devFeeStage[0]).div(100)
);
} else if (
user.blockdelta >= blockDeltaStartStage[1] &&
user.blockdelta <= blockDeltaEndStage[0]
) {
//8% fee if a user deposits and withdraws in between same block and 59 minutes.
pool.lpToken.safeTransfer(
address(msg.sender),
_amount.mul(userFeeStage[1]).div(100)
);
pool.lpToken.safeTransfer(
address(devaddr),
_amount.mul(devFeeStage[1]).div(100)
);
} else if (
user.blockdelta >= blockDeltaStartStage[2] &&
user.blockdelta <= blockDeltaEndStage[1]
) {
//4% fee if a user deposits and withdraws after 1 hour but before 1 day.
pool.lpToken.safeTransfer(
address(msg.sender),
_amount.mul(userFeeStage[2]).div(100)
);
pool.lpToken.safeTransfer(
address(devaddr),
_amount.mul(devFeeStage[2]).div(100)
);
} else if (
user.blockdelta >= blockDeltaStartStage[3] &&
user.blockdelta <= blockDeltaEndStage[2]
) {
//2% fee if a user deposits and withdraws between after 1 day but before 3 days.
pool.lpToken.safeTransfer(
address(msg.sender),
_amount.mul(userFeeStage[3]).div(100)
);
pool.lpToken.safeTransfer(
address(devaddr),
_amount.mul(devFeeStage[3]).div(100)
);
} else if (
user.blockdelta >= blockDeltaStartStage[4] &&
user.blockdelta <= blockDeltaEndStage[3]
) {
//1% fee if a user deposits and withdraws after 3 days but before 5 days.
pool.lpToken.safeTransfer(
address(msg.sender),
_amount.mul(userFeeStage[4]).div(100)
);
pool.lpToken.safeTransfer(
address(devaddr),
_amount.mul(devFeeStage[4]).div(100)
);
} else if (
user.blockdelta >= blockDeltaStartStage[5] &&
user.blockdelta <= blockDeltaEndStage[4]
) {
//0.5% fee if a user deposits and withdraws if the user withdraws after 5 days but before 2 weeks.
pool.lpToken.safeTransfer(
address(msg.sender),
_amount.mul(userFeeStage[5]).div(1000)
);
pool.lpToken.safeTransfer(
address(devaddr),
_amount.mul(devFeeStage[5]).div(1000)
);
} else if (
user.blockdelta >= blockDeltaStartStage[6] &&
user.blockdelta <= blockDeltaEndStage[5]
) {
//0.25% fee if a user deposits and withdraws after 2 weeks.
pool.lpToken.safeTransfer(
address(msg.sender),
_amount.mul(userFeeStage[6]).div(10000)
);
pool.lpToken.safeTransfer(
address(devaddr),
_amount.mul(devFeeStage[6]).div(10000)
);
} else if (user.blockdelta > blockDeltaStartStage[7]) {
//0.1% fee if a user deposits and withdraws after 4 weeks.
pool.lpToken.safeTransfer(
address(msg.sender),
_amount.mul(userFeeStage[7]).div(10000)
);
pool.lpToken.safeTransfer(
address(devaddr),
_amount.mul(devFeeStage[7]).div(10000)
);
}
user.rewardDebt = user.amount.mul(pool.accGovTokenPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
user.lastWithdrawBlock = block.number;
}
}
// Withdraw without caring about rewards. EMERGENCY ONLY. This has the same 25% fee as same block withdrawals to prevent abuse of thisfunction.
function emergencyWithdraw(uint256 _pid) public nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
//reordered from Sushi function to prevent risk of reentrancy
uint256 amountToSend = user.amount.mul(75).div(100);
uint256 devToSend = user.amount.mul(25).div(100);
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), amountToSend);
pool.lpToken.safeTransfer(address(devaddr), devToSend);
emit EmergencyWithdraw(msg.sender, _pid, amountToSend);
}
// Safe GovToken transfer function, just in case if rounding error causes pool to not have enough GovTokens.
function safeGovTokenTransfer(address _to, uint256 _amount) internal {
uint256 govTokenBal = govToken.balanceOf(address(this));
bool transferSuccess = false;
if (_amount > govTokenBal) {
transferSuccess = govToken.transfer(_to, govTokenBal);
} else {
transferSuccess = govToken.transfer(_to, _amount);
}
require(transferSuccess, "MasterSupplier::safeGovTokenTransfer: transfer failed");
}
// Update dev address by the previous dev.
function dev(address _devaddr) public onlyAuthorized {
devaddr = _devaddr;
}
// Update Finish Bonus Block
function bonusFinishUpdate(uint256 _newFinish) public onlyAuthorized {
FINISH_BONUS_AT_BLOCK = _newFinish;
}
// Update Halving At Block
function halvingUpdate(uint256[] memory _newHalving) public onlyAuthorized {
HALVING_AT_BLOCK = _newHalving;
}
// Update Liquidityaddr
function lpUpdate(address _newLP) public onlyAuthorized {
liquidityaddr = _newLP;
}
// Update comfundaddr
function comUpdate(address _newCom) public onlyAuthorized {
comfundaddr = _newCom;
}
// Update founderaddr
function founderUpdate(address _newFounder) public onlyAuthorized {
founderaddr = _newFounder;
}
// Update Reward Per Block
function rewardUpdate(uint256 _newReward) public onlyAuthorized {
REWARD_PER_BLOCK = _newReward;
}
// Update Rewards Mulitplier Array
function rewardMulUpdate(uint256[] memory _newMulReward)
public
onlyAuthorized
{
REWARD_MULTIPLIER = _newMulReward;
}
// Update % lock for general users
function lockUpdate(uint256 _newlock) public onlyAuthorized {
PERCENT_LOCK_BONUS_REWARD = _newlock;
}
// Update % lock for dev
function lockdevUpdate(uint256 _newdevlock) public onlyAuthorized {
PERCENT_FOR_DEV = _newdevlock;
}
// Update % lock for LP
function locklpUpdate(uint256 _newlplock) public onlyAuthorized {
PERCENT_FOR_LP = _newlplock;
}
// Update % lock for COM
function lockcomUpdate(uint256 _newcomlock) public onlyAuthorized {
PERCENT_FOR_COM = _newcomlock;
}
// Update % lock for Founders
function lockfounderUpdate(uint256 _newfounderlock) public onlyAuthorized {
PERCENT_FOR_FOUNDERS = _newfounderlock;
}
// Update START_BLOCK
function starblockUpdate(uint256 _newstarblock) public onlyAuthorized {
START_BLOCK = _newstarblock;
}
function getNewRewardPerBlock(uint256 pid1) public view returns (uint256) {
uint256 multiplier = getMultiplier(block.number - 1, block.number);
if (pid1 == 0) {
return multiplier.mul(REWARD_PER_BLOCK);
} else {
return
multiplier
.mul(REWARD_PER_BLOCK)
.mul(poolInfo[pid1 - 1].allocPoint)
.div(totalAllocPoint);
}
}
function userDelta(uint256 _pid) public view returns (uint256) {
UserInfo storage user = userInfo[_pid][msg.sender];
if (user.lastWithdrawBlock > 0) {
uint256 estDelta = block.number - user.lastWithdrawBlock;
return estDelta;
} else {
uint256 estDelta = block.number - user.firstDepositBlock;
return estDelta;
}
}
function reviseWithdraw(
uint256 _pid,
address _user,
uint256 _block
) public onlyAuthorized() {
UserInfo storage user = userInfo[_pid][_user];
user.lastWithdrawBlock = _block;
}
function reviseDeposit(
uint256 _pid,
address _user,
uint256 _block
) public onlyAuthorized() {
UserInfo storage user = userInfo[_pid][_user];
user.firstDepositBlock = _block;
}
function setStageStarts(uint256[] memory _blockStarts)
public
onlyAuthorized()
{
blockDeltaStartStage = _blockStarts;
}
function setStageEnds(uint256[] memory _blockEnds) public onlyAuthorized() {
blockDeltaEndStage = _blockEnds;
}
function setUserFeeStage(uint256[] memory _userFees)
public
onlyAuthorized()
{
userFeeStage = _userFees;
}
function setDevFeeStage(uint256[] memory _devFees) public onlyAuthorized() {
devFeeStage = _devFees;
}
function setDevDepFee(uint256 _devDepFees) public onlyAuthorized() {
devDepFee = _devDepFees;
}
function setUserDepFee(uint256 _usrDepFees) public onlyAuthorized() {
userDepFee = _usrDepFees;
}
function reclaimTokenOwnership(address _newOwner) public onlyAuthorized() {
govToken.transferOwnership(_newOwner);
}
}
| Update % lock for general users | function lockUpdate(uint256 _newlock) public onlyAuthorized {
PERCENT_LOCK_BONUS_REWARD = _newlock;
}
| 2,502,243 | [
1,
1891,
738,
2176,
364,
7470,
3677,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2176,
1891,
12,
11890,
5034,
389,
2704,
739,
13,
1071,
1338,
15341,
288,
203,
3639,
10950,
19666,
67,
6589,
67,
38,
673,
3378,
67,
862,
21343,
273,
389,
2704,
739,
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
] |
./partial_match/1/0xc38387eB262574Da5f7429819AB811162C913ab2/sources/contracts/admin/AvoConfigV1.sol | @dev This is an auxiliary contract used to set up immutable config values of Avocado contracts at deployment without influencing deterministic address (constructor args). Once values have been set up correctly, owner could `renounceOwnership`. Expected owner is AvoMultisigAdmin contract. | contract AvoConfigV1 is Ownable {
pragma solidity >=0.8.18;
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
struct AvocadoMultisigConfig {
uint256 authorizedMinFee;
uint256 authorizedMaxFee;
address authorizedFeeCollector;
}
struct AvoDepositManagerConfig {
address depositToken;
}
struct AvoSignersListConfig {
bool trackInStorage;
}
event ConfigSet(
AvocadoMultisigConfig avocadoMultisigConfig,
AvoDepositManagerConfig avoDepositManagerConfig,
AvoSignersListConfig avoSignersListConfig
);
error AvoConfig__InvalidConfig();
AvocadoMultisigConfig public avocadoMultisigConfig;
AvoDepositManagerConfig public avoDepositManagerConfig;
AvoSignersListConfig public avoSignersListConfig;
constructor(address owner_) {
_transferOwnership(owner_);
}
function setConfig(
AvocadoMultisigConfig calldata avocadoMultisigConfig_,
AvoDepositManagerConfig calldata avoDepositManagerConfig_,
AvoSignersListConfig calldata avoSignersListConfig_
) external onlyOwner {
if (
avocadoMultisigConfig_.authorizedMinFee == 0 ||
avocadoMultisigConfig_.authorizedMaxFee == 0 ||
avocadoMultisigConfig_.authorizedFeeCollector == address(0) ||
avocadoMultisigConfig_.authorizedMinFee > avocadoMultisigConfig_.authorizedMaxFee
) {
revert AvoConfig__InvalidConfig();
}
avocadoMultisigConfig = avocadoMultisigConfig_;
if (avoDepositManagerConfig_.depositToken == address(0)) {
revert AvoConfig__InvalidConfig();
}
avoDepositManagerConfig = avoDepositManagerConfig_;
avoSignersListConfig = avoSignersListConfig_;
}
function setConfig(
AvocadoMultisigConfig calldata avocadoMultisigConfig_,
AvoDepositManagerConfig calldata avoDepositManagerConfig_,
AvoSignersListConfig calldata avoSignersListConfig_
) external onlyOwner {
if (
avocadoMultisigConfig_.authorizedMinFee == 0 ||
avocadoMultisigConfig_.authorizedMaxFee == 0 ||
avocadoMultisigConfig_.authorizedFeeCollector == address(0) ||
avocadoMultisigConfig_.authorizedMinFee > avocadoMultisigConfig_.authorizedMaxFee
) {
revert AvoConfig__InvalidConfig();
}
avocadoMultisigConfig = avocadoMultisigConfig_;
if (avoDepositManagerConfig_.depositToken == address(0)) {
revert AvoConfig__InvalidConfig();
}
avoDepositManagerConfig = avoDepositManagerConfig_;
avoSignersListConfig = avoSignersListConfig_;
}
function setConfig(
AvocadoMultisigConfig calldata avocadoMultisigConfig_,
AvoDepositManagerConfig calldata avoDepositManagerConfig_,
AvoSignersListConfig calldata avoSignersListConfig_
) external onlyOwner {
if (
avocadoMultisigConfig_.authorizedMinFee == 0 ||
avocadoMultisigConfig_.authorizedMaxFee == 0 ||
avocadoMultisigConfig_.authorizedFeeCollector == address(0) ||
avocadoMultisigConfig_.authorizedMinFee > avocadoMultisigConfig_.authorizedMaxFee
) {
revert AvoConfig__InvalidConfig();
}
avocadoMultisigConfig = avocadoMultisigConfig_;
if (avoDepositManagerConfig_.depositToken == address(0)) {
revert AvoConfig__InvalidConfig();
}
avoDepositManagerConfig = avoDepositManagerConfig_;
avoSignersListConfig = avoSignersListConfig_;
}
}
| 15,547,026 | [
1,
2503,
353,
392,
9397,
20606,
6835,
1399,
358,
444,
731,
11732,
642,
924,
434,
8789,
504,
6821,
20092,
622,
6314,
1377,
2887,
13947,
89,
15495,
25112,
1758,
261,
12316,
833,
2934,
1377,
12419,
924,
1240,
2118,
444,
731,
8783,
16,
3410,
3377,
1375,
1187,
8386,
5460,
12565,
8338,
1377,
13219,
3410,
353,
8789,
83,
5049,
291,
360,
4446,
6835,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
16351,
8789,
83,
809,
58,
21,
353,
14223,
6914,
288,
203,
683,
9454,
18035,
560,
1545,
20,
18,
28,
18,
2643,
31,
203,
5666,
288,
14223,
6914,
289,
628,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
3860,
19,
5460,
429,
18,
18281,
14432,
203,
565,
1958,
8789,
504,
6821,
5049,
291,
360,
809,
288,
203,
3639,
2254,
5034,
10799,
2930,
14667,
31,
203,
3639,
2254,
5034,
10799,
2747,
14667,
31,
203,
3639,
1758,
10799,
14667,
7134,
31,
203,
203,
565,
289,
203,
565,
1958,
8789,
83,
758,
1724,
1318,
809,
288,
203,
3639,
1758,
443,
1724,
1345,
31,
203,
565,
289,
203,
203,
565,
1958,
8789,
83,
2766,
414,
682,
809,
288,
203,
3639,
1426,
3298,
382,
3245,
31,
203,
565,
289,
203,
203,
565,
871,
1903,
694,
12,
203,
3639,
8789,
504,
6821,
5049,
291,
360,
809,
1712,
504,
6821,
5049,
291,
360,
809,
16,
203,
3639,
8789,
83,
758,
1724,
1318,
809,
1712,
83,
758,
1724,
1318,
809,
16,
203,
3639,
8789,
83,
2766,
414,
682,
809,
1712,
83,
2766,
414,
682,
809,
203,
565,
11272,
203,
203,
565,
555,
8789,
83,
809,
972,
1941,
809,
5621,
203,
203,
565,
8789,
504,
6821,
5049,
291,
360,
809,
1071,
1712,
504,
6821,
5049,
291,
360,
809,
31,
203,
565,
8789,
83,
758,
1724,
1318,
809,
1071,
1712,
83,
758,
1724,
1318,
809,
31,
203,
565,
8789,
83,
2766,
414,
682,
809,
1071,
1712,
83,
2766,
414,
682,
809,
31,
203,
203,
565,
3885,
12,
2867,
3410,
67,
13,
288,
2
] |
./full_match/43114/0xD79a51f3253c2f55424455fC419E20087Cd8F50e/sources/ChillyChef.sol | Accumulated CHILLY per share, times 1e12. See below.
| uint256 accCHILLYPerShare; | 4,593,921 | [
1,
8973,
5283,
690,
6469,
2627,
7076,
1534,
7433,
16,
4124,
404,
73,
2138,
18,
2164,
5712,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
5034,
4078,
1792,
2627,
7076,
2173,
9535,
31,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol";
/**
* @dev This contract allows cross chain token transfers.
*
* There are two processes that take place in the contract -
* - Initiate a cross chain transfer to a target blockchain (locks tokens from the caller account on Ethereum)
* - Report a cross chain transfer initiated on a source blockchain (releases tokens to an account on Ethereum)
*
* Reporting cross chain transfers works similar to standard multisig contracts, meaning that multiple
* callers are required to report a transfer before tokens are released to the target account.
*/
contract Bridge is Ownable {
// represents a transaction on another blockchain where tokens were destroyed/locked
struct Transaction {
uint256 amount;
bytes32 fromBlockchain;
address to;
uint8 numOfReports;
bool completed;
}
struct SendRewardsConfig {
bytes32 toBlockchain;
bytes32 toAccount;
uint256 maxLockLimit;
}
bytes32 public sendRewardsToBlockchain; // the target blockchain when send rewards
bytes32 public sendRewardsToAccount; // the target account when send rewards
uint256 public sendRewardsMaxLockLimit; // the lock limit when send rewards
uint256 public maxLockLimit; // the maximum amount of tokens that can be locked in one transaction
uint256 public maxReleaseLimit; // the maximum amount of tokens that can be released in one transaction
uint256 public minLimit; // the minimum amount of tokens that can be transferred in one transaction
uint256 public prevLockLimit; // the lock limit *after* the last transaction
uint256 public prevReleaseLimit; // the release limit *after* the last transaction
uint256 public limitIncPerBlock; // how much the limit increases per block
uint256 public prevLockBlockNumber; // the block number of the last lock transaction
uint256 public prevReleaseBlockNumber; // the block number of the last release transaction
uint256 public commissionAmount; // the commission amount reduced from the release amount
uint256 public totalCommissions; // current total commissions accumulated on report tx
uint8 public minRequiredReports; // minimum number of required reports to release tokens
IERC20 public token; // erc20 token
bool public xTransfersEnabled = true; // true if x transfers are enabled, false if not
bool public reportingEnabled = true; // true if reporting is enabled, false if not
// txId -> Transaction
mapping(uint256 => Transaction) public transactions;
// xTransferId -> txId
mapping(uint256 => uint256) public transactionIds;
// txId -> reporter -> true if reporter already reported txId
mapping(uint256 => mapping(address => bool)) public reportedTxs;
// address -> true if address is reporter
mapping(address => bool) public reporters;
/**
* @dev triggered when tokens are locked in smart contract
*
* @param _from wallet address that the tokens are locked from
* @param _amount amount locked
*/
event TokensLock(address indexed _from, uint256 _amount);
/**
* @dev triggered when tokens are released by the smart contract
*
* @param _to wallet address that the tokens are released to
* @param _amount amount released
*/
event TokensRelease(address indexed _to, uint256 _amount);
/**
* @dev triggered when commissions are withdrawn by the smart contract
*
* @param _to wallet address that the tokens are withdrawn to
* @param _amount amount withdrawn
*/
event CommissionsWithdraw(address indexed _to, uint256 _amount);
/**
* @dev triggered when xTransfer is successfully called
*
* @param _from wallet address that initiated the xtransfer
* @param _toBlockchain target blockchain
* @param _to target wallet
* @param _amount transfer amount
* @param _id xtransfer id
*/
event XTransfer(address indexed _from, bytes32 _toBlockchain, bytes32 indexed _to, uint256 _amount, uint256 _id);
/**
* @dev triggered when report is successfully submitted
*
* @param _reporter reporter wallet
* @param _fromBlockchain source blockchain
* @param _txId tx id on the source blockchain
* @param _to target wallet
* @param _amount transfer amount
* @param _xTransferId xtransfer id
* @param _commissionAmount commission amount
*/
event TxReport(
address indexed _reporter,
bytes32 _fromBlockchain,
uint256 _txId,
address _to,
uint256 _amount,
uint256 _xTransferId,
uint256 _commissionAmount
);
/**
* @dev triggered when final report is successfully submitted
*
* @param _to target wallet
* @param _id xtransfer id
*/
event XTransferComplete(address _to, uint256 _id);
/**
* @dev triggered when rewards were sent
*
* @param _from rewards sender
* @param _amount amount of tokens
*/
event RewardsSent(address _from, uint256 _amount);
/**
* @dev initializes a new Bridge instance
*
* @param _maxLockLimit maximum amount of tokens that can be locked in one transaction
* @param _maxReleaseLimit maximum amount of tokens that can be released in one transaction
* @param _minLimit minimum amount of tokens that can be transferred in one transaction
* @param _limitIncPerBlock how much the limit increases per block
* @param _minRequiredReports minimum number of reporters to report transaction before tokens can be released
* @param _sendRewards send rewards config
* @param _token erc20 token
*/
constructor(
uint256 _maxLockLimit,
uint256 _maxReleaseLimit,
uint256 _minLimit,
uint256 _limitIncPerBlock,
uint8 _minRequiredReports,
uint256 _commissionAmount,
bytes memory _sendRewards,
IERC20 _token
)
greaterThanZero(_maxLockLimit)
greaterThanZero(_maxReleaseLimit)
greaterThanZero(_minLimit)
greaterThanZero(_limitIncPerBlock)
greaterThanZero(_minRequiredReports)
validExternalAddress(address(_token))
{
// validate input
require(_minLimit <= _maxLockLimit && _minLimit <= _maxReleaseLimit, "ERR_INVALID_MIN_LIMIT");
// the maximum limits, minimum limit, and limit increase per block
maxLockLimit = _maxLockLimit;
maxReleaseLimit = _maxReleaseLimit;
minLimit = _minLimit;
limitIncPerBlock = _limitIncPerBlock;
minRequiredReports = _minRequiredReports;
// send rewards
SendRewardsConfig memory sendRewardsConfig = abi.decode(_sendRewards, (SendRewardsConfig));
sendRewardsToBlockchain = sendRewardsConfig.toBlockchain;
sendRewardsToAccount = sendRewardsConfig.toAccount;
sendRewardsMaxLockLimit = sendRewardsConfig.maxLockLimit;
// previous limit is _maxLimit, and previous block number is current block number
prevLockLimit = _maxLockLimit;
prevReleaseLimit = _maxReleaseLimit;
prevLockBlockNumber = block.number;
prevReleaseBlockNumber = block.number;
// no need to validate number as it allowed to be 0
commissionAmount = _commissionAmount;
token = _token;
}
// validates that the caller is a reporter
modifier reporterOnly {
_reporterOnly();
_;
}
// error message binary size optimization
function _reporterOnly() internal view {
require(reporters[msg.sender], "ERR_ACCESS_DENIED");
}
// allows execution only when x transfers are enabled
modifier xTransfersAllowed {
_xTransfersAllowed();
_;
}
// error message binary size optimization
function _xTransfersAllowed() internal view {
require(xTransfersEnabled, "ERR_DISABLED");
}
// allows execution only when reporting is enabled
modifier reportingAllowed {
_reportingAllowed();
_;
}
// error message binary size optimization
function _reportingAllowed() internal view {
require(reportingEnabled, "ERR_DISABLED");
}
// verifies that a value is greater than zero
modifier greaterThanZero(uint256 _value) {
_greaterThanZero(_value);
_;
}
// error message binary size optimization
function _greaterThanZero(uint256 _value) internal pure {
require(_value > 0, "ERR_ZERO_VALUE");
}
// verifies that a value is greater than some amount
modifier greaterEqualThanAmount(uint256 _value, uint256 _amount) {
_greaterEqualThanAmount(_value, _amount);
_;
}
// error message binary size optimization
function _greaterEqualThanAmount(uint256 _value, uint256 _amount) internal pure {
require(_value >= _amount, "ERR_VALUE_TOO_LOW");
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
_validAddress(_address);
_;
}
// error message binary size optimization
function _validAddress(address _address) internal pure {
require(_address != address(0), "ERR_INVALID_ADDRESS");
}
// validates an external address - currently only checks that it isn't null or this
modifier validExternalAddress(address _address) {
_validExternalAddress(_address);
_;
}
// error message binary size optimization
function _validExternalAddress(address _address) internal view {
require(_address != address(0) && _address != address(this), "ERR_INVALID_EXTERNAL_ADDRESS");
}
/**
* @dev setter
*
* @param _maxLockLimit new maxLockLimit
*/
function setMaxLockLimit(uint256 _maxLockLimit) public onlyOwner greaterThanZero(_maxLockLimit) {
maxLockLimit = _maxLockLimit;
}
/**
* @dev setter
*
* @param _maxReleaseLimit new maxReleaseLimit
*/
function setMaxReleaseLimit(uint256 _maxReleaseLimit) public onlyOwner greaterThanZero(_maxReleaseLimit) {
maxReleaseLimit = _maxReleaseLimit;
}
/**
* @dev setter
*
* @param _minLimit new minLimit
*/
function setMinLimit(uint256 _minLimit) public onlyOwner greaterThanZero(_minLimit) {
// validate input
require(_minLimit <= maxLockLimit && _minLimit <= maxReleaseLimit, "ERR_INVALID_MIN_LIMIT");
minLimit = _minLimit;
}
/**
* @dev setter
*
* @param _limitIncPerBlock new limitIncPerBlock
*/
function setLimitIncPerBlock(uint256 _limitIncPerBlock) public onlyOwner greaterThanZero(_limitIncPerBlock) {
limitIncPerBlock = _limitIncPerBlock;
}
/**
* @dev setter
*
* @param _minRequiredReports new minRequiredReports
*/
function setMinRequiredReports(uint8 _minRequiredReports) public onlyOwner greaterThanZero(_minRequiredReports) {
minRequiredReports = _minRequiredReports;
}
/**
* @dev setter
*
* @param _commissionAmount new commission amount
*/
function setCommissionAmount(uint256 _commissionAmount) public onlyOwner {
commissionAmount = _commissionAmount;
}
/**
* @dev setter
*
* @param _blockchain target blockchain where the rewards will be sent to
*/
function setRewardsToBlockchain(bytes32 _blockchain) public onlyOwner {
sendRewardsToBlockchain = _blockchain;
}
/**
* @dev setter
*
* @param _toAccount target account which the rewards will be sent to
*/
function setRewardsToAccount(bytes32 _toAccount) public onlyOwner {
sendRewardsToAccount = _toAccount;
}
/**
* @dev setter
*
* @param _maxLockLimit rewards max limit amount
*/
function setRewardsMaxLockLimit(uint256 _maxLockLimit) public onlyOwner greaterThanZero(_maxLockLimit) {
sendRewardsMaxLockLimit = _maxLockLimit;
}
/**
* @dev allows the owner to set/remove reporters
*
* @param _reporters array of reporters which their status is to be set
* @param _active array of booleans. true if the reporter is approved, false otherwise
*/
function setReporters(address[] calldata _reporters, bool[] calldata _active) public onlyOwner {
require(_reporters.length == _active.length, "missing active status to set for all reporters");
for (uint16 reporterIndex = 0; reporterIndex < _reporters.length; reporterIndex++)
reporters[_reporters[reporterIndex]] = _active[reporterIndex];
}
/**
* @dev allows the owner enable/disable the xTransfer method
*
* @param _enable true to enable, false to disable
*/
function enableXTransfers(bool _enable) public onlyOwner {
xTransfersEnabled = _enable;
}
/**
* @dev allows the owner enable/disable the reportTransaction method
*
* @param _enable true to enable, false to disable
*/
function enableReporting(bool _enable) public onlyOwner {
reportingEnabled = _enable;
}
/**
* @dev claims tokens from a signer (calculated from provided signature) to be converted to tokens on another blockchain
*
* @param _toBlockchain blockchain on which tokens will be issued
* @param _to address to send the tokens to
* @param _amount the amount of tokens to transfer
* @param _deadline permit deadline
* @param _signer address to claim tokens from
* @param _v ECDSA signature recovery identifier
* @param _r ECDSA signature number
* @param _s ECDSA signature number
*/
function xTransfer(
bytes32 _toBlockchain,
bytes32 _to,
uint256 _amount,
uint256 _deadline,
address _signer,
uint8 _v,
bytes32 _r,
bytes32 _s
) public xTransfersAllowed {
// get the current lock limit
uint256 currentLockLimit = getCurrentLockLimit();
// require that; minLimit <= _amount <= currentLockLimit
require(_amount >= minLimit && _amount <= currentLockLimit, "ERR_AMOUNT_NOT_IN_RANGE");
// Permit function enables to give allowance to a spender, without a payment of the signer, due to the fact
// that any account can call permit, provided that it has the signature (_v, _r, _s parameters).
// Example: https://deweb-io.github.io/token/permit_demo.html
ERC20Permit(address(token)).permit(_signer, address(this), _amount, _deadline, _v, _r, _s);
lockTokens(_signer, _amount);
// set the previous lock limit and block number
prevLockLimit = currentLockLimit - _amount;
prevLockBlockNumber = block.number;
// emit XTransfer event
emit XTransfer(_signer, _toBlockchain, _to, _amount, 0);
}
/**
* @dev claims tokens from a signer to be converted to tokens on another blockchain (for a specific account)
* @param _amount the amount of tokens to transfer
*/
function sendRewards(uint256 _amount) public xTransfersAllowed {
require(_amount >= minLimit && _amount <= sendRewardsMaxLockLimit, "ERR_AMOUNT_NOT_IN_RANGE");
lockTokens(msg.sender, _amount);
// emit XTransfer event
emit XTransfer(msg.sender, sendRewardsToBlockchain, sendRewardsToAccount, _amount, 0);
// emit rewards sent event
emit RewardsSent(msg.sender, _amount);
}
/**
* @dev allows reporter to report transaction which occured on another blockchain
*
* @param _fromBlockchain blockchain in which tokens were destroyed
* @param _txId transactionId of transaction thats being reported
* @param _to address to receive tokens
* @param _amount amount of tokens destroyed on another blockchain
* @param _xTransferId unique (if non zero) pre-determined id (unlike _txId which is determined after the transactions been mined)
*/
function reportTx(
bytes32 _fromBlockchain,
uint256 _txId,
address _to,
uint256 _amount,
uint256 _xTransferId
) public reporterOnly reportingAllowed validAddress(_to) greaterEqualThanAmount(_amount, commissionAmount) {
// require that the transaction has not been reported yet by the reporter
require(!reportedTxs[_txId][msg.sender], "ERR_ALREADY_REPORTED");
// set reported as true
reportedTxs[_txId][msg.sender] = true;
Transaction storage txn = transactions[_txId];
// If the caller is the first reporter, set the transaction details
if (txn.numOfReports == 0) {
txn.to = _to;
txn.amount = _amount;
txn.fromBlockchain = _fromBlockchain;
if (_xTransferId != 0) {
// verify uniqueness of xTransfer id to prevent overwriting
require(transactionIds[_xTransferId] == 0, "ERR_TX_ALREADY_EXISTS");
transactionIds[_xTransferId] = _txId;
}
} else {
// otherwise, verify transaction details
require(txn.to == _to && txn.amount == _amount && txn.fromBlockchain == _fromBlockchain, "ERR_TX_MISMATCH");
if (_xTransferId != 0) {
require(transactionIds[_xTransferId] == _txId, "ERR_TX_ALREADY_EXISTS");
}
}
// increment the number of reports
txn.numOfReports++;
emit TxReport(msg.sender, _fromBlockchain, _txId, _to, _amount, _xTransferId, commissionAmount);
// if theres enough reports, try to release tokens
if (txn.numOfReports >= minRequiredReports) {
require(!transactions[_txId].completed, "ERR_TX_ALREADY_COMPLETED");
// set the transaction as completed
transactions[_txId].completed = true;
emit XTransferComplete(_to, _xTransferId);
// update the current total commissions
totalCommissions += commissionAmount;
releaseTokens(_to, _amount - commissionAmount); // release amount minus commission amount
}
}
/**
* @dev gets x transfer amount by xTransferId (not txId)
*
* @param _xTransferId unique (if non zero) pre-determined id (unlike _txId which is determined after the transactions been broadcasted)
* @param _for address corresponding to xTransferId
*
* @return amount that was sent in xTransfer corresponding to _xTransferId
*/
function getXTransferAmount(uint256 _xTransferId, address _for) public view returns (uint256) {
// xTransferId -> txId -> Transaction
Transaction memory transaction = transactions[transactionIds[_xTransferId]];
// verify that the xTransferId is for _for
require(transaction.to == _for, "ERR_TX_MISMATCH");
return transaction.amount;
}
/**
* @dev method for calculating current lock limit
*
* @return the current maximum limit of tokens that can be locked
*/
function getCurrentLockLimit() public view returns (uint256) {
uint256 currentLockLimit = prevLockLimit + ((block.number - prevLockBlockNumber) * limitIncPerBlock);
if (currentLockLimit > maxLockLimit) {
return maxLockLimit;
}
return currentLockLimit;
}
/**
* @dev method for calculating current release limit
*
* @return the current maximum limit of tokens that can be released
*/
function getCurrentReleaseLimit() public view returns (uint256) {
uint256 currentReleaseLimit = prevReleaseLimit + ((block.number - prevReleaseBlockNumber) * limitIncPerBlock);
if (currentReleaseLimit > maxReleaseLimit) {
return maxReleaseLimit;
}
return currentReleaseLimit;
}
/**
* @dev claims and locks tokens from signer to be converted to tokens on another blockchain
*
* @param _sender the address to lock tokens from
* @param _amount the amount of tokens to lock
*/
function lockTokens(address _sender, uint256 _amount) private {
// Do not allow amounts that can not be represented in EOS.
require(_amount % 10**14 == 0, "ERR_AMOUNT_TOO_MANY_DECIMALS");
token.transferFrom(_sender, address(this), _amount);
emit TokensLock(_sender, _amount);
}
/**
* @dev private method to release tokens held by the contract
*
* @param _to the address to release tokens to
* @param _amount the amount of tokens to release
*/
function releaseTokens(address _to, uint256 _amount) private {
// get the current release limit
uint256 currentReleaseLimit = getCurrentReleaseLimit();
require(_amount >= minLimit, "ERR_AMOUNT_TOO_LOW");
require(_amount <= currentReleaseLimit, "ERR_AMOUNT_TOO_HIGH");
// update the previous release limit and block number
prevReleaseLimit = currentReleaseLimit - _amount;
prevReleaseBlockNumber = block.number;
// no need to require, reverts on failure
token.transfer(_to, _amount);
emit TokensRelease(_to, _amount);
}
/**
* @dev allows the owner to withdraw all commissions accumulated
*
* @param _to the address to withdraw commissions to
*/
function withdrawCommissions(address _to) public onlyOwner validAddress(_to) {
// reset total commissions
totalCommissions = 0;
// no need to require, reverts on failure
token.transfer(_to, totalCommissions);
emit CommissionsWithdraw(_to, totalCommissions);
}
}
| * @dev setter @param _minLimit new minLimit/ validate input | function setMinLimit(uint256 _minLimit) public onlyOwner greaterThanZero(_minLimit) {
require(_minLimit <= maxLockLimit && _minLimit <= maxReleaseLimit, "ERR_INVALID_MIN_LIMIT");
minLimit = _minLimit;
}
| 12,961,011 | [
1,
18062,
225,
389,
1154,
3039,
565,
394,
1131,
3039,
19,
1954,
810,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
27724,
3039,
12,
11890,
5034,
389,
1154,
3039,
13,
1071,
1338,
5541,
6802,
9516,
7170,
24899,
1154,
3039,
13,
288,
203,
3639,
2583,
24899,
1154,
3039,
1648,
943,
2531,
3039,
597,
389,
1154,
3039,
1648,
943,
7391,
3039,
16,
315,
9712,
67,
9347,
67,
6236,
67,
8283,
8863,
203,
203,
3639,
1131,
3039,
273,
389,
1154,
3039,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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-03-17
*/
pragma solidity ^0.5.15;
// https://github.com/makerdao/dss/blob/master/src/jug.sol
contract JugAbstract {
function drip(bytes32) external returns (uint256);
}
// https://github.com/makerdao/dss/blob/master/src/pot.sol
contract PotAbstract {
function drip() external returns (uint256);
function dsr() public view returns (uint256);
function chi() public view returns (uint256);
function rho() public view returns (uint256);
}
// https://github.com/makerdao/dss/blob/master/src/vat.sol
contract VatAbstract {
function dai(address) public view returns (uint256);
function sin(address) public view returns (uint256);
}
// https://github.com/makerdao/dss/blob/master/src/vow.sol
contract VowAbstract {
function sin(uint256) public view returns (uint256);
function Sin() public view returns (uint256);
function Ash() public view returns (uint256);
function bump() public view returns (uint256);
function hump() public view returns (uint256);
function flap() external returns (uint256);
function heal(uint256) external;
}
// https://github.com/makerdao/sai/blob/master/src/pit.sol
contract GemPitAbstract {
function burn(address) public;
}
// https://github.com/dapphub/ds-token/blob/master/src/token.sol
contract DSTokenAbstract {
function balanceOf(address) external view returns (uint256);
}
// https://github.com/makerdao/dss/blob/master/src/pot.sol
contract PotHelper {
PotAbstract pa;
constructor(address pot) public {
pa = PotAbstract(pot);
}
// https://github.com/makerdao/dss/blob/master/src/pot.sol#L79
uint256 constant ONE = 10 ** 27;
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x);
}
function rmul(uint x, uint y) internal pure returns (uint z) {
z = mul(x, y) / ONE;
}
function rpow(uint x, uint n, uint base) internal pure returns (uint z) {
assembly {
switch x case 0 {switch n case 0 {z := base} default {z := 0}}
default {
switch mod(n, 2) case 0 { z := base } default { z := x }
let half := div(base, 2) // for rounding.
for { n := div(n, 2) } n { n := div(n,2) } {
let xx := mul(x, x)
if iszero(eq(div(xx, x), x)) { revert(0,0) }
let xxRound := add(xx, half)
if lt(xxRound, xx) { revert(0,0) }
x := div(xxRound, base)
if mod(n,2) {
let zx := mul(z, x)
if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) }
let zxRound := add(zx, half)
if lt(zxRound, zx) { revert(0,0) }
z := div(zxRound, base)
}
}
}
}
}
// View function for calculating value of chi iff drip() is called in the same block.
function drop() public view returns (uint256) { //inject PUBLIC FUNC TO EXTERNAL
if (now == pa.rho()) return pa.chi();
return rmul(rpow(pa.dsr(), now - pa.rho(), ONE), pa.chi());
}
// Pass the Pot Abstract for additional operations
function pot() public view returns (PotAbstract) { //inject PUBLIC FUNC TO EXTERNAL
return pa;
}
}
// 1111111 1=111)) HADAIKEN
//
// Optimized contract for performing some or all of the functions that
// keep Multi-Collateral Dai running.
contract Hadaiken {
address constant internal PIT = address(0x69076e44a9C70a67D5b79d95795Aba299083c275);
address constant internal MKR = address(0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2);
address constant internal JUG = address(0x19c0976f590D67707E62397C87829d896Dc0f1F1);
address constant internal POT = address(0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7);
address constant internal VAT = address(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B);
address constant internal VOW = address(0xA950524441892A31ebddF91d3cEEFa04Bf454466);
GemPitAbstract constant internal pit = GemPitAbstract(PIT);
DSTokenAbstract constant internal gem = DSTokenAbstract(MKR);
JugAbstract constant internal jug = JugAbstract(JUG);
PotAbstract constant internal pot = PotAbstract(POT);
VowAbstract constant internal vow = VowAbstract(VOW);
VatAbstract constant internal vat = VatAbstract(VAT);
PotHelper internal poth;
bytes32 constant internal ETH_A = bytes32("ETH-A");
bytes32 constant internal BAT_A = bytes32("BAT-A");
bytes32 constant internal USDC_A = bytes32("USDC-A");
constructor() public {
poth = new PotHelper(POT);
}
// Raw System Debt
function _rawSysDebt() internal view returns (uint256) {
return (vat.sin(VOW) - vow.Sin() - vow.Ash());
}
function rawSysDebt() public view returns (uint256) { //inject PUBLIC FUNC TO EXTERNAL
return _rawSysDebt();
}
function _sysSurplusThreshold() internal view returns (uint256) {
return (vat.sin(VOW) + vow.bump() + vow.hump());
}
function sysSurplusThreshold() public view returns (uint256) { //inject PUBLIC FUNC TO EXTERNAL
return _sysSurplusThreshold();
}
// Saves you money.
function heal() public { //inject PUBLIC FUNC TO EXTERNAL
_heal();
}
// Returns the amount of debt healed if you're curious about that sort of thing.
function healStat() public returns (uint256 sd) { //inject PUBLIC FUNC TO EXTERNAL
sd = _rawSysDebt();
_heal();
}
// No return here. I want to save gas and who cares.
function _heal() internal {
vow.heal(_rawSysDebt());
}
// Return the new chi value after drip.
function drip() public returns (uint256 chi) { //inject PUBLIC FUNC TO EXTERNAL
chi = pot.drip();
_dripIlks();
}
// Returns a simulated chi value
function drop() public view returns (uint256) { //inject PUBLIC FUNC TO EXTERNAL
return poth.drop();
}
function _dripPot() internal {
pot.drip();
}
function dripIlks() public { //inject PUBLIC FUNC TO EXTERNAL
_dripIlks();
}
function _dripIlks() internal {
jug.drip(ETH_A);
jug.drip(BAT_A);
jug.drip(USDC_A);
}
function kickable() public view returns (bool) { //inject PUBLIC FUNC TO EXTERNAL
return _kickable();
}
// Can we bump an auction?
function _kickable() internal view returns (bool) {
// Assume heal is called prior to kick.
// require(vat.dai(address(this)) >= add(add(vat.sin(address(this)), bump), hump), "Vow/insufficient-surplus");
// require(sub(sub(vat.sin(address(this)), Sin), Ash) == 0, "Vow/debt-not-zero");
return (vat.dai(VOW) >= _sysSurplusThreshold());
}
// Burn all of the MKR in the Sai Pit
function finishhim() public returns (uint256 burned) { //inject PUBLIC FUNC TO EXTERNAL
burned = gem.balanceOf(PIT);
_finishhim();
}
function _finishhim() internal {
pit.burn(MKR);
}
// Kick off an auction and return the auction ID
function ccccombobreaker() public returns (uint256) { //inject PUBLIC FUNC TO EXTERNAL
_heal(); // Flap requires debt == 0
return vow.flap();
}
// Kick off an auction and throw away id
function _ccccombobreaker() internal {
vow.flap();
}
// Kitchen sink. Call this early and often.
function hadaiken() public { //inject PUBLIC FUNC TO EXTERNAL
_dripPot(); // Update the chi
_dripIlks(); // Updates the Ilk rates
_heal(); // Cancel out system debt with system surplus
if (_kickable()) { _ccccombobreaker(); } // Start an auction
}
} | inject PUBLIC FUNC TO EXTERNAL
| function drop() public view returns (uint256) { | 7,265,598 | [
1,
22170,
17187,
478,
21163,
8493,
5675,
11702,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3640,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/ownership/Ownable.sol";
contract IRewardDistributionRecipient is Ownable {
address public rewardDistribution;
function notifyRewardAmount(uint256 reward) external;
modifier onlyRewardDistribution() {
require(_msgSender() == rewardDistribution, "Caller is not reward distribution");
_;
}
function setRewardDistribution(address _rewardDistribution) external onlyOwner {
rewardDistribution = _rewardDistribution;
}
}
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./IRewardDistributionRecipient.sol";
contract LPTokenWrapper {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public token;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
event Approval(address indexed owner, address indexed spender, uint256 value);
constructor(address _token) public {
token = IERC20(_token);
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function stakeFor(address _user, uint256 _amount) public {
_stake(_user, _amount);
}
function stake(uint256 _amount) public {
_stake(msg.sender, _amount);
}
function approve(address _user, uint256 _amount) public {
_approve(msg.sender, _user, _amount);
}
function withdraw(uint256 _amount) public {
_withdraw(msg.sender, _amount);
}
function withdrawFrom(address _user, uint256 _amount) public {
_withdraw(_user, _amount);
_approve(
_user,
msg.sender,
_allowances[_user][msg.sender].sub(_amount, "LPTokenWrapper: withdraw amount exceeds allowance")
);
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return _allowances[_owner][_spender];
}
function _stake(address _user, uint256 _amount) internal {
_totalSupply = _totalSupply.add(_amount);
_balances[_user] = _balances[_user].add(_amount);
token.safeTransferFrom(msg.sender, address(this), _amount);
}
function _withdraw(address _owner, uint256 _amount) internal {
_totalSupply = _totalSupply.sub(_amount);
_balances[_owner] = _balances[_owner].sub(_amount);
IERC20(token).safeTransfer(msg.sender, _amount);
}
function _approve(
address _owner,
address _user,
uint256 _amount
) internal returns (bool) {
require(_user != address(0), "LPTokenWrapper: approve to the zero address");
_allowances[_owner][_user] = _amount;
emit Approval(_owner, _user, _amount);
return true;
}
}
contract ModifiedUnipool is LPTokenWrapper, IRewardDistributionRecipient {
address public rewardToken;
uint256 public constant DURATION = 7 days;
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);
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
constructor(address _rewardToken, address _token) public LPTokenWrapper(_token) {
rewardToken = _rewardToken;
}
function notifyRewardAmount(uint256 reward) external onlyRewardDistribution updateReward(address(0)) {
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);
}
function exit() external {
withdraw(balanceOf(msg.sender));
getReward(msg.sender);
}
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(uint256 amount) public updateReward(msg.sender) {
require(amount > 0, "Cannot stake 0");
super.stake(amount);
emit Staked(msg.sender, amount);
}
function stakeFor(address _user, uint256 _amount) public updateReward(_user) {
require(_amount > 0, "Cannot stake 0");
super.stakeFor(_user, _amount);
emit Staked(_user, _amount);
}
function withdraw(uint256 amount) public updateReward(msg.sender) {
require(amount > 0, "Cannot withdraw 0");
super.withdraw(amount);
emit Withdrawn(msg.sender, amount);
}
function withdrawFrom(address _user, uint256 amount) public updateReward(_user) {
require(amount > 0, "Cannot withdraw 0");
super.withdrawFrom(_user, amount);
emit Withdrawn(_user, amount);
}
function getReward() public {
_getReward(msg.sender);
}
function getReward(address _user) public {
_getReward(_user);
}
function _getReward(address _user) internal updateReward(_user) {
uint256 reward = earned(_user);
if (reward > 0) {
rewards[_user] = 0;
IERC20(rewardToken).safeTransfer(_user, reward);
emit RewardPaid(_user, reward);
}
}
}
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
pragma solidity ^0.5.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.5.0;
import "../GSN/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = _msgSender();
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.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 ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* IMPORTANT: It is unsafe to assume that an address for which this
* function returns false is an externally-owned account (EOA) and not a
* contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
| * @dev Collection of functions related to the address type/ | library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
return (codehash != 0x0 && codehash != accountHash);
}
assembly { codehash := extcodehash(account) }
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
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");
}
}
| 55,920 | [
1,
2532,
434,
4186,
3746,
358,
326,
1758,
618,
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,
12083,
5267,
288,
203,
565,
445,
353,
8924,
12,
2867,
2236,
13,
2713,
1476,
1135,
261,
6430,
13,
288,
203,
203,
3639,
1731,
1578,
981,
2816,
31,
203,
3639,
1731,
1578,
2236,
2310,
273,
374,
6511,
25,
72,
3247,
26,
1611,
5292,
74,
9060,
3707,
71,
29,
5324,
73,
27,
1966,
22,
72,
952,
27,
4630,
71,
20,
73,
12483,
70,
26,
8643,
5353,
24532,
9036,
70,
27,
17156,
361,
28,
3028,
25,
72,
7140,
69,
24,
7301,
31,
203,
3639,
327,
261,
710,
2816,
480,
374,
92,
20,
597,
981,
2816,
480,
2236,
2310,
1769,
203,
565,
289,
203,
203,
3639,
19931,
288,
981,
2816,
519,
1110,
710,
2816,
12,
4631,
13,
289,
203,
565,
445,
358,
9148,
429,
12,
2867,
2236,
13,
2713,
16618,
1135,
261,
2867,
8843,
429,
13,
288,
203,
3639,
327,
1758,
12,
11890,
16874,
12,
4631,
10019,
203,
565,
289,
203,
203,
565,
445,
1366,
620,
12,
2867,
8843,
429,
8027,
16,
2254,
5034,
3844,
13,
2713,
288,
203,
3639,
2583,
12,
2867,
12,
2211,
2934,
12296,
1545,
3844,
16,
315,
1887,
30,
2763,
11339,
11013,
8863,
203,
203,
3639,
261,
6430,
2216,
16,
262,
273,
8027,
18,
1991,
18,
1132,
12,
8949,
13,
2932,
8863,
203,
3639,
2583,
12,
4768,
16,
315,
1887,
30,
13496,
358,
1366,
460,
16,
8027,
2026,
1240,
15226,
329,
8863,
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
] |
./full_match/137/0x0a49EbdC20DfBcD90A53b4BA4C74a5DBfb42BECa/sources/contracts/Constants.sol | It's primary admin.
| bytes32 constant BIG_TIMELOCK_ADMIN = 0x00; | 4,795,622 | [
1,
7193,
1807,
3354,
3981,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3890,
1578,
5381,
18855,
67,
4684,
6589,
67,
15468,
273,
374,
92,
713,
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
] |
pragma solidity 0.5.10;
import 'openzeppelin-solidity/contracts/token/ERC20/ERC20.sol';
import 'openzeppelin-solidity/contracts/math/SafeMath.sol';
import './Loans.sol';
import './ALCompound.sol';
/**
* @title Atomic Loans Funds Contract
* @author Atomic Loans
*/
contract Funds is DSMath, ALCompound {
Loans loans;
uint256 public constant DEFAULT_LIQUIDATION_RATIO = 1400000000000000000000000000; // 140% (1.4x in RAY) minimum collateralization ratio
uint256 public constant DEFAULT_LIQUIDATION_PENALTY = 1000000000937303470807876289; // 3% (3 in RAY) liquidation penalty ((1.000000000937303470807876289) ^ (60 * 60 * 24 * 365)) - 1 = ~0.03
uint256 public constant DEFAULT_MIN_LOAN_AMT = 25 ether; // Min 25 WAD
uint256 public constant DEFAULT_MAX_LOAN_AMT = 2**256-1; // Max 2**256
uint256 public constant DEFAULT_MIN_LOAN_DUR = 6 hours; // 6 hours
uint256 public constant NUM_SECONDS_IN_YEAR = 365 days;
uint256 public constant MAX_LOAN_LENGTH = 10 * NUM_SECONDS_IN_YEAR;
uint256 public constant MAX_UINT_256 = 2**256-1;
mapping (address => bytes32[]) public secretHashes; // User secret hashes
mapping (address => uint256) public secretHashIndex; // User secret hash index
mapping (address => bytes) public pubKeys; // User A Coin PubKeys
mapping (bytes32 => Fund) public funds;
mapping (address => bytes32) public fundOwner;
mapping (bytes32 => Bools) public bools;
uint256 public fundIndex;
uint256 public lastGlobalInterestUpdated;
uint256 public tokenMarketLiquidity;
uint256 public cTokenMarketLiquidity;
uint256 public marketLiquidity;
uint256 public totalBorrow;
uint256 public globalInterestRateNumerator;
uint256 public lastUtilizationRatio;
uint256 public globalInterestRate;
uint256 public maxUtilizationDelta;
uint256 public utilizationInterestDivisor;
uint256 public maxInterestRateNumerator;
uint256 public minInterestRateNumerator;
uint256 public interestUpdateDelay;
uint256 public defaultArbiterFee;
ERC20 public token;
uint256 public decimals;
CTokenInterface public cToken;
bool compoundSet;
address deployer;
/**
* @notice Container for Loan Fund information
* @member lender Loan Fund Owner
* @member minLoanAmt Minimum Loan Amount that can be requested by a 'borrower'
* @member maxLoanAmt Maximum Loan Amount that can be requested by a 'borrower'
* @member minLoanDur Minimum Loan Duration that can be requested by a 'borrower'
* @member maxLoanDur Maximum Loan Duration that can be requested by a 'borrower'
* @member interest Interest Rate of Loan Fund in RAY per second
* @member penalty Liquidation Penalty Rate of Loan Fund in RAY per second
* @member fee Optional Automation Fee Rate of Loan Fund in RAY per second
* @member liquidationRatio Liquidation Ratio of Loan Fund in RAY
* @member arbiter Optional address of Automator Arbiter
* @member balance Amount of non-borrowed tokens in Loan Fund
* @member cBalance Amount of non-borrowed cTokens in Loan Fund
*/
struct Fund {
address lender;
uint256 minLoanAmt;
uint256 maxLoanAmt;
uint256 minLoanDur;
uint256 maxLoanDur;
uint256 fundExpiry;
uint256 interest;
uint256 penalty;
uint256 fee;
uint256 liquidationRatio;
address arbiter;
uint256 balance;
uint256 cBalance;
}
/**
* @notice Container for Loan Fund boolean configurations
* @member custom Indicator that this Loan Fund is custom and does not use global settings
* @member compoundEnabled Indicator that this Loan Fund lends non-borrowed tokens on Compound
*/
struct Bools {
bool custom;
bool compoundEnabled;
}
event Create(bytes32 fund);
event Deposit(bytes32 fund, uint256 amount_);
event Update(bytes32 fund, uint256 maxLoanDur_, uint256 fundExpiry_, address arbiter_);
event Request(bytes32 fund, address borrower_, uint256 amount_, uint256 collateral_, uint256 loanDur_, uint256 requestTimestamp_);
event Withdraw(bytes32 fund, uint256 amount_, address recipient_);
event EnableCompound(bytes32 fund);
event DisableCompound(bytes32 fund);
/**
* @notice Construct a new Medianizer
*/
/**
* @notice Construct a new Funds contract
* @param token_ The address of the stablecoin token
* @param decimals_ The number of decimals in the stablecoin token
*/
constructor(
ERC20 token_,
uint256 decimals_
) public {
require(address(token_) != address(0), "Funds.constructor: Token address must be non-zero");
require(decimals_ != 0, "Funds.constructor: Decimals must be non-zero");
deployer = msg.sender;
token = token_;
decimals = decimals_;
utilizationInterestDivisor = 10531702972595856680093239305; // 10.53 in RAY (~10:1 ratio for % change in utilization ratio to % change in interest rate)
maxUtilizationDelta = 95310179948351216961192521; // Global Interest Rate Numerator can change up to 9.53% in RAY (~10% change in utilization ratio = ~1% change in interest rate)
globalInterestRateNumerator = 95310179948351216961192521; // ~10% ( (e^(ln(1.100)/(60*60*24*365)) - 1) * (60*60*24*365) )
maxInterestRateNumerator = 182321557320989604265864303; // ~20% ( (e^(ln(1.200)/(60*60*24*365)) - 1) * (60*60*24*365) )
minInterestRateNumerator = 24692612600038629323181834; // ~2.5% ( (e^(ln(1.025)/(60*60*24*365)) - 1) * (60*60*24*365) )
interestUpdateDelay = 86400; // 1 DAY
defaultArbiterFee = 1000000000236936036262880196; // 0.75% (0.75 in RAY) optional arbiter fee ((1.000000000236936036262880196) ^ (60 * 60 * 24 * 365)) - 1 = ~0.0075
globalInterestRate = add(RAY, div(globalInterestRateNumerator, NUM_SECONDS_IN_YEAR)); // Interest rate per second
}
// NOTE: THE FOLLOWING FUNCTIONS CAN ONLY BE CALLED BY THE DEPLOYER OF THE
// CONTRACT ONCE. THIS IS TO ALLOW FOR FUNDS, LOANS, AND SALES
// CONTRACTS TO BE DEPLOYED SEPARATELY (DUE TO GAS LIMIT RESTRICTIONS).
// IF YOU ARE USING THIS CONTRACT, ENSURE THAT THESE FUNCTIONS HAVE
// ALREADY BEEN CALLED BEFORE DEPOSITING FUNDS.
// ======================================================================
/**
* @dev Sets Loans contract
* @param loans_ Address of Loans contract
*/
function setLoans(Loans loans_) external {
require(msg.sender == deployer, "Funds.setLoans: Only the deployer can perform this");
require(address(loans) == address(0), "Funds.setLoans: Loans address has already been set");
require(address(loans_) != address(0), "Funds.setLoans: Loans address must be non-zero");
loans = loans_;
require(token.approve(address(loans_), MAX_UINT_256), "Funds.setLoans: Tokens cannot be approved");
}
/**
* @dev Enables assets in loan fund that haven't been borrowed to be lent on Compound
* @param cToken_ The address of the Compound Token
* @param comptroller_ The address of the Compound Comptroller
*/
function setCompound(CTokenInterface cToken_, address comptroller_) external {
require(msg.sender == deployer, "Funds.setCompound: Only the deployer can enable Compound lending");
require(!compoundSet, "Funds.setCompound: Compound address has already been set");
require(address(cToken_) != address(0), "Funds.setCompound: cToken address must be non-zero");
require(comptroller_ != address(0), "Funds.setCompound: comptroller address must be non-zero");
cToken = cToken_;
comptroller = comptroller_;
compoundSet = true;
}
// ======================================================================
// NOTE: THE FOLLOWING FUNCTIONS ALLOW VARIABLES TO BE MODIFIED BY THE
// DEPLOYER, SINCE THE ALGORITHM FOR CALCULATING GLOBAL INTEREST
// RATE IS UNTESTED WITH A DECENTRALIZED PROTOCOL, AND MAY NEED TO
// BE UPDATED IN THE CASE THAT RATES DO NOT UPDATE AS INTENDED. A
// FUTURE ITERATION OF THE PROTOCOL WILL REMOVE THESE FUNCTIONS. IF
// YOU WISH TO OPT OUT OF GLOBAL APR YOU CAN CREATE A CUSTOM LOAN FUND
// ======================================================================
/**
* @dev Sets the Utilization Interest Divisor
*/
function setUtilizationInterestDivisor(uint256 utilizationInterestDivisor_) external {
require(msg.sender == deployer, "Funds.setUtilizationInterestDivisor: Only the deployer can perform this");
require(utilizationInterestDivisor_ != 0, "Funds.setUtilizationInterestDivisor: utilizationInterestDivisor is zero");
utilizationInterestDivisor = utilizationInterestDivisor_;
}
/**
* @dev Sets the Max Utilization Delta
*/
function setMaxUtilizationDelta(uint256 maxUtilizationDelta_) external {
require(msg.sender == deployer, "Funds.setMaxUtilizationDelta: Only the deployer can perform this");
require(maxUtilizationDelta_ != 0, "Funds.setMaxUtilizationDelta: maxUtilizationDelta is zero");
maxUtilizationDelta = maxUtilizationDelta_;
}
/**
* @dev Sets the Global Interest Rate Numerator
*/
function setGlobalInterestRateNumerator(uint256 globalInterestRateNumerator_) external {
require(msg.sender == deployer, "Funds.setGlobalInterestRateNumerator: Only the deployer can perform this");
require(globalInterestRateNumerator_ != 0, "Funds.setGlobalInterestRateNumerator: globalInterestRateNumerator is zero");
globalInterestRateNumerator = globalInterestRateNumerator_;
}
/**
* @dev Sets the Global Interest Rate
*/
function setGlobalInterestRate(uint256 globalInterestRate_) external {
require(msg.sender == deployer, "Funds.setGlobalInterestRate: Only the deployer can perform this");
require(globalInterestRate_ != 0, "Funds.setGlobalInterestRate: globalInterestRate is zero");
globalInterestRate = globalInterestRate_;
}
/**
* @dev Sets the Maximum Interest Rate Numerator
*/
function setMaxInterestRateNumerator(uint256 maxInterestRateNumerator_) external {
require(msg.sender == deployer, "Funds.setMaxInterestRateNumerator: Only the deployer can perform this");
require(maxInterestRateNumerator_ != 0, "Funds.setMaxInterestRateNumerator: maxInterestRateNumerator is zero");
maxInterestRateNumerator = maxInterestRateNumerator_;
}
/**
* @dev Sets the Minimum Interest Rate Numerator
*/
function setMinInterestRateNumerator(uint256 minInterestRateNumerator_) external {
require(msg.sender == deployer, "Funds.setMinInterestRateNumerator: Only the deployer can perform this");
require(minInterestRateNumerator_ != 0, "Funds.setMinInterestRateNumerator: minInterestRateNumerator is zero");
minInterestRateNumerator = minInterestRateNumerator_;
}
/**
* @dev Sets the Interest Update Delay
*/
function setInterestUpdateDelay(uint256 interestUpdateDelay_) external {
require(msg.sender == deployer, "Funds.setInterestUpdateDelay: Only the deployer can perform this");
require(interestUpdateDelay_ != 0, "Funds.setInterestUpdateDelay: interestUpdateDelay is zero");
interestUpdateDelay = interestUpdateDelay_;
}
/**
* @dev Sets the Default Arbiter Fee
*/
function setDefaultArbiterFee(uint256 defaultArbiterFee_) external {
require(msg.sender == deployer, "Funds.setDefaultArbiterFee: Only the deployer can perform this");
require(defaultArbiterFee_ <= 1000000000315522921573372069, "Funds.setDefaultArbiterFee: defaultArbiterFee cannot be less than -1%"); // ~1% ((1.000000000315522921573372069) ^ (60 * 60 * 24 * 365)) - 1 = ~0.01
defaultArbiterFee = defaultArbiterFee_;
}
// ======================================================================
/**
* @notice Get the lender of a Loan Fund
* @param fund The Id of a Loan Fund
* @return Owner address of Loan Fund
*/
function lender(bytes32 fund) public view returns (address) {
return funds[fund].lender;
}
/**
* @notice Get minimum loan amount able to be requested by a 'borrower'
* @param fund The Id of a Loan Fund
* @return The minimum amount of tokens that can be requested from a Loan Fund
*/
function minLoanAmt(bytes32 fund) public view returns (uint256) {
if (bools[fund].custom) {return funds[fund].minLoanAmt;}
else {return div(DEFAULT_MIN_LOAN_AMT, (10 ** sub(18, decimals)));}
}
/**
* @notice Get maximum loan amount able to be requested by a 'borrower'
* @param fund The Id of a Loan Fund
* @return The maximum amount of tokens that can be requested from a Loan Fund
*/
function maxLoanAmt(bytes32 fund) public view returns (uint256) {
if (bools[fund].custom) {return funds[fund].maxLoanAmt;}
else {return DEFAULT_MAX_LOAN_AMT;}
}
/**
* @notice Get minimum loan duration able to be requested by a 'borrower'
* @param fund The Id of a Loan Fund
* @return The minimum duration loan that can be requested from a Loan Fund
*/
function minLoanDur(bytes32 fund) public view returns (uint256) {
if (bools[fund].custom) {return funds[fund].minLoanDur;}
else {return DEFAULT_MIN_LOAN_DUR;}
}
/**
* @notice Get maximum loan duration able to be requested by a 'borrower'
* @param fund The Id of a Loan Fund
* @return The maximum duration loan that can be requested from a Loan Fund
*/
function maxLoanDur(bytes32 fund) public view returns (uint256) {
return funds[fund].maxLoanDur;
}
/**
* @notice Get maximum loan duration able to be requested by a 'borrower'
* @param fund The Id of a Loan Fund
* @return The maximum duration loan that can be requested from a Loan Fund
*/
function fundExpiry(bytes32 fund) public view returns (uint256) {
return funds[fund].fundExpiry;
}
/**
* @notice Get the interest rate for a Loan Fund
* @param fund The Id of a Loan Fund
* @return The interest rate per second for a Loan Fund in RAY per second
*/
function interest(bytes32 fund) public view returns (uint256) {
if (bools[fund].custom) {return funds[fund].interest;}
else {return globalInterestRate;}
}
/**
* @notice Get the liquidation penalty rate for a Loan Fund
* @param fund The Id of a Loan Fund
* @return The liquidation penalty rate per second for a Loan Fund in RAY per second
*/
function penalty(bytes32 fund) public view returns (uint256) {
if (bools[fund].custom) {return funds[fund].penalty;}
else {return DEFAULT_LIQUIDATION_PENALTY;}
}
/**
* @notice Get the optional automation fee for a Loan Fund
* @param fund The Id of a Loan Fund
* @return The optional automation fee rate of Loan Fund in RAY per second
*/
function fee(bytes32 fund) public view returns (uint256) {
if (bools[fund].custom) {return funds[fund].fee;}
else {return defaultArbiterFee;}
}
/**
* @notice Get the liquidation ratio of a Loan Fund
* @param fund The Id of a Loan Fund
* @return The liquidation ratio of Loan Fund in RAY
*/
function liquidationRatio(bytes32 fund) public view returns (uint256) {
if (bools[fund].custom) {return funds[fund].liquidationRatio;}
else {return DEFAULT_LIQUIDATION_RATIO;}
}
/**
* @notice Get the arbiter for a Loan Fund
* @param fund The Id of a Loan Fund
* @return The address of the arbiter for a Loan fund
*/
function arbiter(bytes32 fund) public view returns (address) {
return funds[fund].arbiter;
}
/**
* @notice Get the current balance of a Loan Fund in tokens
* @param fund The Id of a Loan Fund
* @return The amount of tokens remaining in Loan Fund
*/
function balance(bytes32 fund) public returns (uint256) {
if (bools[fund].compoundEnabled) {
return wmul(funds[fund].cBalance, cToken.exchangeRateCurrent());
} else {
return funds[fund].balance;
}
}
function cTokenExchangeRate() public returns (uint256) {
if (compoundSet) {
return cToken.exchangeRateCurrent();
} else {
return 0;
}
}
/**
* @notice Get the custom indicator for a Loan Fund
* @param fund The Id of a Loan Fund
* @return The indicator of whether a Loan Fund is custom or not
*/
function custom(bytes32 fund) public view returns (bool) {
return bools[fund].custom;
}
/**
* @notice Get the number of secretHashes provided per address
* @param addr_ The address of the user
* @return The length of the secretHashes array for user address
*/
function secretHashesCount(address addr_) public view returns (uint256) {
return secretHashes[addr_].length;
}
/**
* @notice Lenders create Loan Fund using Global Protocol parameters and deposit assets
* @param maxLoanDur_ Max Loan Duration of Loan Fund in seconds
* @param arbiter_ Optional address of arbiter
* @param compoundEnabled_ Indicator whether excess funds should be lent on Compound
* @param amount_ Amount of tokens to be deposited on creation
* @return The Id of a Loan Fund
*
* Note: Only one loan fund is allowed per ethereum address.
* Exception is made for the deployer for testing.
*/
function create(
uint256 maxLoanDur_,
uint256 fundExpiry_,
address arbiter_,
bool compoundEnabled_,
uint256 amount_
) external returns (bytes32 fund) {
// #IF TESTING
require(funds[fundOwner[msg.sender]].lender != msg.sender || msg.sender == deployer, "Funds.create: Only one loan fund allowed per address");
// #ELSE:
// require(funds[fundOwner[msg.sender]].lender != msg.sender, "Funds.create: Only one loan fund allowed per address"); // Only allow one loan fund per address
// #ENDIF
require(
ensureNotZero(maxLoanDur_, false) < MAX_LOAN_LENGTH && ensureNotZero(fundExpiry_, true) < now + MAX_LOAN_LENGTH,
"Funds.create: fundExpiry and maxLoanDur cannot exceed 10 years"
); // Make sure someone can't request a loan for longer than 10 years
if (!compoundSet) {require(compoundEnabled_ == false, "Funds.create: Cannot enable Compound as it has not been configured");}
fundIndex = add(fundIndex, 1);
fund = bytes32(fundIndex);
funds[fund].lender = msg.sender;
funds[fund].maxLoanDur = ensureNotZero(maxLoanDur_, false);
funds[fund].fundExpiry = ensureNotZero(fundExpiry_, true);
funds[fund].arbiter = arbiter_;
bools[fund].custom = false;
bools[fund].compoundEnabled = compoundEnabled_;
fundOwner[msg.sender] = bytes32(fundIndex);
if (amount_ > 0) {deposit(fund, amount_);}
emit Create(fund);
}
/**
* @notice Lenders create Loan Fund using Custom parameters and deposit assets
* @param minLoanAmt_ Minimum amount of tokens that can be borrowed from Loan Fund
* @param maxLoanAmt_ Maximum amount of tokens that can be borrowed from Loan Fund
* @param minLoanDur_ Minimum length of loan that can be requested from Loan Fund in seconds
* @param maxLoanDur_ Maximum length of loan that can be requested from Loan Fund in seconds
* @param arbiter_ Optional address of arbiter
* @param compoundEnabled_ Indicator whether excess funds should be lent on Compound
* @param amount_ Amount of tokens to be deposited on creation
* @return The Id of a Loan Fund
*
* Note: Only one loan fund is allowed per ethereum address.
* Exception is made for the deployer for testing.
*/
function createCustom(
uint256 minLoanAmt_,
uint256 maxLoanAmt_,
uint256 minLoanDur_,
uint256 maxLoanDur_,
uint256 fundExpiry_,
uint256 liquidationRatio_,
uint256 interest_,
uint256 penalty_,
uint256 fee_,
address arbiter_,
bool compoundEnabled_,
uint256 amount_
) external returns (bytes32 fund) {
// #IF TESTING
require(funds[fundOwner[msg.sender]].lender != msg.sender || msg.sender == deployer, "Funds.create: Only one loan fund allowed per address"); // Exception for deployer during testing
// #ELSE:
// require(funds[fundOwner[msg.sender]].lender != msg.sender, "Funds.create: Only one loan fund allowed per address"); // Only allow one loan fund per address
// #ENDIF
require(
ensureNotZero(maxLoanDur_, false) < MAX_LOAN_LENGTH && ensureNotZero(fundExpiry_, true) < now + MAX_LOAN_LENGTH,
"Funds.createCustom: fundExpiry and maxLoanDur cannot exceed 10 years"
); // Make sure someone can't request a loan for longer than 10 years
require(maxLoanAmt_ >= minLoanAmt_, "Funds.createCustom: maxLoanAmt must be greater than or equal to minLoanAmt");
require(ensureNotZero(maxLoanDur_, false) >= minLoanDur_, "Funds.createCustom: maxLoanDur must be greater than or equal to minLoanDur");
if (!compoundSet) {require(compoundEnabled_ == false, "Funds.createCustom: Cannot enable Compound as it has not been configured");}
fundIndex = add(fundIndex, 1);
fund = bytes32(fundIndex);
funds[fund].lender = msg.sender;
funds[fund].minLoanAmt = minLoanAmt_;
funds[fund].maxLoanAmt = maxLoanAmt_;
funds[fund].minLoanDur = minLoanDur_;
funds[fund].maxLoanDur = ensureNotZero(maxLoanDur_, false);
funds[fund].fundExpiry = ensureNotZero(fundExpiry_, true);
funds[fund].interest = interest_;
funds[fund].penalty = penalty_;
funds[fund].fee = fee_;
funds[fund].liquidationRatio = liquidationRatio_;
funds[fund].arbiter = arbiter_;
bools[fund].custom = true;
bools[fund].compoundEnabled = compoundEnabled_;
fundOwner[msg.sender] = bytes32(fundIndex);
if (amount_ > 0) {deposit(fund, amount_);}
emit Create(fund);
}
/**
* @notice Lenders deposit tokens in Loan Fund
* @param fund The Id of a Loan Fund
* @param amount_ Amount of tokens to deposit
*
* Note: Anyone can deposit tokens into a Loan Fund
*/
function deposit(bytes32 fund, uint256 amount_) public {
require(token.transferFrom(msg.sender, address(this), amount_), "Funds.deposit: Failed to transfer tokens");
if (bools[fund].compoundEnabled) {
mintCToken(address(token), address(cToken), amount_);
uint256 cTokenToAdd = div(mul(amount_, WAD), cToken.exchangeRateCurrent());
funds[fund].cBalance = add(funds[fund].cBalance, cTokenToAdd);
if (!custom(fund)) {cTokenMarketLiquidity = add(cTokenMarketLiquidity, cTokenToAdd);}
} else {
funds[fund].balance = add(funds[fund].balance, amount_);
if (!custom(fund)) {tokenMarketLiquidity = add(tokenMarketLiquidity, amount_);}
}
if (!custom(fund)) {calcGlobalInterest();}
emit Deposit(fund, amount_);
}
/**
* @notice Users update Loan Fund settings
* @param fund The Id of a Loan Fund
* @param maxLoanDur_ Maximum length of loan that can be requested from Loan Fund in seconds
* @param fundExpiry_ Timestamp when all funds should be removable from Loan Fund
* @param arbiter_ Optional address of the arbiter for a Loan fund
*
* Note: msg.sender must be the lender of the Loan Fund
*/
function update(
bytes32 fund,
uint256 maxLoanDur_,
uint256 fundExpiry_,
address arbiter_
) public {
require(msg.sender == lender(fund), "Funds.update: Only the lender can update the fund");
require(
ensureNotZero(maxLoanDur_, false) <= MAX_LOAN_LENGTH && ensureNotZero(fundExpiry_, true) <= now + MAX_LOAN_LENGTH,
"Funds.update: fundExpiry and maxLoanDur cannot exceed 10 years"
); // Make sure someone can't request a loan for eternity
funds[fund].maxLoanDur = maxLoanDur_;
funds[fund].fundExpiry = fundExpiry_;
funds[fund].arbiter = arbiter_;
emit Update(fund, maxLoanDur_, fundExpiry_, arbiter_);
}
/**
* @notice Users update custom Loan Fund settings
* @param fund The Id of a Loan Fund
* @param minLoanAmt_ Minimum amount of tokens that can be borrowed from Loan Fund
* @param maxLoanAmt_ Maximum amount of tokens that can be borrowed from Loan Fund
* @param minLoanDur_ Minimum length of loan that can be requested from Loan Fund in seconds
* @param maxLoanDur_ Maximum length of loan that can be requested from Loan Fund in seconds
* @param fundExpiry_ Timestamp when all funds should be removable from Loan Fund
* @param interest_ The interest rate per second for a Loan Fund in RAY per second
* @param penalty_ The liquidation penalty rate per second for a Loan Fund in RAY per second
* @param fee_ The optional automation fee rate of Loan Fund in RAY per second
* @param liquidationRatio_ The liquidation ratio of Loan Fund in RAY
* @param arbiter_ Optional address of the arbiter for a Loan fund
*
* Note: msg.sender must be the lender of the Loan Fund
*/
function updateCustom(
bytes32 fund,
uint256 minLoanAmt_,
uint256 maxLoanAmt_,
uint256 minLoanDur_,
uint256 maxLoanDur_,
uint256 fundExpiry_,
uint256 interest_,
uint256 penalty_,
uint256 fee_,
uint256 liquidationRatio_,
address arbiter_
) external {
require(bools[fund].custom, "Funds.updateCustom: Fund must be a custom fund");
require(maxLoanAmt_ >= minLoanAmt_, "Funds.updateCustom: maxLoanAmt must be greater than or equal to minLoanAmt");
require(ensureNotZero(maxLoanDur_, false) >= minLoanDur_, "Funds.updateCustom: maxLoanDur must be greater than or equal to minLoanDur");
update(fund, maxLoanDur_, fundExpiry_, arbiter_);
funds[fund].minLoanAmt = minLoanAmt_;
funds[fund].maxLoanAmt = maxLoanAmt_;
funds[fund].minLoanDur = minLoanDur_;
funds[fund].interest = interest_;
funds[fund].penalty = penalty_;
funds[fund].fee = fee_;
funds[fund].liquidationRatio = liquidationRatio_;
}
/**
* @notice Lenders request loan from Loan Fund on behalf of Borrower
* @param fund The Id of a Loan Fund
* @param amount_ Amount of tokens to request
* @param collateral_ Amount of collateral to deposit in satoshis
* @param loanDur_ Length of loan request in seconds
* @param secretHashes_ 4 Borrower Secret Hashes and 4 Lender Secret Hashes
* @param pubKeyA_ Borrower Bitcoin public key to use for refunding collateral
* @param pubKeyB_ Lender Bitcoin public key to use for refunding collateral
*
* Note: Borrower client should verify params after Ethereum tx
* confirmation before locking Bitcoin.
*
*/
function request(
bytes32 fund,
address borrower_,
uint256 amount_,
uint256 collateral_,
uint256 loanDur_,
uint256 requestTimestamp_,
bytes32[8] calldata secretHashes_,
bytes calldata pubKeyA_,
bytes calldata pubKeyB_
) external returns (bytes32 loanIndex) {
require(msg.sender == lender(fund), "Funds.request: Only the lender can fulfill a loan request");
require(amount_ <= balance(fund), "Funds.request: Insufficient balance");
require(amount_ >= minLoanAmt(fund), "Funds.request: Amount requested must be greater than minLoanAmt");
require(amount_ <= maxLoanAmt(fund), "Funds.request: Amount requested must be less than maxLoanAmt");
require(loanDur_ >= minLoanDur(fund), "Funds.request: Loan duration must be greater than minLoanDur");
require(loanDur_ <= sub(fundExpiry(fund), now) && loanDur_ <= maxLoanDur(fund), "Funds.request: Loan duration must be less than maxLoanDur and expiry");
require(borrower_ != address(0), "Funds.request: Borrower address must be non-zero");
require(secretHashes_[0] != bytes32(0) && secretHashes_[1] != bytes32(0), "Funds.request: SecretHash1 & SecretHash2 should be non-zero");
require(secretHashes_[2] != bytes32(0) && secretHashes_[3] != bytes32(0), "Funds.request: SecretHash3 & SecretHash4 should be non-zero");
require(secretHashes_[4] != bytes32(0) && secretHashes_[5] != bytes32(0), "Funds.request: SecretHash5 & SecretHash6 should be non-zero");
require(secretHashes_[6] != bytes32(0) && secretHashes_[7] != bytes32(0), "Funds.request: SecretHash7 & SecretHash8 should be non-zero");
loanIndex = createLoan(fund, borrower_, amount_, collateral_, loanDur_, requestTimestamp_);
loanSetSecretHashes(fund, loanIndex, secretHashes_, pubKeyA_, pubKeyB_);
loanUpdateMarketLiquidity(fund, amount_);
loans.fund(loanIndex);
emit Request(fund, borrower_, amount_, collateral_, loanDur_, requestTimestamp_);
}
/**
* @notice Lenders withdraw tokens in Loan Fund
* @param fund The Id of a Loan Fund
* @param amount_ Amount of tokens to withdraw
*/
function withdraw(bytes32 fund, uint256 amount_) external {
withdrawTo(fund, amount_, msg.sender);
}
/**
* @notice Lenders withdraw tokens in Loan Fund
* @param fund The Id of a Loan Fund
* @param amount_ Amount of tokens to withdraw
* @param recipient_ Address that should receive the funds
*/
function withdrawTo(bytes32 fund, uint256 amount_, address recipient_) public {
require(msg.sender == lender(fund), "Funds.withdrawTo: Only the lender can withdraw tokens");
require(balance(fund) >= amount_, "Funds.withdrawTo: Insufficient balance");
if (bools[fund].compoundEnabled) {
uint256 cBalanceBefore = cToken.balanceOf(address(this));
redeemUnderlying(address(cToken), amount_);
uint256 cBalanceAfter = cToken.balanceOf(address(this));
uint256 cTokenToRemove = sub(cBalanceBefore, cBalanceAfter);
funds[fund].cBalance = sub(funds[fund].cBalance, cTokenToRemove);
require(token.transfer(recipient_, amount_), "Funds.withdrawTo: Token transfer failed");
if (!custom(fund)) {cTokenMarketLiquidity = sub(cTokenMarketLiquidity, cTokenToRemove);}
} else {
funds[fund].balance = sub(funds[fund].balance, amount_);
require(token.transfer(recipient_, amount_), "Funds.withdrawTo: Token transfer failed");
if (!custom(fund)) {tokenMarketLiquidity = sub(tokenMarketLiquidity, amount_);}
}
if (!custom(fund)) {calcGlobalInterest();}
emit Withdraw(fund, amount_, recipient_);
}
/**
* @notice Submit secretHashes to be used with future loans
* @param secretHashes_ List of secretHashes
*/
function generate(bytes32[] calldata secretHashes_) external {
for (uint i = 0; i < secretHashes_.length; i++) {
secretHashes[msg.sender].push(secretHashes_[i]);
}
}
/**
* @notice Set Lender or Arbiter Bitcoin Public Key
* @param pubKey_ Bitcoin Public Key
*/
function setPubKey(bytes calldata pubKey_) external { // Set PubKey for Fund
pubKeys[msg.sender] = pubKey_;
}
/**
* @notice Enable Compound for Loan Fund
* @param fund The Id of a Loan Fund
*/
function enableCompound(bytes32 fund) external {
require(compoundSet, "Funds.enableCompound: Cannot enable Compound as it has not been configured");
require(bools[fund].compoundEnabled == false, "Funds.enableCompound: Compound is already enabled");
require(msg.sender == lender(fund), "Funds.enableCompound: Only the lender can enable Compound");
uint256 cBalanceBefore = cToken.balanceOf(address(this));
mintCToken(address(token), address(cToken), funds[fund].balance);
uint256 cBalanceAfter = cToken.balanceOf(address(this));
uint256 cTokenToReturn = sub(cBalanceAfter, cBalanceBefore);
tokenMarketLiquidity = sub(tokenMarketLiquidity, funds[fund].balance);
cTokenMarketLiquidity = add(cTokenMarketLiquidity, cTokenToReturn);
bools[fund].compoundEnabled = true;
funds[fund].balance = 0;
funds[fund].cBalance = cTokenToReturn;
emit EnableCompound(fund);
}
/**
* @notice Disable Compound for Loan Fund
* @param fund The Id of a Loan Fund
*/
function disableCompound(bytes32 fund) external {
require(bools[fund].compoundEnabled, "Funds.disableCompound: Compound is already disabled");
require(msg.sender == lender(fund), "Funds.disableCompound: Only the lender can disable Compound");
uint256 balanceBefore = token.balanceOf(address(this));
redeemCToken(address(cToken), funds[fund].cBalance);
uint256 balanceAfter = token.balanceOf(address(this));
uint256 tokenToReturn = sub(balanceAfter, balanceBefore);
tokenMarketLiquidity = add(tokenMarketLiquidity, tokenToReturn);
cTokenMarketLiquidity = sub(cTokenMarketLiquidity, funds[fund].cBalance);
bools[fund].compoundEnabled = false;
funds[fund].cBalance = 0;
funds[fund].balance = tokenToReturn;
emit DisableCompound(fund);
}
/**
* @notice Decrease Total Borrow by Loans contract
* @param amount_ The amount of tokens to decrease totalBorrow by
*/
function decreaseTotalBorrow(uint256 amount_) external {
require(msg.sender == address(loans), "Funds.decreaseTotalBorrow: Only the Loans contract can perform this");
totalBorrow = sub(totalBorrow, amount_);
}
/**
* @notice Calculate and update Global Interest Rate
* @dev Implementation returns Global Interest Rate per second in RAY
*
* Note: Only updates interest rate if interestUpdateDelay has passed since last update
* if utilizationRatio increases newAPR = oldAPR + (min(10%, utilizationRatio) / 10)
* if utilizationRatio decreases newAPR = oldAPR - (max(10%, utilizationRatio) / 10)
* ΔAPR should be less than or equal to 1%
* For every 10% change in utilization ratio, the interest rate will change a maximum of 1%
* i.e. newAPR = 11.5% + (10% / 10) = 12.5%
*
*/
function calcGlobalInterest() public {
marketLiquidity = add(tokenMarketLiquidity, wmul(cTokenMarketLiquidity, cTokenExchangeRate()));
if (now > (add(lastGlobalInterestUpdated, interestUpdateDelay))) {
uint256 utilizationRatio;
if (totalBorrow != 0) {utilizationRatio = rdiv(totalBorrow, add(marketLiquidity, totalBorrow));}
if (utilizationRatio > lastUtilizationRatio) {
uint256 changeUtilizationRatio = sub(utilizationRatio, lastUtilizationRatio);
globalInterestRateNumerator = min(maxInterestRateNumerator, add(globalInterestRateNumerator, rdiv(min(maxUtilizationDelta, changeUtilizationRatio), utilizationInterestDivisor)));
} else {
uint256 changeUtilizationRatio = sub(lastUtilizationRatio, utilizationRatio);
globalInterestRateNumerator = max(minInterestRateNumerator, sub(globalInterestRateNumerator, rdiv(min(maxUtilizationDelta, changeUtilizationRatio), utilizationInterestDivisor)));
}
globalInterestRate = add(RAY, div(globalInterestRateNumerator, NUM_SECONDS_IN_YEAR));
lastGlobalInterestUpdated = now;
lastUtilizationRatio = utilizationRatio;
}
}
/**
* @notice Calculate compound interest for a length of time
* @param amount_ The amount of tokens
* @param rate_ 1 + nominal per second interest rate in percentage terms
* @param loanDur_ The loan duration in seconds
*/
function calcInterest(uint256 amount_, uint256 rate_, uint256 loanDur_) public pure returns (uint256) {
return sub(rmul(amount_, rpow(rate_, loanDur_)), amount_);
}
/**
* @dev Ensure null values for fundExpiry and maxLoanDur are set to MAX_LOAN_LENGTH
* @param value The value to be sanity checked
*/
function ensureNotZero(uint256 value, bool addNow) public view returns (uint256) {
if (value == 0) {
if (addNow) {
return now + MAX_LOAN_LENGTH;
}
return MAX_LOAN_LENGTH;
}
return value;
}
/**
* @dev Takes loan request parameters, creates loan, and returns loanIndex
* @param fund The Id of a Loan Fund
* @param amount_ Amount of tokens to request
* @param collateral_ Amount of collateral to deposit in satoshis
* @param loanDur_ Length of loan request in seconds
*/
function createLoan(
bytes32 fund,
address borrower_,
uint256 amount_,
uint256 collateral_,
uint256 loanDur_,
uint256 requestTimestamp_
) private returns (bytes32 loanIndex) {
loanIndex = loans.create(
now + loanDur_,
[borrower_, lender(fund), funds[fund].arbiter],
[
amount_,
calcInterest(amount_, interest(fund), loanDur_),
calcInterest(amount_, penalty(fund), loanDur_),
calcInterest(amount_, fee(fund), loanDur_),
collateral_,
liquidationRatio(fund),
requestTimestamp_
],
fund
);
}
/**
* @dev Takes loan request Bitcoin parameters, sets loan Public Keys and Secret Hashes
* @param fund The Id of the Loan Fund
* @param loan The Id of the Loan
* @param secretHashes_ 4 Borrower Secret Hashes and 4 Lender Secret Hashes
* @param pubKeyA_ Borrower Bitcoin public key to use for refunding collateral
* @param pubKeyB_ Lender Bitcoin public key to use for refunding collateral
*/
function loanSetSecretHashes(
bytes32 fund,
bytes32 loan,
bytes32[8] memory secretHashes_,
bytes memory pubKeyA_,
bytes memory pubKeyB_
) private {
loans.setSecretHashes(
loan,
[ secretHashes_[0], secretHashes_[1], secretHashes_[2], secretHashes_[3] ],
[ secretHashes_[4], secretHashes_[5], secretHashes_[6], secretHashes_[7] ],
getSecretHashesForLoan(arbiter(fund)),
pubKeyA_,
pubKeyB_,
pubKeys[arbiter(fund)]
);
}
/**
* @dev Updates market liquidity based on amount of tokens being requested to borrow
* @param fund Loan Id of the Loan Fund
* @param amount_ The amount of tokens that are being requested
*/
function loanUpdateMarketLiquidity(bytes32 fund, uint256 amount_) private {
if (bools[fund].compoundEnabled) {
uint256 cBalanceBefore = cToken.balanceOf(address(this));
redeemUnderlying(address(cToken), amount_);
uint256 cBalanceAfter = cToken.balanceOf(address(this));
uint256 cTokenToRemove = sub(cBalanceBefore, cBalanceAfter);
funds[fund].cBalance = sub(funds[fund].cBalance, cTokenToRemove);
if (!custom(fund)) {cTokenMarketLiquidity = sub(cTokenMarketLiquidity, cTokenToRemove);}
} else {
funds[fund].balance = sub(funds[fund].balance, amount_);
if (!custom(fund)) {tokenMarketLiquidity = sub(tokenMarketLiquidity, amount_);}
}
if (!custom(fund)) {
totalBorrow = add(totalBorrow, amount_);
calcGlobalInterest();
}
}
/**
* @dev Get the next 4 secret hashes required for loan
* @param addr_ Address of Lender or Arbiter
*/
function getSecretHashesForLoan(address addr_) private returns (bytes32[4] memory) {
secretHashIndex[addr_] = add(secretHashIndex[addr_], 4);
require(secretHashesCount(addr_) >= secretHashIndex[addr_], "Funds.getSecretHashesForLoan: Not enough secrets generated");
return [
secretHashes[addr_][sub(secretHashIndex[addr_], 4)],
secretHashes[addr_][sub(secretHashIndex[addr_], 3)],
secretHashes[addr_][sub(secretHashIndex[addr_], 2)],
secretHashes[addr_][sub(secretHashIndex[addr_], 1)]
];
}
}
| * @notice Get maximum loan duration able to be requested by a 'borrower' @param fund The Id of a Loan Fund @return The maximum duration loan that can be requested from a Loan Fund/ | function fundExpiry(bytes32 fund) public view returns (uint256) {
return funds[fund].fundExpiry;
}
| 5,528,115 | [
1,
967,
4207,
28183,
3734,
7752,
358,
506,
3764,
635,
279,
296,
70,
15318,
264,
11,
225,
284,
1074,
1021,
3124,
434,
279,
3176,
304,
478,
1074,
327,
1021,
4207,
3734,
28183,
716,
848,
506,
3764,
628,
279,
3176,
304,
478,
1074,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
284,
1074,
14633,
12,
3890,
1578,
284,
1074,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
284,
19156,
63,
74,
1074,
8009,
74,
1074,
14633,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.6.8;
import "./ProtoBufRuntime.sol";
import "./GoogleProtobufAny.sol";
library PartSetHeader {
//struct definition
struct Data {
uint64 total;
bytes hash;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[3] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_total(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_hash(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_total(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.total = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_hash(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.hash = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
if (r.total != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_uint64(r.total, pointer, bs);
}
if (r.hash.length != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.hash, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_uint64(r.total);
e += 1 + ProtoBufRuntime._sz_lendelim(r.hash.length);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.total != 0) {
return false;
}
if (r.hash.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.total = input.total;
output.hash = input.hash;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library PartSetHeader
library BlockID {
//struct definition
struct Data {
bytes hash;
PartSetHeader.Data part_set_header;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[3] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_hash(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_part_set_header(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_hash(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.hash = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_part_set_header(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(PartSetHeader.Data memory x, uint256 sz) = _decode_PartSetHeader(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.part_set_header = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_PartSetHeader(uint256 p, bytes memory bs)
internal
pure
returns (PartSetHeader.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(PartSetHeader.Data memory r, ) = PartSetHeader._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
if (r.hash.length != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.hash, pointer, bs);
}
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += PartSetHeader._encode_nested(r.part_set_header, pointer, bs);
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_lendelim(r.hash.length);
e += 1 + ProtoBufRuntime._sz_lendelim(PartSetHeader._estimate(r.part_set_header));
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.hash.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.hash = input.hash;
PartSetHeader.store(input.part_set_header, output.part_set_header);
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library BlockID
library Timestamp {
//struct definition
struct Data {
int64 secs;
int64 nanos;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[3] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_secs(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_nanos(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_secs(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.secs = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_nanos(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.nanos = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
if (r.secs != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_int64(r.secs, pointer, bs);
}
if (r.nanos != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_int64(r.nanos, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_int64(r.secs);
e += 1 + ProtoBufRuntime._sz_int64(r.nanos);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.secs != 0) {
return false;
}
if (r.nanos != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.secs = input.secs;
output.nanos = input.nanos;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library Timestamp
library Consensus {
//struct definition
struct Data {
uint64 height;
uint64 app;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[3] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_height(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_app(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_height(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.height = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_app(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.app = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
if (r.height != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_uint64(r.height, pointer, bs);
}
if (r.app != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_uint64(r.app, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_uint64(r.height);
e += 1 + ProtoBufRuntime._sz_uint64(r.app);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.height != 0) {
return false;
}
if (r.app != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.height = input.height;
output.app = input.app;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library Consensus
library TmHeader {
//struct definition
struct Data {
Consensus.Data version;
string chain_id;
int64 height;
Timestamp.Data time;
BlockID.Data last_block_id;
bytes last_commit_hash;
bytes data_hash;
bytes validators_hash;
bytes next_validators_hash;
bytes consensus_hash;
bytes app_hash;
bytes last_results_hash;
bytes evidence_hash;
bytes proposer_address;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[15] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_version(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_chain_id(pointer, bs, r, counters);
}
else if (fieldId == 3) {
pointer += _read_height(pointer, bs, r, counters);
}
else if (fieldId == 4) {
pointer += _read_time(pointer, bs, r, counters);
}
else if (fieldId == 5) {
pointer += _read_last_block_id(pointer, bs, r, counters);
}
else if (fieldId == 6) {
pointer += _read_last_commit_hash(pointer, bs, r, counters);
}
else if (fieldId == 7) {
pointer += _read_data_hash(pointer, bs, r, counters);
}
else if (fieldId == 8) {
pointer += _read_validators_hash(pointer, bs, r, counters);
}
else if (fieldId == 9) {
pointer += _read_next_validators_hash(pointer, bs, r, counters);
}
else if (fieldId == 10) {
pointer += _read_consensus_hash(pointer, bs, r, counters);
}
else if (fieldId == 11) {
pointer += _read_app_hash(pointer, bs, r, counters);
}
else if (fieldId == 12) {
pointer += _read_last_results_hash(pointer, bs, r, counters);
}
else if (fieldId == 13) {
pointer += _read_evidence_hash(pointer, bs, r, counters);
}
else if (fieldId == 14) {
pointer += _read_proposer_address(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_version(
uint256 p,
bytes memory bs,
Data memory r,
uint[15] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(Consensus.Data memory x, uint256 sz) = _decode_Consensus(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.version = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_chain_id(
uint256 p,
bytes memory bs,
Data memory r,
uint[15] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(string memory x, uint256 sz) = ProtoBufRuntime._decode_string(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.chain_id = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_height(
uint256 p,
bytes memory bs,
Data memory r,
uint[15] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs);
if (isNil(r)) {
counters[3] += 1;
} else {
r.height = x;
if (counters[3] > 0) counters[3] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_time(
uint256 p,
bytes memory bs,
Data memory r,
uint[15] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(Timestamp.Data memory x, uint256 sz) = _decode_Timestamp(p, bs);
if (isNil(r)) {
counters[4] += 1;
} else {
r.time = x;
if (counters[4] > 0) counters[4] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_last_block_id(
uint256 p,
bytes memory bs,
Data memory r,
uint[15] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(BlockID.Data memory x, uint256 sz) = _decode_BlockID(p, bs);
if (isNil(r)) {
counters[5] += 1;
} else {
r.last_block_id = x;
if (counters[5] > 0) counters[5] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_last_commit_hash(
uint256 p,
bytes memory bs,
Data memory r,
uint[15] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[6] += 1;
} else {
r.last_commit_hash = x;
if (counters[6] > 0) counters[6] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_data_hash(
uint256 p,
bytes memory bs,
Data memory r,
uint[15] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[7] += 1;
} else {
r.data_hash = x;
if (counters[7] > 0) counters[7] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_validators_hash(
uint256 p,
bytes memory bs,
Data memory r,
uint[15] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[8] += 1;
} else {
r.validators_hash = x;
if (counters[8] > 0) counters[8] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_next_validators_hash(
uint256 p,
bytes memory bs,
Data memory r,
uint[15] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[9] += 1;
} else {
r.next_validators_hash = x;
if (counters[9] > 0) counters[9] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_consensus_hash(
uint256 p,
bytes memory bs,
Data memory r,
uint[15] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[10] += 1;
} else {
r.consensus_hash = x;
if (counters[10] > 0) counters[10] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_app_hash(
uint256 p,
bytes memory bs,
Data memory r,
uint[15] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[11] += 1;
} else {
r.app_hash = x;
if (counters[11] > 0) counters[11] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_last_results_hash(
uint256 p,
bytes memory bs,
Data memory r,
uint[15] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[12] += 1;
} else {
r.last_results_hash = x;
if (counters[12] > 0) counters[12] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_evidence_hash(
uint256 p,
bytes memory bs,
Data memory r,
uint[15] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[13] += 1;
} else {
r.evidence_hash = x;
if (counters[13] > 0) counters[13] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_proposer_address(
uint256 p,
bytes memory bs,
Data memory r,
uint[15] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[14] += 1;
} else {
r.proposer_address = x;
if (counters[14] > 0) counters[14] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_Consensus(uint256 p, bytes memory bs)
internal
pure
returns (Consensus.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(Consensus.Data memory r, ) = Consensus._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_Timestamp(uint256 p, bytes memory bs)
internal
pure
returns (Timestamp.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(Timestamp.Data memory r, ) = Timestamp._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_BlockID(uint256 p, bytes memory bs)
internal
pure
returns (BlockID.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(BlockID.Data memory r, ) = BlockID._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += Consensus._encode_nested(r.version, pointer, bs);
if (bytes(r.chain_id).length != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_string(r.chain_id, pointer, bs);
}
if (r.height != 0) {
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_int64(r.height, pointer, bs);
}
pointer += ProtoBufRuntime._encode_key(
4,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += Timestamp._encode_nested(r.time, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
5,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += BlockID._encode_nested(r.last_block_id, pointer, bs);
if (r.last_commit_hash.length != 0) {
pointer += ProtoBufRuntime._encode_key(
6,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.last_commit_hash, pointer, bs);
}
if (r.data_hash.length != 0) {
pointer += ProtoBufRuntime._encode_key(
7,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.data_hash, pointer, bs);
}
if (r.validators_hash.length != 0) {
pointer += ProtoBufRuntime._encode_key(
8,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.validators_hash, pointer, bs);
}
if (r.next_validators_hash.length != 0) {
pointer += ProtoBufRuntime._encode_key(
9,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.next_validators_hash, pointer, bs);
}
if (r.consensus_hash.length != 0) {
pointer += ProtoBufRuntime._encode_key(
10,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.consensus_hash, pointer, bs);
}
if (r.app_hash.length != 0) {
pointer += ProtoBufRuntime._encode_key(
11,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.app_hash, pointer, bs);
}
if (r.last_results_hash.length != 0) {
pointer += ProtoBufRuntime._encode_key(
12,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.last_results_hash, pointer, bs);
}
if (r.evidence_hash.length != 0) {
pointer += ProtoBufRuntime._encode_key(
13,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.evidence_hash, pointer, bs);
}
if (r.proposer_address.length != 0) {
pointer += ProtoBufRuntime._encode_key(
14,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.proposer_address, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_lendelim(Consensus._estimate(r.version));
e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.chain_id).length);
e += 1 + ProtoBufRuntime._sz_int64(r.height);
e += 1 + ProtoBufRuntime._sz_lendelim(Timestamp._estimate(r.time));
e += 1 + ProtoBufRuntime._sz_lendelim(BlockID._estimate(r.last_block_id));
e += 1 + ProtoBufRuntime._sz_lendelim(r.last_commit_hash.length);
e += 1 + ProtoBufRuntime._sz_lendelim(r.data_hash.length);
e += 1 + ProtoBufRuntime._sz_lendelim(r.validators_hash.length);
e += 1 + ProtoBufRuntime._sz_lendelim(r.next_validators_hash.length);
e += 1 + ProtoBufRuntime._sz_lendelim(r.consensus_hash.length);
e += 1 + ProtoBufRuntime._sz_lendelim(r.app_hash.length);
e += 1 + ProtoBufRuntime._sz_lendelim(r.last_results_hash.length);
e += 1 + ProtoBufRuntime._sz_lendelim(r.evidence_hash.length);
e += 1 + ProtoBufRuntime._sz_lendelim(r.proposer_address.length);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (bytes(r.chain_id).length != 0) {
return false;
}
if (r.height != 0) {
return false;
}
if (r.last_commit_hash.length != 0) {
return false;
}
if (r.data_hash.length != 0) {
return false;
}
if (r.validators_hash.length != 0) {
return false;
}
if (r.next_validators_hash.length != 0) {
return false;
}
if (r.consensus_hash.length != 0) {
return false;
}
if (r.app_hash.length != 0) {
return false;
}
if (r.last_results_hash.length != 0) {
return false;
}
if (r.evidence_hash.length != 0) {
return false;
}
if (r.proposer_address.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
Consensus.store(input.version, output.version);
output.chain_id = input.chain_id;
output.height = input.height;
Timestamp.store(input.time, output.time);
BlockID.store(input.last_block_id, output.last_block_id);
output.last_commit_hash = input.last_commit_hash;
output.data_hash = input.data_hash;
output.validators_hash = input.validators_hash;
output.next_validators_hash = input.next_validators_hash;
output.consensus_hash = input.consensus_hash;
output.app_hash = input.app_hash;
output.last_results_hash = input.last_results_hash;
output.evidence_hash = input.evidence_hash;
output.proposer_address = input.proposer_address;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library TmHeader
library Vote {
//struct definition
struct Data {
TYPES_PROTO_GLOBAL_ENUMS.SignedMsgType typ;
int64 height;
int64 round;
BlockID.Data block_id;
Timestamp.Data timestamp;
bytes validator_address;
int64 validator_index;
bytes signature;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[9] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_typ(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_height(pointer, bs, r, counters);
}
else if (fieldId == 3) {
pointer += _read_round(pointer, bs, r, counters);
}
else if (fieldId == 4) {
pointer += _read_block_id(pointer, bs, r, counters);
}
else if (fieldId == 5) {
pointer += _read_timestamp(pointer, bs, r, counters);
}
else if (fieldId == 6) {
pointer += _read_validator_address(pointer, bs, r, counters);
}
else if (fieldId == 7) {
pointer += _read_validator_index(pointer, bs, r, counters);
}
else if (fieldId == 8) {
pointer += _read_signature(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_typ(
uint256 p,
bytes memory bs,
Data memory r,
uint[9] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs);
TYPES_PROTO_GLOBAL_ENUMS.SignedMsgType x = TYPES_PROTO_GLOBAL_ENUMS.decode_SignedMsgType(tmp);
if (isNil(r)) {
counters[1] += 1;
} else {
r.typ = x;
if(counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_height(
uint256 p,
bytes memory bs,
Data memory r,
uint[9] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.height = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_round(
uint256 p,
bytes memory bs,
Data memory r,
uint[9] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs);
if (isNil(r)) {
counters[3] += 1;
} else {
r.round = x;
if (counters[3] > 0) counters[3] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_block_id(
uint256 p,
bytes memory bs,
Data memory r,
uint[9] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(BlockID.Data memory x, uint256 sz) = _decode_BlockID(p, bs);
if (isNil(r)) {
counters[4] += 1;
} else {
r.block_id = x;
if (counters[4] > 0) counters[4] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_timestamp(
uint256 p,
bytes memory bs,
Data memory r,
uint[9] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(Timestamp.Data memory x, uint256 sz) = _decode_Timestamp(p, bs);
if (isNil(r)) {
counters[5] += 1;
} else {
r.timestamp = x;
if (counters[5] > 0) counters[5] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_validator_address(
uint256 p,
bytes memory bs,
Data memory r,
uint[9] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[6] += 1;
} else {
r.validator_address = x;
if (counters[6] > 0) counters[6] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_validator_index(
uint256 p,
bytes memory bs,
Data memory r,
uint[9] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs);
if (isNil(r)) {
counters[7] += 1;
} else {
r.validator_index = x;
if (counters[7] > 0) counters[7] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_signature(
uint256 p,
bytes memory bs,
Data memory r,
uint[9] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[8] += 1;
} else {
r.signature = x;
if (counters[8] > 0) counters[8] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_BlockID(uint256 p, bytes memory bs)
internal
pure
returns (BlockID.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(BlockID.Data memory r, ) = BlockID._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_Timestamp(uint256 p, bytes memory bs)
internal
pure
returns (Timestamp.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(Timestamp.Data memory r, ) = Timestamp._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
if (uint(r.typ) != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
int32 _enum_typ = TYPES_PROTO_GLOBAL_ENUMS.encode_SignedMsgType(r.typ);
pointer += ProtoBufRuntime._encode_enum(_enum_typ, pointer, bs);
}
if (r.height != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_int64(r.height, pointer, bs);
}
if (r.round != 0) {
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_int64(r.round, pointer, bs);
}
pointer += ProtoBufRuntime._encode_key(
4,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += BlockID._encode_nested(r.block_id, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
5,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += Timestamp._encode_nested(r.timestamp, pointer, bs);
if (r.validator_address.length != 0) {
pointer += ProtoBufRuntime._encode_key(
6,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.validator_address, pointer, bs);
}
if (r.validator_index != 0) {
pointer += ProtoBufRuntime._encode_key(
7,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_int64(r.validator_index, pointer, bs);
}
if (r.signature.length != 0) {
pointer += ProtoBufRuntime._encode_key(
8,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.signature, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_enum(TYPES_PROTO_GLOBAL_ENUMS.encode_SignedMsgType(r.typ));
e += 1 + ProtoBufRuntime._sz_int64(r.height);
e += 1 + ProtoBufRuntime._sz_int64(r.round);
e += 1 + ProtoBufRuntime._sz_lendelim(BlockID._estimate(r.block_id));
e += 1 + ProtoBufRuntime._sz_lendelim(Timestamp._estimate(r.timestamp));
e += 1 + ProtoBufRuntime._sz_lendelim(r.validator_address.length);
e += 1 + ProtoBufRuntime._sz_int64(r.validator_index);
e += 1 + ProtoBufRuntime._sz_lendelim(r.signature.length);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (uint(r.typ) != 0) {
return false;
}
if (r.height != 0) {
return false;
}
if (r.round != 0) {
return false;
}
if (r.validator_address.length != 0) {
return false;
}
if (r.validator_index != 0) {
return false;
}
if (r.signature.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.typ = input.typ;
output.height = input.height;
output.round = input.round;
BlockID.store(input.block_id, output.block_id);
Timestamp.store(input.timestamp, output.timestamp);
output.validator_address = input.validator_address;
output.validator_index = input.validator_index;
output.signature = input.signature;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library Vote
library Commit {
//struct definition
struct Data {
int64 height;
int64 round;
BlockID.Data block_id;
CommitSig.Data[] signatures;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[5] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_height(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_round(pointer, bs, r, counters);
}
else if (fieldId == 3) {
pointer += _read_block_id(pointer, bs, r, counters);
}
else if (fieldId == 4) {
pointer += _read_signatures(pointer, bs, nil(), counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
pointer = offset;
r.signatures = new CommitSig.Data[](counters[4]);
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_height(pointer, bs, nil(), counters);
}
else if (fieldId == 2) {
pointer += _read_round(pointer, bs, nil(), counters);
}
else if (fieldId == 3) {
pointer += _read_block_id(pointer, bs, nil(), counters);
}
else if (fieldId == 4) {
pointer += _read_signatures(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_height(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.height = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_round(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.round = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_block_id(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(BlockID.Data memory x, uint256 sz) = _decode_BlockID(p, bs);
if (isNil(r)) {
counters[3] += 1;
} else {
r.block_id = x;
if (counters[3] > 0) counters[3] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_signatures(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(CommitSig.Data memory x, uint256 sz) = _decode_CommitSig(p, bs);
if (isNil(r)) {
counters[4] += 1;
} else {
r.signatures[r.signatures.length - counters[4]] = x;
if (counters[4] > 0) counters[4] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_BlockID(uint256 p, bytes memory bs)
internal
pure
returns (BlockID.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(BlockID.Data memory r, ) = BlockID._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_CommitSig(uint256 p, bytes memory bs)
internal
pure
returns (CommitSig.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(CommitSig.Data memory r, ) = CommitSig._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
uint256 i;
if (r.height != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_int64(r.height, pointer, bs);
}
if (r.round != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_int64(r.round, pointer, bs);
}
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += BlockID._encode_nested(r.block_id, pointer, bs);
if (r.signatures.length != 0) {
for(i = 0; i < r.signatures.length; i++) {
pointer += ProtoBufRuntime._encode_key(
4,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs)
;
pointer += CommitSig._encode_nested(r.signatures[i], pointer, bs);
}
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;uint256 i;
e += 1 + ProtoBufRuntime._sz_int64(r.height);
e += 1 + ProtoBufRuntime._sz_int64(r.round);
e += 1 + ProtoBufRuntime._sz_lendelim(BlockID._estimate(r.block_id));
for(i = 0; i < r.signatures.length; i++) {
e += 1 + ProtoBufRuntime._sz_lendelim(CommitSig._estimate(r.signatures[i]));
}
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.height != 0) {
return false;
}
if (r.round != 0) {
return false;
}
if (r.signatures.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.height = input.height;
output.round = input.round;
BlockID.store(input.block_id, output.block_id);
for(uint256 i4 = 0; i4 < input.signatures.length; i4++) {
output.signatures.push(input.signatures[i4]);
}
}
//array helpers for Signatures
/**
* @dev Add value to an array
* @param self The in-memory struct
* @param value The value to add
*/
function addSignatures(Data memory self, CommitSig.Data memory value) internal pure {
/**
* First resize the array. Then add the new element to the end.
*/
CommitSig.Data[] memory tmp = new CommitSig.Data[](self.signatures.length + 1);
for (uint256 i = 0; i < self.signatures.length; i++) {
tmp[i] = self.signatures[i];
}
tmp[self.signatures.length] = value;
self.signatures = tmp;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library Commit
library CommitSig {
//struct definition
struct Data {
TYPES_PROTO_GLOBAL_ENUMS.BlockIDFlag block_id_flag;
bytes validator_address;
Timestamp.Data timestamp;
bytes signature;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[5] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_block_id_flag(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_validator_address(pointer, bs, r, counters);
}
else if (fieldId == 3) {
pointer += _read_timestamp(pointer, bs, r, counters);
}
else if (fieldId == 4) {
pointer += _read_signature(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_block_id_flag(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs);
TYPES_PROTO_GLOBAL_ENUMS.BlockIDFlag x = TYPES_PROTO_GLOBAL_ENUMS.decode_BlockIDFlag(tmp);
if (isNil(r)) {
counters[1] += 1;
} else {
r.block_id_flag = x;
if(counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_validator_address(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.validator_address = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_timestamp(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(Timestamp.Data memory x, uint256 sz) = _decode_Timestamp(p, bs);
if (isNil(r)) {
counters[3] += 1;
} else {
r.timestamp = x;
if (counters[3] > 0) counters[3] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_signature(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[4] += 1;
} else {
r.signature = x;
if (counters[4] > 0) counters[4] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_Timestamp(uint256 p, bytes memory bs)
internal
pure
returns (Timestamp.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(Timestamp.Data memory r, ) = Timestamp._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
if (uint(r.block_id_flag) != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
int32 _enum_block_id_flag = TYPES_PROTO_GLOBAL_ENUMS.encode_BlockIDFlag(r.block_id_flag);
pointer += ProtoBufRuntime._encode_enum(_enum_block_id_flag, pointer, bs);
}
if (r.validator_address.length != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.validator_address, pointer, bs);
}
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += Timestamp._encode_nested(r.timestamp, pointer, bs);
if (r.signature.length != 0) {
pointer += ProtoBufRuntime._encode_key(
4,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.signature, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_enum(TYPES_PROTO_GLOBAL_ENUMS.encode_BlockIDFlag(r.block_id_flag));
e += 1 + ProtoBufRuntime._sz_lendelim(r.validator_address.length);
e += 1 + ProtoBufRuntime._sz_lendelim(Timestamp._estimate(r.timestamp));
e += 1 + ProtoBufRuntime._sz_lendelim(r.signature.length);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (uint(r.block_id_flag) != 0) {
return false;
}
if (r.validator_address.length != 0) {
return false;
}
if (r.signature.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.block_id_flag = input.block_id_flag;
output.validator_address = input.validator_address;
Timestamp.store(input.timestamp, output.timestamp);
output.signature = input.signature;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library CommitSig
library SignedHeader {
//struct definition
struct Data {
TmHeader.Data header;
Commit.Data commit;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[3] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_header(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_commit(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_header(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(TmHeader.Data memory x, uint256 sz) = _decode_TmHeader(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.header = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_commit(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(Commit.Data memory x, uint256 sz) = _decode_Commit(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.commit = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_TmHeader(uint256 p, bytes memory bs)
internal
pure
returns (TmHeader.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(TmHeader.Data memory r, ) = TmHeader._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_Commit(uint256 p, bytes memory bs)
internal
pure
returns (Commit.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(Commit.Data memory r, ) = Commit._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += TmHeader._encode_nested(r.header, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += Commit._encode_nested(r.commit, pointer, bs);
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_lendelim(TmHeader._estimate(r.header));
e += 1 + ProtoBufRuntime._sz_lendelim(Commit._estimate(r.commit));
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
TmHeader.store(input.header, output.header);
Commit.store(input.commit, output.commit);
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library SignedHeader
library CanonicalBlockID {
//struct definition
struct Data {
bytes hash;
CanonicalPartSetHeader.Data part_set_header;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[3] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_hash(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_part_set_header(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_hash(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.hash = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_part_set_header(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(CanonicalPartSetHeader.Data memory x, uint256 sz) = _decode_CanonicalPartSetHeader(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.part_set_header = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_CanonicalPartSetHeader(uint256 p, bytes memory bs)
internal
pure
returns (CanonicalPartSetHeader.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(CanonicalPartSetHeader.Data memory r, ) = CanonicalPartSetHeader._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
if (r.hash.length != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.hash, pointer, bs);
}
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += CanonicalPartSetHeader._encode_nested(r.part_set_header, pointer, bs);
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_lendelim(r.hash.length);
e += 1 + ProtoBufRuntime._sz_lendelim(CanonicalPartSetHeader._estimate(r.part_set_header));
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.hash.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.hash = input.hash;
CanonicalPartSetHeader.store(input.part_set_header, output.part_set_header);
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library CanonicalBlockID
library CanonicalPartSetHeader {
//struct definition
struct Data {
uint64 total;
bytes hash;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[3] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_total(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_hash(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_total(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.total = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_hash(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.hash = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
if (r.total != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_uint64(r.total, pointer, bs);
}
if (r.hash.length != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.hash, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_uint64(r.total);
e += 1 + ProtoBufRuntime._sz_lendelim(r.hash.length);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.total != 0) {
return false;
}
if (r.hash.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.total = input.total;
output.hash = input.hash;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library CanonicalPartSetHeader
library CanonicalVote {
//struct definition
struct Data {
TYPES_PROTO_GLOBAL_ENUMS.SignedMsgType typ;
int64 height;
int64 round;
CanonicalBlockID.Data block_id;
Timestamp.Data timestamp;
string chain_id;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[7] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_typ(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_height(pointer, bs, r, counters);
}
else if (fieldId == 3) {
pointer += _read_round(pointer, bs, r, counters);
}
else if (fieldId == 4) {
pointer += _read_block_id(pointer, bs, r, counters);
}
else if (fieldId == 5) {
pointer += _read_timestamp(pointer, bs, r, counters);
}
else if (fieldId == 6) {
pointer += _read_chain_id(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_typ(
uint256 p,
bytes memory bs,
Data memory r,
uint[7] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs);
TYPES_PROTO_GLOBAL_ENUMS.SignedMsgType x = TYPES_PROTO_GLOBAL_ENUMS.decode_SignedMsgType(tmp);
if (isNil(r)) {
counters[1] += 1;
} else {
r.typ = x;
if(counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_height(
uint256 p,
bytes memory bs,
Data memory r,
uint[7] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 x, uint256 sz) = ProtoBufRuntime._decode_sfixed64(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.height = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_round(
uint256 p,
bytes memory bs,
Data memory r,
uint[7] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 x, uint256 sz) = ProtoBufRuntime._decode_sfixed64(p, bs);
if (isNil(r)) {
counters[3] += 1;
} else {
r.round = x;
if (counters[3] > 0) counters[3] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_block_id(
uint256 p,
bytes memory bs,
Data memory r,
uint[7] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(CanonicalBlockID.Data memory x, uint256 sz) = _decode_CanonicalBlockID(p, bs);
if (isNil(r)) {
counters[4] += 1;
} else {
r.block_id = x;
if (counters[4] > 0) counters[4] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_timestamp(
uint256 p,
bytes memory bs,
Data memory r,
uint[7] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(Timestamp.Data memory x, uint256 sz) = _decode_Timestamp(p, bs);
if (isNil(r)) {
counters[5] += 1;
} else {
r.timestamp = x;
if (counters[5] > 0) counters[5] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_chain_id(
uint256 p,
bytes memory bs,
Data memory r,
uint[7] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(string memory x, uint256 sz) = ProtoBufRuntime._decode_string(p, bs);
if (isNil(r)) {
counters[6] += 1;
} else {
r.chain_id = x;
if (counters[6] > 0) counters[6] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_CanonicalBlockID(uint256 p, bytes memory bs)
internal
pure
returns (CanonicalBlockID.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(CanonicalBlockID.Data memory r, ) = CanonicalBlockID._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_Timestamp(uint256 p, bytes memory bs)
internal
pure
returns (Timestamp.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(Timestamp.Data memory r, ) = Timestamp._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
if (uint(r.typ) != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
int32 _enum_typ = TYPES_PROTO_GLOBAL_ENUMS.encode_SignedMsgType(r.typ);
pointer += ProtoBufRuntime._encode_enum(_enum_typ, pointer, bs);
}
if (r.height != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.Fixed64,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_sfixed64(r.height, pointer, bs);
}
if (r.round != 0) {
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.Fixed64,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_sfixed64(r.round, pointer, bs);
}
pointer += ProtoBufRuntime._encode_key(
4,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += CanonicalBlockID._encode_nested(r.block_id, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
5,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += Timestamp._encode_nested(r.timestamp, pointer, bs);
if (bytes(r.chain_id).length != 0) {
pointer += ProtoBufRuntime._encode_key(
6,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_string(r.chain_id, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_enum(TYPES_PROTO_GLOBAL_ENUMS.encode_SignedMsgType(r.typ));
e += 1 + 8;
e += 1 + 8;
e += 1 + ProtoBufRuntime._sz_lendelim(CanonicalBlockID._estimate(r.block_id));
e += 1 + ProtoBufRuntime._sz_lendelim(Timestamp._estimate(r.timestamp));
e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.chain_id).length);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (uint(r.typ) != 0) {
return false;
}
if (r.height != 0) {
return false;
}
if (r.round != 0) {
return false;
}
if (bytes(r.chain_id).length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.typ = input.typ;
output.height = input.height;
output.round = input.round;
CanonicalBlockID.store(input.block_id, output.block_id);
Timestamp.store(input.timestamp, output.timestamp);
output.chain_id = input.chain_id;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library CanonicalVote
library Height {
//struct definition
struct Data {
uint64 revision_number;
uint64 revision_height;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[3] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_revision_number(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_revision_height(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_revision_number(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.revision_number = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_revision_height(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.revision_height = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
if (r.revision_number != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_uint64(r.revision_number, pointer, bs);
}
if (r.revision_height != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_uint64(r.revision_height, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_uint64(r.revision_number);
e += 1 + ProtoBufRuntime._sz_uint64(r.revision_height);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.revision_number != 0) {
return false;
}
if (r.revision_height != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.revision_number = input.revision_number;
output.revision_height = input.revision_height;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library Height
library TYPES_PROTO_GLOBAL_ENUMS {
//enum definition
// Solidity enum definitions
enum BlockIDFlag {
BLOCK_ID_FLAG_UNKNOWN,
BLOCK_ID_FLAG_ABSENT,
BLOCK_ID_FLAG_COMMIT,
BLOCK_ID_FLAG_NIL
}
// Solidity enum encoder
function encode_BlockIDFlag(BlockIDFlag x) internal pure returns (int32) {
if (x == BlockIDFlag.BLOCK_ID_FLAG_UNKNOWN) {
return 0;
}
if (x == BlockIDFlag.BLOCK_ID_FLAG_ABSENT) {
return 1;
}
if (x == BlockIDFlag.BLOCK_ID_FLAG_COMMIT) {
return 2;
}
if (x == BlockIDFlag.BLOCK_ID_FLAG_NIL) {
return 3;
}
revert();
}
// Solidity enum decoder
function decode_BlockIDFlag(int64 x) internal pure returns (BlockIDFlag) {
if (x == 0) {
return BlockIDFlag.BLOCK_ID_FLAG_UNKNOWN;
}
if (x == 1) {
return BlockIDFlag.BLOCK_ID_FLAG_ABSENT;
}
if (x == 2) {
return BlockIDFlag.BLOCK_ID_FLAG_COMMIT;
}
if (x == 3) {
return BlockIDFlag.BLOCK_ID_FLAG_NIL;
}
revert();
}
// Solidity enum definitions
enum SignedMsgType {
SIGNED_MSG_TYPE_UNKNOWN,
SIGNED_MSG_TYPE_PREVOTE,
SIGNED_MSG_TYPE_PRECOMMIT,
SIGNED_MSG_TYPE_PROPOSAL
}
// Solidity enum encoder
function encode_SignedMsgType(SignedMsgType x) internal pure returns (int32) {
if (x == SignedMsgType.SIGNED_MSG_TYPE_UNKNOWN) {
return 0;
}
if (x == SignedMsgType.SIGNED_MSG_TYPE_PREVOTE) {
return 1;
}
if (x == SignedMsgType.SIGNED_MSG_TYPE_PRECOMMIT) {
return 2;
}
if (x == SignedMsgType.SIGNED_MSG_TYPE_PROPOSAL) {
return 32;
}
revert();
}
// Solidity enum decoder
function decode_SignedMsgType(int64 x) internal pure returns (SignedMsgType) {
if (x == 0) {
return SignedMsgType.SIGNED_MSG_TYPE_UNKNOWN;
}
if (x == 1) {
return SignedMsgType.SIGNED_MSG_TYPE_PREVOTE;
}
if (x == 2) {
return SignedMsgType.SIGNED_MSG_TYPE_PRECOMMIT;
}
if (x == 32) {
return SignedMsgType.SIGNED_MSG_TYPE_PROPOSAL;
}
revert();
}
}
//library TYPES_PROTO_GLOBAL_ENUMS | * @dev The decoder for reading a field @param p The offset of bytes array to start decode @param bs The bytes array to be decoded @param r The in-memory struct @param counters The counters for repeated fields @return The number of bytes decoded/* if `r` is NULL, then only counting the number of fields./ | function _read_part_set_header(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
(CanonicalPartSetHeader.Data memory x, uint256 sz) = _decode_CanonicalPartSetHeader(p, bs);
if (isNil(r)) {
counters[2] += 1;
r.part_set_header = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
| 2,568,510 | [
1,
1986,
8320,
364,
6453,
279,
652,
225,
293,
1021,
1384,
434,
1731,
526,
358,
787,
2495,
225,
7081,
1021,
1731,
526,
358,
506,
6383,
225,
436,
1021,
316,
17,
7858,
1958,
225,
13199,
1021,
13199,
364,
12533,
1466,
327,
1021,
1300,
434,
1731,
6383,
19,
309,
1375,
86,
68,
353,
3206,
16,
1508,
1338,
22075,
326,
1300,
434,
1466,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
389,
896,
67,
2680,
67,
542,
67,
3374,
12,
203,
565,
2254,
5034,
293,
16,
203,
565,
1731,
3778,
7081,
16,
203,
565,
1910,
3778,
436,
16,
203,
565,
2254,
63,
23,
65,
3778,
13199,
203,
225,
262,
2713,
16618,
1135,
261,
11890,
13,
288,
203,
565,
261,
15512,
1988,
694,
1864,
18,
751,
3778,
619,
16,
2254,
5034,
11262,
13,
273,
389,
3922,
67,
15512,
1988,
694,
1864,
12,
84,
16,
7081,
1769,
203,
565,
309,
261,
291,
12616,
12,
86,
3719,
288,
203,
1377,
13199,
63,
22,
65,
1011,
404,
31,
203,
1377,
436,
18,
2680,
67,
542,
67,
3374,
273,
619,
31,
203,
1377,
309,
261,
23426,
63,
22,
65,
405,
374,
13,
13199,
63,
22,
65,
3947,
404,
31,
203,
565,
289,
203,
565,
327,
11262,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.0;
library TellorTransfer {
using SafeMath for uint256;
event Approval(address indexed _owner, address indexed _spender, uint256 _value);//ERC20 Approval event
event Transfer(address indexed _from, address indexed _to, uint256 _value);//ERC20 Transfer Event
/*Functions*/
/**
* @dev Allows for a transfer of tokens to _to
* @param _to The address to send tokens to
* @param _amount The amount of tokens to send
* @return true if transfer is successful
*/
function transfer(TellorStorage.TellorStorageStruct storage self, address _to, uint256 _amount) public returns (bool success) {
doTransfer(self,msg.sender, _to, _amount);
return true;
}
/**
* @notice Send _amount tokens to _to from _from on the condition it
* is approved by _from
* @param _from The address holding the tokens being transferred
* @param _to The address of the recipient
* @param _amount The amount of tokens to be transferred
* @return True if the transfer was successful
*/
function transferFrom(TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint256 _amount) public returns (bool success) {
require(self.allowed[_from][msg.sender] >= _amount);
self.allowed[_from][msg.sender] -= _amount;
doTransfer(self,_from, _to, _amount);
return true;
}
/**
* @dev This function approves a _spender an _amount of tokens to use
* @param _spender address
* @param _amount amount the spender is being approved for
* @return true if spender appproved successfully
*/
function approve(TellorStorage.TellorStorageStruct storage self, address _spender, uint _amount) public returns (bool) {
require(_spender != address(0));
self.allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
// /**
// * @param _user address of party with the balance
// * @param _spender address of spender of parties said balance
// * @return Returns the remaining allowance of tokens granted to the _spender from the _user
// */
// function allowance(TellorStorage.TellorStorageStruct storage self,address _user, address _spender) public view returns (uint) {
// return self.allowed[_user][_spender];
// }
/**
* @dev Completes POWO transfers by updating the balances on the current block number
* @param _from address to transfer from
* @param _to addres to transfer to
* @param _amount to transfer
*/
function doTransfer(TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint _amount) public {
require(_amount > 0);
require(_to != address(0));
require(allowedToTrade(self,_from,_amount)); //allowedToTrade checks the stakeAmount is removed from balance if the _user is staked
uint previousBalance = balanceOfAt(self,_from, block.number);
updateBalanceAtNow(self.balances[_from], previousBalance - _amount);
previousBalance = balanceOfAt(self,_to, block.number);
require(previousBalance + _amount >= previousBalance); // Check for overflow
updateBalanceAtNow(self.balances[_to], previousBalance + _amount);
emit Transfer(_from, _to, _amount);
}
/**
* @dev Gets balance of owner specified
* @param _user is the owner address used to look up the balance
* @return Returns the balance associated with the passed in _user
*/
function balanceOf(TellorStorage.TellorStorageStruct storage self,address _user) public view returns (uint) {
return balanceOfAt(self,_user, block.number);
}
/**
* @dev Queries the balance of _user at a specific _blockNumber
* @param _user The address from which the balance will be retrieved
* @param _blockNumber The block number when the balance is queried
* @return The balance at _blockNumber specified
*/
function balanceOfAt(TellorStorage.TellorStorageStruct storage self,address _user, uint _blockNumber) public view returns (uint) {
if ((self.balances[_user].length == 0) || (self.balances[_user][0].fromBlock > _blockNumber)) {
return 0;
}
else {
return getBalanceAt(self.balances[_user], _blockNumber);
}
}
/**
* @dev Getter for balance for owner on the specified _block number
* @param checkpoints gets the mapping for the balances[owner]
* @param _block is the block number to search the balance on
* @return the balance at the checkpoint
*/
function getBalanceAt(TellorStorage.Checkpoint[] storage checkpoints, uint _block) view public 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;
// 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 This function returns whether or not a given user is allowed to trade a given amount
* and removing the staked amount from their balance if they are staked
* @param _user address of user
* @param _amount to check if the user can spend
* @return true if they are allowed to spend the amount being checked
*/
function allowedToTrade(TellorStorage.TellorStorageStruct storage self,address _user,uint _amount) public view returns(bool) {
if(self.stakerDetails[_user].currentStatus >0){
//Removes the stakeAmount from balance if the _user is staked
if(balanceOf(self,_user).sub(self.uintVars[keccak256("stakeAmount")]).sub(_amount) >= 0){
return true;
}
}
else if(balanceOf(self,_user).sub(_amount) >= 0){
return true;
}
return false;
}
/**
* @dev Updates balance for from and to on the current block number via doTransfer
* @param checkpoints gets the mapping for the balances[owner]
* @param _value is the new balance
*/
function updateBalanceAtNow(TellorStorage.Checkpoint[] storage checkpoints, uint _value) public {
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length -1].fromBlock < block.number)) {
TellorStorage.Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
TellorStorage.Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
}
//Slightly modified SafeMath library - includes a min and max function, removes useless div function
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function add(int256 a, int256 b) internal pure returns (int256 c) {
if (b > 0) {
c = a + b;
assert(c >= a);
} else {
c = a + b;
assert(c <= a);
}
}
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
function max(int256 a, int256 b) internal pure returns (uint256) {
return a > b ? uint256(a) : uint256(b);
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function sub(int256 a, int256 b) internal pure returns (int256 c) {
if (b > 0) {
c = a - b;
assert(c <= a);
} else {
c = a - b;
assert(c >= a);
}
}
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;
}
}
/**
* @title Tellor Oracle Storage Library
* @dev Contains all the variables/structs used by Tellor
* This test file is exactly the same as the production/mainnet file.
*/
library TellorStorage {
//Internal struct for use in proof-of-work submission
struct Details {
uint value;
address miner;
}
struct Dispute {
bytes32 hash;//unique hash of dispute: keccak256(_miner,_requestId,_timestamp)
int tally;//current tally of votes for - against measure
bool executed;//is the dispute settled
bool disputeVotePassed;//did the vote pass?
bool isPropFork; //true for fork proposal NEW
address reportedMiner; //miner who alledgedly submitted the 'bad value' will get disputeFee if dispute vote fails
address reportingParty;//miner reporting the 'bad value'-pay disputeFee will get reportedMiner's stake if dispute vote passes
address proposedForkAddress;//new fork address (if fork proposal)
mapping(bytes32 => uint) disputeUintVars;
//Each of the variables below is saved in the mapping disputeUintVars for each disputeID
//e.g. TellorStorageStruct.DisputeById[disputeID].disputeUintVars[keccak256("requestId")]
//These are the variables saved in this mapping:
// uint keccak256("requestId");//apiID of disputed value
// uint keccak256("timestamp");//timestamp of distputed value
// uint keccak256("value"); //the value being disputed
// uint keccak256("minExecutionDate");//7 days from when dispute initialized
// uint keccak256("numberOfVotes");//the number of parties who have voted on the measure
// uint keccak256("blockNumber");// the blocknumber for which votes will be calculated from
// uint keccak256("minerSlot"); //index in dispute array
// uint keccak256("quorum"); //quorum for dispute vote NEW
// uint keccak256("fee"); //fee paid corresponding to dispute
mapping (address => bool) voted; //mapping of address to whether or not they voted
}
struct StakeInfo {
uint currentStatus;//0-not Staked, 1=Staked, 2=LockedForWithdraw 3= OnDispute
uint startDate; //stake start date
}
//Internal struct to allow balances to be queried by blocknumber for voting purposes
struct Checkpoint {
uint128 fromBlock;// fromBlock is the block number that the value was generated from
uint128 value;// value is the amount of tokens at a specific block number
}
struct Request {
string queryString;//id to string api
string dataSymbol;//short name for api request
bytes32 queryHash;//hash of api string and granularity e.g. keccak256(abi.encodePacked(_sapi,_granularity))
uint[] requestTimestamps; //array of all newValueTimestamps requested
mapping(bytes32 => uint) apiUintVars;
//Each of the variables below is saved in the mapping apiUintVars for each api request
//e.g. requestDetails[_requestId].apiUintVars[keccak256("totalTip")]
//These are the variables saved in this mapping:
// uint keccak256("granularity"); //multiplier for miners
// uint keccak256("requestQPosition"); //index in requestQ
// uint keccak256("totalTip");//bonus portion of payout
mapping(uint => uint) minedBlockNum;//[apiId][minedTimestamp]=>block.number
mapping(uint => uint) finalValues;//This the time series of finalValues stored by the contract where uint UNIX timestamp is mapped to value
mapping(uint => bool) inDispute;//checks if API id is in dispute or finalized.
mapping(uint => address[5]) minersByValue;
mapping(uint => uint[5])valuesByTimestamp;
}
struct TellorStorageStruct {
bytes32 currentChallenge; //current challenge to be solved
uint[51] requestQ; //uint50 array of the top50 requests by payment amount
uint[] newValueTimestamps; //array of all timestamps requested
Details[5] currentMiners; //This struct is for organizing the five mined values to find the median
mapping(bytes32 => address) addressVars;
//Address fields in the Tellor contract are saved the addressVars mapping
//e.g. addressVars[keccak256("tellorContract")] = address
//These are the variables saved in this mapping:
// address keccak256("tellorContract");//Tellor address
// address keccak256("_owner");//Tellor Owner address
// address keccak256("_deity");//Tellor Owner that can do things at will
mapping(bytes32 => uint) uintVars;
//uint fields in the Tellor contract are saved the uintVars mapping
//e.g. uintVars[keccak256("decimals")] = uint
//These are the variables saved in this mapping:
// keccak256("decimals"); //18 decimal standard ERC20
// keccak256("disputeFee");//cost to dispute a mined value
// keccak256("disputeCount");//totalHistoricalDisputes
// keccak256("total_supply"); //total_supply of the token in circulation
// keccak256("stakeAmount");//stakeAmount for miners (we can cut gas if we just hardcode it in...or should it be variable?)
// keccak256("stakerCount"); //number of parties currently staked
// keccak256("timeOfLastNewValue"); // time of last challenge solved
// keccak256("difficulty"); // Difficulty of current block
// keccak256("currentTotalTips"); //value of highest api/timestamp PayoutPool
// keccak256("currentRequestId"); //API being mined--updates with the ApiOnQ Id
// keccak256("requestCount"); // total number of requests through the system
// keccak256("slotProgress");//Number of miners who have mined this value so far
// keccak256("miningReward");//Mining Reward in PoWo tokens given to all miners per value
// keccak256("timeTarget"); //The time between blocks (mined Oracle values)
mapping(bytes32 => mapping(address=>bool)) minersByChallenge;//This is a boolean that tells you if a given challenge has been completed by a given miner
mapping(uint => uint) requestIdByTimestamp;//minedTimestamp to apiId
mapping(uint => uint) requestIdByRequestQIndex; //link from payoutPoolIndex (position in payout pool array) to apiId
mapping(uint => Dispute) disputesById;//disputeId=> Dispute details
mapping (address => Checkpoint[]) balances; //balances of a party given blocks
mapping(address => mapping (address => uint)) allowed; //allowance for a given party and approver
mapping(address => StakeInfo) stakerDetails;//mapping from a persons address to their staking info
mapping(uint => Request) requestDetails;//mapping of apiID to details
mapping(bytes32 => uint) requestIdByQueryHash;// api bytes32 gets an id = to count of requests array
mapping(bytes32 => uint) disputeIdByDisputeHash;//maps a hash to an ID for each dispute
}
}
//Functions for retrieving min and Max in 51 length array (requestQ)
//Taken partly from: https://github.com/modular-network/ethereum-libraries-array-utils/blob/master/contracts/Array256Lib.sol
library Utilities{
/**
* @dev Returns the minimum value in an array.
*/
function getMax(uint[51] memory data) internal pure returns(uint256 max,uint256 maxIndex) {
max = data[1];
maxIndex;
for(uint i=1;i < data.length;i++){
if(data[i] > max){
max = data[i];
maxIndex = i;
}
}
}
/**
* @dev Returns the minimum value in an array.
*/
function getMin(uint[51] memory data) internal pure returns(uint256 min,uint256 minIndex) {
minIndex = data.length - 1;
min = data[minIndex];
for(uint i = data.length-1;i > 0;i--) {
if(data[i] < min) {
min = data[i];
minIndex = i;
}
}
}
}
/**
***********************************TEST LIBRARY***************************************
* @title Tellor Getters Library
* @dev This is the test getter library for all variables in the Tellor Tributes system. TellorGetters references this
* libary for the getters logic.
* Many of the functions have been commented out for simplicity.
*/
library TellorGettersLibrary{
using SafeMath for uint256;
event NewTellorAddress(address _newTellor); //emmited when a proposed fork is voted true
/*Functions*/
//The next two functions are onlyOwner functions. For Tellor to be truly decentralized, we will need to transfer the Deity to the 0 address.
//Only needs to be in library
/**
* @dev This function allows us to set a new Deity (or remove it)
* @param _newDeity address of the new Deity of the tellor system
*/
function changeDeity(TellorStorage.TellorStorageStruct storage self, address _newDeity) internal{
require(self.addressVars[keccak256("_deity")] == msg.sender);
self.addressVars[keccak256("_deity")] =_newDeity;
}
//Only needs to be in library
/**
* @dev This function allows the deity to upgrade the Tellor System
* @param _tellorContract address of new updated TellorCore contract
*/
function changeTellorContract(TellorStorage.TellorStorageStruct storage self,address _tellorContract) internal{
require(self.addressVars[keccak256("_deity")] == msg.sender);
self.addressVars[keccak256("tellorContract")]= _tellorContract;
emit NewTellorAddress(_tellorContract);
}
// /*Tellor Getters*/
// /**
// * @dev This function tells you if a given challenge has been completed by a given miner
// * @param _challenge the challenge to search for
// * @param _miner address that you want to know if they solved the challenge
// * @return true if the _miner address provided solved the
// */
// function didMine(TellorStorage.TellorStorageStruct storage self, bytes32 _challenge,address _miner) internal view returns(bool){
// return self.minersByChallenge[_challenge][_miner];
// }
// /**
// * @dev Checks if an address voted in a dispute
// * @param _disputeId to look up
// * @param _address of voting party to look up
// * @return bool of whether or not party voted
// */
// function didVote(TellorStorage.TellorStorageStruct storage self,uint _disputeId, address _address) internal view returns(bool){
// return self.disputesById[_disputeId].voted[_address];
// }
// /**
// * @dev allows Tellor to read data from the addressVars mapping
// * @param _data is the keccak256("variable_name") of the variable that is being accessed.
// * These are examples of how the variables are saved within other functions:
// * addressVars[keccak256("_owner")]
// * addressVars[keccak256("tellorContract")]
// */
// function getAddressVars(TellorStorage.TellorStorageStruct storage self, bytes32 _data) view internal returns(address){
// return self.addressVars[_data];
// }
// *
// * @dev Gets all dispute variables
// * @param _disputeId to look up
// * @return bytes32 hash of dispute
// * @return bool executed where true if it has been voted on
// * @return bool disputeVotePassed
// * @return bool isPropFork true if the dispute is a proposed fork
// * @return address of reportedMiner
// * @return address of reportingParty
// * @return address of proposedForkAddress
// * @return uint of requestId
// * @return uint of timestamp
// * @return uint of value
// * @return uint of minExecutionDate
// * @return uint of numberOfVotes
// * @return uint of blocknumber
// * @return uint of minerSlot
// * @return uint of quorum
// * @return uint of fee
// * @return int count of the current tally
// function getAllDisputeVars(TellorStorage.TellorStorageStruct storage self,uint _disputeId) internal view returns(bytes32, bool, bool, bool, address, address, address,uint[9] memory, int){
// TellorStorage.Dispute storage disp = self.disputesById[_disputeId];
// return(disp.hash,disp.executed, disp.disputeVotePassed, disp.isPropFork, disp.reportedMiner, disp.reportingParty,disp.proposedForkAddress,[disp.disputeUintVars[keccak256("requestId")], disp.disputeUintVars[keccak256("timestamp")], disp.disputeUintVars[keccak256("value")], disp.disputeUintVars[keccak256("minExecutionDate")], disp.disputeUintVars[keccak256("numberOfVotes")], disp.disputeUintVars[keccak256("blockNumber")], disp.disputeUintVars[keccak256("minerSlot")], disp.disputeUintVars[keccak256("quorum")],disp.disputeUintVars[keccak256("fee")]],disp.tally);
// }
// /**
// * @dev Getter function for variables for the requestId being currently mined(currentRequestId)
// * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request
// */
// function getCurrentVariables(TellorStorage.TellorStorageStruct storage self) internal view returns(bytes32, uint, uint,string memory,uint,uint){
// return (self.currentChallenge,self.uintVars[keccak256("currentRequestId")],self.uintVars[keccak256("difficulty")],self.requestDetails[self.uintVars[keccak256("currentRequestId")]].queryString,self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("granularity")],self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("totalTip")]);
// }
// /**
// * @dev Checks if a given hash of miner,requestId has been disputed
// * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId));
// * @return uint disputeId
// */
// function getDisputeIdByDisputeHash(TellorStorage.TellorStorageStruct storage self,bytes32 _hash) internal view returns(uint){
// return self.disputeIdByDisputeHash[_hash];
// }
// /*
// * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId
// * @param _disputeId is the dispute id;
// * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
// * the variables/strings used to save the data in the mapping. The variables names are
// * commented out under the disputeUintVars under the Dispute struct
// * @return uint value for the bytes32 data submitted
// */
// function getDisputeUintVars(TellorStorage.TellorStorageStruct storage self,uint _disputeId,bytes32 _data) internal view returns(uint){
// return self.disputesById[_disputeId].disputeUintVars[_data];
// }
// /**
// * @dev Gets the a value for the latest timestamp available
// * @return value for timestamp of last proof of work submited
// * @return true if the is a timestamp for the lastNewValue
// */
// function getLastNewValue(TellorStorage.TellorStorageStruct storage self) internal view returns(uint,bool){
// return (retrieveData(self,self.requestIdByTimestamp[self.uintVars[keccak256("timeOfLastNewValue")]], self.uintVars[keccak256("timeOfLastNewValue")]),true);
// }
// /**
// * @dev Gets the a value for the latest timestamp available
// * @param _requestId being requested
// * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't
// */
// function getLastNewValueById(TellorStorage.TellorStorageStruct storage self,uint _requestId) internal view returns(uint,bool){
// TellorStorage.Request storage _request = self.requestDetails[_requestId];
// if(_request.requestTimestamps.length > 0){
// return (retrieveData(self,_requestId,_request.requestTimestamps[_request.requestTimestamps.length - 1]),true);
// }
// else{
// return (0,false);
// }
// }
// /**
// * @dev Gets blocknumber for mined timestamp
// * @param _requestId to look up
// * @param _timestamp is the timestamp to look up blocknumber
// * @return uint of the blocknumber which the dispute was mined
// */
// function getMinedBlockNum(TellorStorage.TellorStorageStruct storage self,uint _requestId, uint _timestamp) internal view returns(uint){
// return self.requestDetails[_requestId].minedBlockNum[_timestamp];
// }
// /**
// * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
// * @param _requestId to look up
// * @param _timestamp is the timestamp to look up miners for
// * @return the 5 miners' addresses
// */
// function getMinersByRequestIdAndTimestamp(TellorStorage.TellorStorageStruct storage self, uint _requestId, uint _timestamp) internal view returns(address[5] memory){
// return self.requestDetails[_requestId].minersByValue[_timestamp];
// }
// /**
// * @dev Get the name of the token
// * @return string of the token name
// */
// function getName(TellorStorage.TellorStorageStruct storage self) internal pure returns(string memory){
// return "Tellor Tributes";
// }
/**
* @dev Counts the number of values that have been submited for the request
* if called for the currentRequest being mined it can tell you how many miners have submitted a value for that
* request so far
* @param _requestId the requestId to look up
* @return uint count of the number of values received for the requestId
*/
function getNewValueCountbyRequestId(TellorStorage.TellorStorageStruct storage self, uint _requestId) internal view returns(uint){
return self.requestDetails[_requestId].requestTimestamps.length;
}
// /**
// * @dev Getter function for the specified requestQ index
// * @param _index to look up in the requestQ array
// * @return uint of reqeuestId
// */
// function getRequestIdByRequestQIndex(TellorStorage.TellorStorageStruct storage self, uint _index) internal view returns(uint){
// require(_index <= 50);
// return self.requestIdByRequestQIndex[_index];
// }
// /**
// * @dev Getter function for requestId based on timestamp
// * @param _timestamp to check requestId
// * @return uint of reqeuestId
// */
// function getRequestIdByTimestamp(TellorStorage.TellorStorageStruct storage self, uint _timestamp) internal view returns(uint){
// return self.requestIdByTimestamp[_timestamp];
// }
/**
* @dev Getter function for requestId based on the qeuaryHash
* @param _queryHash hash(of string api and granularity) to check if a request already exists
* @return uint requestId
*/
function getRequestIdByQueryHash(TellorStorage.TellorStorageStruct storage self, bytes32 _queryHash) internal view returns(uint){
return self.requestIdByQueryHash[_queryHash];
}
// /**
// * @dev Getter function for the requestQ array
// * @return the requestQ arrray
// */
// function getRequestQ(TellorStorage.TellorStorageStruct storage self) view internal returns(uint[51] memory){
// return self.requestQ;
// }
// *
// * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct
// * for the requestId specified
// * @param _requestId to look up
// * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
// * the variables/strings used to save the data in the mapping. The variables names are
// * commented out under the apiUintVars under the requestDetails struct
// * @return uint value of the apiUintVars specified in _data for the requestId specified
// function getRequestUintVars(TellorStorage.TellorStorageStruct storage self,uint _requestId,bytes32 _data) internal view returns(uint){
// return self.requestDetails[_requestId].apiUintVars[_data];
// }
/**
* @dev Gets the API struct variables that are not mappings
* @param _requestId to look up
* @return string of api to query
* @return string of symbol of api to query
* @return bytes32 hash of string
* @return bytes32 of the granularity(decimal places) requested
* @return uint of index in requestQ array
* @return uint of current payout/tip for this requestId
*/
function getRequestVars(TellorStorage.TellorStorageStruct storage self,uint _requestId) internal view returns(string memory,string memory, bytes32,uint, uint, uint) {
TellorStorage.Request storage _request = self.requestDetails[_requestId];
return (_request.queryString,_request.dataSymbol,_request.queryHash, _request.apiUintVars[keccak256("granularity")],_request.apiUintVars[keccak256("requestQPosition")],_request.apiUintVars[keccak256("totalTip")]);
}
// /**
// * @dev This function allows users to retireve all information about a staker
// * @param _staker address of staker inquiring about
// * @return uint current state of staker
// * @return uint startDate of staking
// */
// function getStakerInfo(TellorStorage.TellorStorageStruct storage self,address _staker) internal view returns(uint,uint){
// return (self.stakerDetails[_staker].currentStatus,self.stakerDetails[_staker].startDate);
// }
// /**
// * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
// * @param _requestId to look up
// * @param _timestamp is the timestampt to look up miners for
// * @return address[5] array of 5 addresses ofminers that mined the requestId
// */
// function getSubmissionsByTimestamp(TellorStorage.TellorStorageStruct storage self, uint _requestId, uint _timestamp) internal view returns(uint[5] memory){
// return self.requestDetails[_requestId].valuesByTimestamp[_timestamp];
// }
// /**
// * @dev Get the symbol of the token
// * @return string of the token symbol
// */
// function getSymbol(TellorStorage.TellorStorageStruct storage self) internal pure returns(string memory){
// return "TT";
// }
/**
* @dev Gets the timestamp for the value based on their index
* @param _requestID is the requestId to look up
* @param _index is the value index to look up
* @return uint timestamp
*/
function getTimestampbyRequestIDandIndex(TellorStorage.TellorStorageStruct storage self,uint _requestID, uint _index) internal view returns(uint){
return self.requestDetails[_requestID].requestTimestamps[_index];
}
// /**
// * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable
// * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
// * the variables/strings used to save the data in the mapping. The variables names are
// * commented out under the uintVars under the TellorStorageStruct struct
// * This is an example of how data is saved into the mapping within other functions:
// * self.uintVars[keccak256("stakerCount")]
// * @return uint of specified variable
// */
// function getUintVar(TellorStorage.TellorStorageStruct storage self,bytes32 _data) view internal returns(uint){
// return self.uintVars[_data];
// }
/**
* @dev Getter function for next requestId on queue/request with highest payout at time the function is called
* @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string
*/
function getVariablesOnDeck(TellorStorage.TellorStorageStruct storage self) internal view returns(uint, uint,string memory){
uint newRequestId = getTopRequestID(self);
return (newRequestId,self.requestDetails[newRequestId].apiUintVars[keccak256("totalTip")],self.requestDetails[newRequestId].queryString);
}
/**
* @dev Getter function for the request with highest payout. This function is used within the getVariablesOnDeck function
* @return uint _requestId of request with highest payout at the time the function is called
*/
function getTopRequestID(TellorStorage.TellorStorageStruct storage self) internal view returns(uint _requestId){
uint _max;
uint _index;
(_max,_index) = Utilities.getMax(self.requestQ);
_requestId = self.requestIdByRequestQIndex[_index];
}
/**
* @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
* @param _requestId to look up
* @param _timestamp is the timestamp to look up miners for
* @return bool true if requestId/timestamp is under dispute
*/
function isInDispute(TellorStorage.TellorStorageStruct storage self, uint _requestId, uint _timestamp) internal view returns(bool){
return self.requestDetails[_requestId].inDispute[_timestamp];
}
/**
* @dev Retreive value from oracle based on requestId/timestamp
* @param _requestId being requested
* @param _timestamp to retreive data/value from
* @return uint value for requestId/timestamp submitted
*/
function retrieveData(TellorStorage.TellorStorageStruct storage self, uint _requestId, uint _timestamp) internal view returns (uint) {
return self.requestDetails[_requestId].finalValues[_timestamp];
}
// /**
// * @dev Getter for the total_supply of oracle tokens
// * @return uint total supply
// */
// function totalSupply(TellorStorage.TellorStorageStruct storage self) internal view returns (uint) {
// return self.uintVars[keccak256("total_supply")];
// }
}
/**
* @title Tellor Getters
* @dev Oracle contract with all tellor getter functions. The logic for the functions on this contract
* is saved on the TellorGettersLibrary, TellorTransfer, TellorGettersLibrary, and TellorStake
*/
contract TellorGetters{
using SafeMath for uint256;
using TellorTransfer for TellorStorage.TellorStorageStruct;
using TellorGettersLibrary for TellorStorage.TellorStorageStruct;
//using TellorStake for TellorStorage.TellorStorageStruct;
TellorStorage.TellorStorageStruct tellor;
// *
// * @param _user address
// * @param _spender address
// * @return Returns the remaining allowance of tokens granted to the _spender from the _user
// function allowance(address _user, address _spender) external view returns (uint) {
// return tellor.allowance(_user,_spender);
// }
/**
* @dev This function returns whether or not a given user is allowed to trade a given amount
* @param _user address
* @param _amount uint of amount
* @return true if the user is alloed to trade the amount specified
*/
function allowedToTrade(address _user,uint _amount) external view returns(bool){
return tellor.allowedToTrade(_user,_amount);
}
/**
* @dev Gets balance of owner specified
* @param _user is the owner address used to look up the balance
* @return Returns the balance associated with the passed in _user
*/
function balanceOf(address _user) external view returns (uint) {
return tellor.balanceOf(_user);
}
/**
* @dev Queries the balance of _user at a specific _blockNumber
* @param _user 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 _user, uint _blockNumber) external view returns (uint) {
return tellor.balanceOfAt(_user,_blockNumber);
}
// /**
// * @dev This function tells you if a given challenge has been completed by a given miner
// * @param _challenge the challenge to search for
// * @param _miner address that you want to know if they solved the challenge
// * @return true if the _miner address provided solved the
// */
// function didMine(bytes32 _challenge, address _miner) external view returns(bool){
// return tellor.didMine(_challenge,_miner);
// }
// /**
// * @dev Checks if an address voted in a given dispute
// * @param _disputeId to look up
// * @param _address to look up
// * @return bool of whether or not party voted
// */
// function didVote(uint _disputeId, address _address) external view returns(bool){
// return tellor.didVote(_disputeId,_address);
// }
// /**
// * @dev allows Tellor to read data from the addressVars mapping
// * @param _data is the keccak256("variable_name") of the variable that is being accessed.
// * These are examples of how the variables are saved within other functions:
// * addressVars[keccak256("_owner")]
// * addressVars[keccak256("tellorContract")]
// */
// function getAddressVars(bytes32 _data) view external returns(address){
// return tellor.getAddressVars(_data);
// }
// /**
// * @dev Gets all dispute variables
// * @param _disputeId to look up
// * @return bytes32 hash of dispute
// * @return bool executed where true if it has been voted on
// * @return bool disputeVotePassed
// * @return bool isPropFork true if the dispute is a proposed fork
// * @return address of reportedMiner
// * @return address of reportingParty
// * @return address of proposedForkAddress
// * @return uint of requestId
// * @return uint of timestamp
// * @return uint of value
// * @return uint of minExecutionDate
// * @return uint of numberOfVotes
// * @return uint of blocknumber
// * @return uint of minerSlot
// * @return uint of quorum
// * @return uint of fee
// * @return int count of the current tally
// */
// function getAllDisputeVars(uint _disputeId) public view returns(bytes32, bool, bool, bool, address, address, address,uint[9] memory, int){
// return tellor.getAllDisputeVars(_disputeId);
// }
// /**
// * @dev Getter function for variables for the requestId being currently mined(currentRequestId)
// * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request
// */
// function getCurrentVariables() external view returns(bytes32, uint, uint,string memory,uint,uint){
// return tellor.getCurrentVariables();
// }
// *
// * @dev Checks if a given hash of miner,requestId has been disputed
// * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId));
// * @return uint disputeId
// function getDisputeIdByDisputeHash(bytes32 _hash) external view returns(uint){
// return tellor.getDisputeIdByDisputeHash(_hash);
// }
// /**
// * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId
// * @param _disputeId is the dispute id;
// * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
// * the variables/strings used to save the data in the mapping. The variables names are
// * commented out under the disputeUintVars under the Dispute struct
// * @return uint value for the bytes32 data submitted
// */
// function getDisputeUintVars(uint _disputeId,bytes32 _data) external view returns(uint){
// return tellor.getDisputeUintVars(_disputeId,_data);
// }
// /**
// * @dev Gets the a value for the latest timestamp available
// * @return value for timestamp of last proof of work submited
// * @return true if the is a timestamp for the lastNewValue
// */
// function getLastNewValue() external view returns(uint,bool){
// return tellor.getLastNewValue();
// }
// /**
// * @dev Gets the a value for the latest timestamp available
// * @param _requestId being requested
// * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't
// */
// function getLastNewValueById(uint _requestId) external view returns(uint,bool){
// return tellor.getLastNewValueById(_requestId);
// }
// /**
// * @dev Gets blocknumber for mined timestamp
// * @param _requestId to look up
// * @param _timestamp is the timestamp to look up blocknumber
// * @return uint of the blocknumber which the dispute was mined
// */
// function getMinedBlockNum(uint _requestId, uint _timestamp) external view returns(uint){
// return tellor.getMinedBlockNum(_requestId,_timestamp);
// }
// /**
// * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
// * @param _requestId to look up
// * @param _timestamp is the timestamp to look up miners for
// * @return the 5 miners' addresses
// */
// function getMinersByRequestIdAndTimestamp(uint _requestId, uint _timestamp) external view returns(address[5] memory){
// return tellor.getMinersByRequestIdAndTimestamp(_requestId,_timestamp);
// }
// /**
// * @dev Get the name of the token
// * return string of the token name
// */
// function getName() external view returns(string memory){
// return tellor.getName();
// }
/**
* @dev Counts the number of values that have been submited for the request
* if called for the currentRequest being mined it can tell you how many miners have submitted a value for that
* request so far
* @param _requestId the requestId to look up
* @return uint count of the number of values received for the requestId
*/
function getNewValueCountbyRequestId(uint _requestId) external view returns(uint){
return tellor.getNewValueCountbyRequestId(_requestId);
}
// /**
// * @dev Getter function for the specified requestQ index
// * @param _index to look up in the requestQ array
// * @return uint of reqeuestId
// */
// function getRequestIdByRequestQIndex(uint _index) external view returns(uint){
// return tellor.getRequestIdByRequestQIndex(_index);
// }
// /**
// * @dev Getter function for requestId based on timestamp
// * @param _timestamp to check requestId
// * @return uint of reqeuestId
// */
// function getRequestIdByTimestamp(uint _timestamp) external view returns(uint){
// return tellor.getRequestIdByTimestamp(_timestamp);
// }
/**
* @dev Getter function for requestId based on the queryHash
* @param _request is the hash(of string api and granularity) to check if a request already exists
* @return uint requestId
*/
function getRequestIdByQueryHash(bytes32 _request) external view returns(uint){
return tellor.getRequestIdByQueryHash(_request);
}
// /**
// * @dev Getter function for the requestQ array
// * @return the requestQ arrray
// */
// function getRequestQ() view public returns(uint[51] memory){
// return tellor.getRequestQ();
// }
// /**
// * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct
// * for the requestId specified
// * @param _requestId to look up
// * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
// * the variables/strings used to save the data in the mapping. The variables names are
// * commented out under the apiUintVars under the requestDetails struct
// * @return uint value of the apiUintVars specified in _data for the requestId specified
// */
// function getRequestUintVars(uint _requestId,bytes32 _data) external view returns(uint){
// return tellor.getRequestUintVars(_requestId,_data);
// }
/**
* @dev Gets the API struct variables that are not mappings
* @param _requestId to look up
* @return string of api to query
* @return string of symbol of api to query
* @return bytes32 hash of string
* @return bytes32 of the granularity(decimal places) requested
* @return uint of index in requestQ array
* @return uint of current payout/tip for this requestId
*/
function getRequestVars(uint _requestId) external view returns(string memory, string memory,bytes32,uint, uint, uint) {
return tellor.getRequestVars(_requestId);
}
// /**
// * @dev This function allows users to retireve all information about a staker
// * @param _staker address of staker inquiring about
// * @return uint current state of staker
// * @return uint startDate of staking
// */
// function getStakerInfo(address _staker) external view returns(uint,uint){
// return tellor.getStakerInfo(_staker);
// }
// /**
// * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
// * @param _requestId to look up
// * @param _timestamp is the timestampt to look up miners for
// * @return address[5] array of 5 addresses ofminers that mined the requestId
// */
// function getSubmissionsByTimestamp(uint _requestId, uint _timestamp) external view returns(uint[5] memory){
// return tellor.getSubmissionsByTimestamp(_requestId,_timestamp);
// }
// /**
// * @dev Get the symbol of the token
// * return string of the token symbol
// */
// function getSymbol() external view returns(string memory){
// return tellor.getSymbol();
// }
/**
* @dev Gets the timestamp for the value based on their index
* @param _requestID is the requestId to look up
* @param _index is the value index to look up
* @return uint timestamp
*/
function getTimestampbyRequestIDandIndex(uint _requestID, uint _index) external view returns(uint){
return tellor.getTimestampbyRequestIDandIndex(_requestID,_index);
}
// /**
// * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable
// * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
// * the variables/strings used to save the data in the mapping. The variables names are
// * commented out under the uintVars under the TellorStorageStruct struct
// * This is an example of how data is saved into the mapping within other functions:
// * self.uintVars[keccak256("stakerCount")]
// * @return uint of specified variable
// */
// function getUintVar(bytes32 _data) view public returns(uint){
// return tellor.getUintVar(_data);
// }
/**
* @dev Getter function for next requestId on queue/request with highest payout at time the function is called
* @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string
*/
function getVariablesOnDeck() external view returns(uint, uint,string memory){
return tellor.getVariablesOnDeck();
}
/**
* @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
* @param _requestId to look up
* @param _timestamp is the timestamp to look up miners for
* @return bool true if requestId/timestamp is under dispute
*/
function isInDispute(uint _requestId, uint _timestamp) external view returns(bool){
return tellor.isInDispute(_requestId,_timestamp);
}
/**
* @dev Retreive value from oracle based on timestamp
* @param _requestId being requested
* @param _timestamp to retreive data/value from
* @return value for timestamp submitted
*/
function retrieveData(uint _requestId, uint _timestamp) external view returns (uint) {
return tellor.retrieveData(_requestId,_timestamp);
}
// *
// * @dev Getter for the total_supply of oracle tokens
// * @return uint total supply
// function totalSupply() external view returns (uint) {
// return tellor.totalSupply();
// }
}
/**** TellorMaster Test Contract***/
/*WARNING: This contract is used for the delegate calls to the Test Tellor contract
wich excludes mining for testing purposes
This has bee adapted for projects testing Tellor integration
**/
/**
* @title Tellor Master
* @dev This is the Master contract with all tellor getter functions and delegate call to Tellor.
* The logic for the functions on this contract is saved on the TellorGettersLibrary, TellorTransfer,
* TellorGettersLibrary, and TellorStake
*/
contract TellorMaster is TellorGetters{
event NewTellorAddress(address _newTellor);
/**
* @dev The constructor sets the original `tellorStorageOwner` of the contract to the sender
* account, the tellor contract to the Tellor master address and owner to the Tellor master owner address
* @param _tellorContract is the address for the tellor contract
*/
constructor (address _tellorContract) public{
init();
tellor.addressVars[keccak256("_owner")] = msg.sender;
tellor.addressVars[keccak256("_deity")] = msg.sender;
tellor.addressVars[keccak256("tellorContract")]= _tellorContract;
emit NewTellorAddress(_tellorContract);
}
/**
* @dev This function stakes the five initial miners, sets the supply and all the constant variables.
* This function is called by the constructor function on TellorMaster.sol
*/
function init() internal {
require(tellor.uintVars[keccak256("decimals")] == 0);
//Give this contract 6000 Tellor Tributes so that it can stake the initial 6 miners
TellorTransfer.updateBalanceAtNow(tellor.balances[address(this)], 2**256-1 - 6000e18);
// //the initial 5 miner addresses are specfied below
// //changed payable[5] to 6
address payable[6] memory _initalMiners = [address(0xE037EC8EC9ec423826750853899394dE7F024fee),
address(0xcdd8FA31AF8475574B8909F135d510579a8087d3),
address(0xb9dD5AfD86547Df817DA2d0Fb89334A6F8eDd891),
address(0x230570cD052f40E14C14a81038c6f3aa685d712B),
address(0x3233afA02644CCd048587F8ba6e99b3C00A34DcC),
address(0xe010aC6e0248790e08F42d5F697160DEDf97E024)];
//Stake each of the 5 miners specified above
for(uint i=0;i<6;i++){//6th miner to allow for dispute
//Miner balance is set at 1000e18 at the block that this function is ran
TellorTransfer.updateBalanceAtNow(tellor.balances[_initalMiners[i]],1000e18);
//newStake(self, _initalMiners[i]);
}
//update the total suppply
tellor.uintVars[keccak256("total_supply")] += 6000e18;//6th miner to allow for dispute
//set Constants
tellor.uintVars[keccak256("decimals")] = 18;
tellor.uintVars[keccak256("targetMiners")] = 200;
tellor.uintVars[keccak256("stakeAmount")] = 1000e18;
tellor.uintVars[keccak256("disputeFee")] = 970e18;
tellor.uintVars[keccak256("timeTarget")]= 600;
tellor.uintVars[keccak256("timeOfLastNewValue")] = now - now % tellor.uintVars[keccak256("timeTarget")];
tellor.uintVars[keccak256("difficulty")] = 1;
}
/**
* @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
* @dev Only needs to be in library
* @param _newDeity the new Deity in the contract
*/
function changeDeity(address _newDeity) external{
tellor.changeDeity(_newDeity);
}
/**
* @dev allows for the deity to make fast upgrades. Deity should be 0 address if decentralized
* @param _tellorContract the address of the new Tellor Contract
*/
function changeTellorContract(address _tellorContract) external{
tellor.changeTellorContract(_tellorContract);
}
/**
* @dev This is the fallback function that allows contracts to call the tellor contract at the address stored
*/
function () external payable {
address addr = tellor.addressVars[keccak256("tellorContract")];
bytes memory _calldata = msg.data;
assembly {
let result := delegatecall(not(0), addr, add(_calldata, 0x20), mload(_calldata), 0, 0)
let size := returndatasize
let ptr := mload(0x40)
returndatacopy(ptr, 0, size)
// revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas.
// if the call returned error data, forward it
switch result case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
}
/*
* @title Price/numeric Pull Oracle mapping contract
*/
contract OracleIDDescriptions {
/*Variables*/
mapping(uint=>bytes32) tellorIDtoBytesID;
mapping(bytes32 => uint) bytesIDtoTellorID;
mapping(uint => uint) tellorCodeToStatusCode;
mapping(uint => uint) statusCodeToTellorCode;
mapping(uint => int) tellorIdtoAdjFactor;
/*Events*/
event TellorIdMappedToBytes(uint _requestID, bytes32 _id);
event StatusMapped(uint _tellorStatus, uint _status);
event AdjFactorMapped(uint _requestID, int _adjFactor);
/**
* @dev This function allows the user to map the tellor's Id to it's _adjFactor and
* to match the standarized granularity
* @param _tellorId uint the tellor status
* @param _adjFactor is 1eN where N is the number of decimals to convert to ADO standard
*/
function defineTellorIdtoAdjFactor(uint _tellorId, int _adjFactor) external{
require(tellorIdtoAdjFactor[_tellorId] == 0, "Already Set");
tellorIdtoAdjFactor[_tellorId] = _adjFactor;
emit AdjFactorMapped(_tellorId, _adjFactor);
}
/**
* @dev This function allows the user to map the tellor uint data status code to the standarized
* ADO uint status code such as null, retreived etc...
* @param _tellorStatus uint the tellor status
* @param _status the ADO standarized uint status
*/
function defineTellorCodeToStatusCode(uint _tellorStatus, uint _status) external{
require(tellorCodeToStatusCode[_tellorStatus] == 0, "Already Set");
tellorCodeToStatusCode[_tellorStatus] = _status;
statusCodeToTellorCode[_status] = _tellorStatus;
emit StatusMapped(_tellorStatus, _status);
}
/**
* @dev Allows user to map the standarized bytes32 Id to a specific requestID from Tellor
* The dev should ensure the _requestId exists otherwise request the data on Tellor to get a requestId
* @param _requestID is the existing Tellor RequestID
* @param _id is the descption of the ID in bytes
*/
function defineTellorIdToBytesID(uint _requestID, bytes32 _id) external{
require(tellorIDtoBytesID[_requestID] == bytes32(0), "Already Set");
tellorIDtoBytesID[_requestID] = _id;
bytesIDtoTellorID[_id] = _requestID;
emit TellorIdMappedToBytes(_requestID,_id);
}
/**
* @dev Getter function for the uint Tellor status code from the specified uint ADO standarized status code
* @param _status the uint ADO standarized status
* @return _tellorStatus uint
*/
function getTellorStatusFromStatus(uint _status) public view returns(uint _tellorStatus){
return statusCodeToTellorCode[_status];
}
/**
* @dev Getter function of the uint ADO standarized status code from the specified Tellor uint status
* @param _tellorStatus uint
* @return _status the uint ADO standarized status
*/
function getStatusFromTellorStatus (uint _tellorStatus) public view returns(uint _status) {
return tellorCodeToStatusCode[_tellorStatus];
}
/**
* @dev Getter function of the Tellor RequestID based on the specified bytes32 ADO standaraized _id
* @param _id is the bytes32 descriptor mapped to an existing Tellor's requestId
* @return _requestId is Tellor's requestID corresnpoding to _id
*/
function getTellorIdFromBytes(bytes32 _id) public view returns(uint _requestId) {
return bytesIDtoTellorID[_id];
}
/**
* @dev Getter function of the Tellor RequestID based on the specified bytes32 ADO standaraized _id
* @param _id is the bytes32 descriptor mapped to an existing Tellor's requestId
* @return _requestId is Tellor's requestID corresnpoding to _id
*/
function getGranularityAdjFactor(bytes32 _id) public view returns(int adjFactor) {
uint requestID = bytesIDtoTellorID[_id];
adjFactor = tellorIdtoAdjFactor[requestID];
return adjFactor;
}
/**
* @dev Getter function of the bytes32 ADO standaraized _id based on the specified Tellor RequestID
* @param _requestId is Tellor's requestID
* @return _id is the bytes32 descriptor mapped to an existing Tellor's requestId
*/
function getBytesFromTellorID(uint _requestId) public view returns(bytes32 _id) {
return tellorIDtoBytesID[_requestId];
}
}
pragma solidity >=0.5.0 <0.7.0;
/**
* @dev EIP2362 Interface for pull oracles
* https://github.com/tellor-io/EIP-2362
*/
interface EIP2362Interface{
/**
* @dev Exposed function pertaining to EIP standards
* @param _id bytes32 ID of the query
* @return int,uint,uint returns the value, timestamp, and status code of query
*/
function valueFor(bytes32 _id) external view returns(int256,uint256,uint256);
}
/**
* @title UserContract
* This contracts creates for easy integration to the Tellor System
* by allowing smart contracts to read data off Tellor
*/
contract UsingTellor is EIP2362Interface{
address payable public tellorStorageAddress;
address public oracleIDDescriptionsAddress;
TellorMaster _tellorm;
OracleIDDescriptions descriptions;
event NewDescriptorSet(address _descriptorSet);
constructor(address payable _storage) public {
tellorStorageAddress = _storage;
_tellorm = TellorMaster(tellorStorageAddress);
}
/*Functions*/
/*
* @dev Allows the owner to set the address for the oracleID descriptors
* used by the ADO members for price key value pairs standarization
* _oracleDescriptors is the address for the OracleIDDescriptions contract
*/
function setOracleIDDescriptors(address _oracleDescriptors) external {
require(oracleIDDescriptionsAddress == address(0), "Already Set");
oracleIDDescriptionsAddress = _oracleDescriptors;
descriptions = OracleIDDescriptions(_oracleDescriptors);
emit NewDescriptorSet(_oracleDescriptors);
}
/**
* @dev Allows the user to get the latest value for the requestId specified
* @param _requestId is the requestId to look up the value for
* @return bool true if it is able to retreive a value, the value, and the value's timestamp
*/
function getCurrentValue(uint256 _requestId) public view returns (bool ifRetrieve, uint256 value, uint256 _timestampRetrieved) {
return getDataBefore(_requestId,now);
}
/**
* @dev Allows the user to get the latest value for the requestId specified using the
* ADO specification for the standard inteface for price oracles
* @param _bytesId is the ADO standarized bytes32 price/key value pair identifier
* @return the timestamp, outcome or value/ and the status code (for retreived, null, etc...)
*/
function valueFor(bytes32 _bytesId) external view returns (int value, uint256 timestamp, uint status) {
uint _id = descriptions.getTellorIdFromBytes(_bytesId);
int n = descriptions.getGranularityAdjFactor(_bytesId);
if (_id > 0){
bool _didGet;
uint256 _returnedValue;
uint256 _timestampRetrieved;
(_didGet,_returnedValue,_timestampRetrieved) = getDataBefore(_id,now);
if(_didGet){
return (int(_returnedValue)*n,_timestampRetrieved, descriptions.getStatusFromTellorStatus(1));
}
else{
return (0,0,descriptions.getStatusFromTellorStatus(2));
}
}
return (0, 0, descriptions.getStatusFromTellorStatus(0));
}
/**
* @dev Allows the user to get the first value for the requestId after the specified timestamp
* @param _requestId is the requestId to look up the value for
* @param _timestamp after which to search for first verified value
* @return bool true if it is able to retreive a value, the value, and the value's timestamp
*/
function getDataBefore(uint256 _requestId, uint256 _timestamp)
public
view
returns (bool _ifRetrieve, uint256 _value, uint256 _timestampRetrieved)
{
uint256 _count = _tellorm.getNewValueCountbyRequestId(_requestId);
if (_count > 0) {
for (uint256 i = _count; i > 0; i--) {
uint256 _time = _tellorm.getTimestampbyRequestIDandIndex(_requestId, i - 1);
if (_time > 0 && _time <= _timestamp && _tellorm.isInDispute(_requestId,_time) == false) {
return (true, _tellorm.retrieveData(_requestId, _time), _time);
}
}
}
return (false, 0, 0);
}
}
contract PriceLock is UsingTellor {
// custom data structure to hold locked funds and time
uint256 public tellorID;
uint256 public currentValue;
bool _didGet;
uint256 _timestamp;
struct accountData {
uint balance;
uint releaseTime;
uint targetPrice;
}
// only one locked account per address
mapping (address => accountData) accounts;
constructor(uint _tellorID, address payable _tellorAddress) UsingTellor(_tellorAddress) public {
tellorID = _tellorID;
}
function payIn(uint lockTimeS, uint price) public payable {
// send some amount (in Wei) when calling this function.
// the amount will then be placed in a locked account
// the funds will be released once the indicated lock time in seconds
// passed or target price is reached and can only be retrieved by the same account which was
// depositing them - highlighting the intrinsic security model
// offered by a blockchain system like Ethereum
uint amount = msg.value;
payOut();
if (accounts[msg.sender].balance > 0)
msg.sender.transfer(msg.value);
else {
accounts[msg.sender].targetPrice = price;
accounts[msg.sender].balance = amount;
accounts[msg.sender].releaseTime = now + lockTimeS;
}
}
function payOut() public{
(_didGet,currentValue,_timestamp) = getCurrentValue(tellorID);
// check if user has funds due for pay out because lock time is over or targetprice is reached
if ((accounts[msg.sender].balance != 0 && accounts[msg.sender].releaseTime < now) || (accounts[msg.sender].balance != 0 && accounts[msg.sender].targetPrice < currentValue)) {
msg.sender.transfer(accounts[msg.sender].balance);
accounts[msg.sender].balance = 0;
accounts[msg.sender].releaseTime = 0;
}
}
function getMyLockedFunds() public view returns (uint) {
return accounts[msg.sender].balance;
}
function getMyTargetPrice() public view returns (uint) {
return accounts[msg.sender].targetPrice;
}
function getMyReleaseTime() public view returns (uint) {
return accounts[msg.sender].releaseTime;
}
}
| check if user has funds due for pay out because lock time is over or targetprice is reached | function payOut() public{
(_didGet,currentValue,_timestamp) = getCurrentValue(tellorID);
if ((accounts[msg.sender].balance != 0 && accounts[msg.sender].releaseTime < now) || (accounts[msg.sender].balance != 0 && accounts[msg.sender].targetPrice < currentValue)) {
msg.sender.transfer(accounts[msg.sender].balance);
accounts[msg.sender].balance = 0;
accounts[msg.sender].releaseTime = 0;
}
}
| 1,755,541 | [
1,
1893,
309,
729,
711,
284,
19156,
6541,
364,
8843,
596,
2724,
2176,
813,
353,
1879,
578,
1018,
8694,
353,
8675,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
8843,
1182,
1435,
1071,
95,
203,
3639,
261,
67,
14044,
967,
16,
2972,
620,
16,
67,
5508,
13,
273,
5175,
620,
12,
88,
1165,
280,
734,
1769,
203,
3639,
309,
14015,
13739,
63,
3576,
18,
15330,
8009,
12296,
480,
374,
597,
9484,
63,
3576,
18,
15330,
8009,
9340,
950,
411,
2037,
13,
747,
261,
13739,
63,
3576,
18,
15330,
8009,
12296,
480,
374,
597,
9484,
63,
3576,
18,
15330,
8009,
3299,
5147,
411,
14794,
3719,
288,
203,
5411,
1234,
18,
15330,
18,
13866,
12,
13739,
63,
3576,
18,
15330,
8009,
12296,
1769,
203,
5411,
9484,
63,
3576,
18,
15330,
8009,
12296,
273,
374,
31,
203,
5411,
9484,
63,
3576,
18,
15330,
8009,
9340,
950,
273,
374,
31,
203,
3639,
289,
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
] |
./partial_match/1/0x294fED5F1D3D30cfA6Fe86A937dC3141EEc8bC6d/sources/contracts/engine/V3/forks/GenArt721CoreV3_Engine_Flex_PROOF.sol | * @notice Returns project details for project `_projectId`. @param _projectId Project to be queried. @return projectName Name of project @return artist Artist of project @return description Project description @return website Project website @return license Project license @dev this function was named projectDetails prior to V3 core contract./ | function projectDetails(
uint256 _projectId
)
external
view
returns (
string memory projectName,
string memory artist,
string memory description,
string memory website,
string memory license
)
{
Project storage project = projects[_projectId];
projectName = project.name;
artist = project.artist;
description = project.description;
website = project.website;
license = project.license;
}
| 15,526,702 | [
1,
1356,
1984,
3189,
364,
1984,
1375,
67,
4406,
548,
8338,
225,
389,
4406,
548,
5420,
358,
506,
23264,
18,
327,
17234,
1770,
434,
1984,
327,
15469,
9042,
376,
434,
1984,
327,
2477,
5420,
2477,
327,
12504,
5420,
12504,
327,
8630,
5420,
8630,
225,
333,
445,
1703,
4141,
1984,
3790,
6432,
358,
776,
23,
2922,
6835,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1984,
3790,
12,
203,
3639,
2254,
5034,
389,
4406,
548,
203,
565,
262,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
203,
5411,
533,
3778,
17234,
16,
203,
5411,
533,
3778,
15469,
16,
203,
5411,
533,
3778,
2477,
16,
203,
5411,
533,
3778,
12504,
16,
203,
5411,
533,
3778,
8630,
203,
3639,
262,
203,
565,
288,
203,
3639,
5420,
2502,
1984,
273,
10137,
63,
67,
4406,
548,
15533,
203,
3639,
17234,
273,
1984,
18,
529,
31,
203,
3639,
15469,
273,
1984,
18,
25737,
31,
203,
3639,
2477,
273,
1984,
18,
3384,
31,
203,
3639,
12504,
273,
1984,
18,
21868,
31,
203,
3639,
8630,
273,
1984,
18,
12687,
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
] |
pragma solidity ^0.6.0;
contract initializable5 { //inject NONSTANDARD NAMING
bool private initialized;
bool private initializing;
modifier INITIALIZER65() { //inject NONSTANDARD NAMING
require(initializing || ISCONSTRUCTOR91() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
function ISCONSTRUCTOR91() private view returns (bool) { //inject NONSTANDARD NAMING
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
contract contextupgradesafe87 is initializable5 { //inject NONSTANDARD NAMING
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __CONTEXT_INIT10() internal INITIALIZER65 { //inject NONSTANDARD NAMING
__CONTEXT_INIT_UNCHAINED61();
}
function __CONTEXT_INIT_UNCHAINED61() internal INITIALIZER65 { //inject NONSTANDARD NAMING
}
function _MSGSENDER78() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA22() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
contract ownableupgradesafe25 is initializable5, contextupgradesafe87 { //inject NONSTANDARD NAMING
address private _owner;
event OWNERSHIPTRANSFERRED52(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
function __OWNABLE_INIT13() internal INITIALIZER65 { //inject NONSTANDARD NAMING
__CONTEXT_INIT_UNCHAINED61();
__OWNABLE_INIT_UNCHAINED84();
}
function __OWNABLE_INIT_UNCHAINED84() internal INITIALIZER65 { //inject NONSTANDARD NAMING
address msgSender = _MSGSENDER78();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED52(address(0), msgSender);
}
function OWNER9() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER81() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER78(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP19() public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED52(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP24(address newOwner) public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED52(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
library safemath14 { //inject NONSTANDARD NAMING
function ADD80(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB60(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB60(a, b, "SafeMath: subtraction overflow");
}
function SUB60(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL16(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV54(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV54(a, b, "SafeMath: division by zero");
}
function DIV54(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD56(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD56(a, b, "SafeMath: modulo by zero");
}
function MOD56(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
interface ierc2086 { //inject NONSTANDARD NAMING
function TOTALSUPPLY25() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF21(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER6(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE84(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE33(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM54(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER56(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL90(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library console87 { //inject NONSTANDARD NAMING
address constant console_address36 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING
function _SENDLOGPAYLOAD51(bytes memory payload) private view { //inject NONSTANDARD NAMING
uint256 payloadLength = payload.length;
address consoleAddress = console_address36;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function LOG40() internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log()"));
}
function LOGINT64(int p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(int)", p0));
}
function LOGUINT96(uint p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0));
}
function LOGSTRING94(string memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0));
}
function LOGBOOL52(bool p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0));
}
function LOGADDRESS2(address p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0));
}
function LOGBYTES0(bytes memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes)", p0));
}
function LOGBYTE23(byte p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(byte)", p0));
}
function LOGBYTES1100(bytes1 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes1)", p0));
}
function LOGBYTES273(bytes2 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes2)", p0));
}
function LOGBYTES377(bytes3 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes3)", p0));
}
function LOGBYTES477(bytes4 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes4)", p0));
}
function LOGBYTES578(bytes5 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes5)", p0));
}
function LOGBYTES61(bytes6 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes6)", p0));
}
function LOGBYTES735(bytes7 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes7)", p0));
}
function LOGBYTES818(bytes8 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes8)", p0));
}
function LOGBYTES931(bytes9 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes9)", p0));
}
function LOGBYTES1064(bytes10 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes10)", p0));
}
function LOGBYTES1141(bytes11 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes11)", p0));
}
function LOGBYTES1261(bytes12 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes12)", p0));
}
function LOGBYTES1365(bytes13 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes13)", p0));
}
function LOGBYTES1433(bytes14 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes14)", p0));
}
function LOGBYTES1532(bytes15 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes15)", p0));
}
function LOGBYTES1678(bytes16 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes16)", p0));
}
function LOGBYTES176(bytes17 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes17)", p0));
}
function LOGBYTES1833(bytes18 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes18)", p0));
}
function LOGBYTES1973(bytes19 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes19)", p0));
}
function LOGBYTES202(bytes20 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes20)", p0));
}
function LOGBYTES2137(bytes21 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes21)", p0));
}
function LOGBYTES2248(bytes22 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes22)", p0));
}
function LOGBYTES2317(bytes23 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes23)", p0));
}
function LOGBYTES2438(bytes24 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes24)", p0));
}
function LOGBYTES2548(bytes25 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes25)", p0));
}
function LOGBYTES261(bytes26 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes26)", p0));
}
function LOGBYTES2793(bytes27 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes27)", p0));
}
function LOGBYTES2869(bytes28 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes28)", p0));
}
function LOGBYTES299(bytes29 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes29)", p0));
}
function LOGBYTES3053(bytes30 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes30)", p0));
}
function LOGBYTES3139(bytes31 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes31)", p0));
}
function LOGBYTES3263(bytes32 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes32)", p0));
}
function LOG40(uint p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0));
}
function LOG40(string memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0));
}
function LOG40(bool p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0));
}
function LOG40(address p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0));
}
function LOG40(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function LOG40(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function LOG40(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function LOG40(uint p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function LOG40(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function LOG40(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function LOG40(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function LOG40(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function LOG40(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function LOG40(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function LOG40(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function LOG40(bool p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function LOG40(address p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function LOG40(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function LOG40(address p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function LOG40(address p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function LOG40(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function LOG40(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function LOG40(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function LOG40(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function LOG40(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function LOG40(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function LOG40(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function LOG40(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function LOG40(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function LOG40(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function LOG40(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function LOG40(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function LOG40(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function LOG40(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function LOG40(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function LOG40(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function LOG40(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function LOG40(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function LOG40(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function LOG40(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function LOG40(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
interface iuniswapv2factory11 { //inject NONSTANDARD NAMING
event PAIRCREATED16(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING
function FEETO47() external view returns (address); //inject NONSTANDARD NAMING
function FEETOSETTER62() external view returns (address); //inject NONSTANDARD NAMING
function GETPAIR25(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRS78(uint) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRSLENGTH45() external view returns (uint); //inject NONSTANDARD NAMING
function CREATEPAIR19(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING
function SETFEETO7(address) external; //inject NONSTANDARD NAMING
function SETFEETOSETTER93(address) external; //inject NONSTANDARD NAMING
}
contract feeapprover21 is ownableupgradesafe25 { //inject NONSTANDARD NAMING
using safemath14 for uint256;
function INITIALIZE58( //inject NONSTANDARD NAMING
address _NANOCOREAddress,
address _WETHAddress,
address _uniswapFactory
) public INITIALIZER65 {
ownableupgradesafe25.__OWNABLE_INIT13();
nanocoreTokenAddress = _NANOCOREAddress;
WETHAddress = _WETHAddress;
tokenUniswapPair = iuniswapv2factory11(_uniswapFactory).GETPAIR25(WETHAddress,nanocoreTokenAddress);
feePercentX100 = 15;
paused = false; // We start paused until sync post LGE happens.
}
address tokenUniswapPair;
iuniswapv2factory11 public uniswapFactory;
address internal WETHAddress;
address nanocoreTokenAddress;
address nanocoreVaultAddress;
uint8 public feePercentX100; // max 255 = 25.5% artificial clamp
uint256 public lastTotalSupplyOfLPTokens;
bool paused;
// Pausing transfers of the token
function SETPAUSED71(bool _pause) public ONLYOWNER81 { //inject NONSTANDARD NAMING
paused = _pause;
}
function SETFEEMULTIPLIER40(uint8 _feeMultiplier) public ONLYOWNER81 { //inject NONSTANDARD NAMING
feePercentX100 = _feeMultiplier;
}
function SETNANOCOREVAULTADDRESS89(address _nanocoreVaultAddress) public ONLYOWNER81 { //inject NONSTANDARD NAMING
nanocoreVaultAddress = _nanocoreVaultAddress;
}
function SYNC99() public { //inject NONSTANDARD NAMING
uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25();
lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal;
}
function CALCULATEAMOUNTSAFTERFEE82( //inject NONSTANDARD NAMING
address sender,
address recipient, // unusued maybe use din future
uint256 amount
) public returns (uint256 transferToAmount, uint256 transferToFeeDistributorAmount)
{
require(paused == false, "FEE APPROVER: Transfers Paused");
uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25();
// console.log("sender is " , sender);
// console.log("recipient is is " , recipient, 'pair is :', tokenUniswapPair);
// console.log("Old LP supply", lastTotalSupplyOfLPTokens);
// console.log("Current LP supply", _LPSupplyOfPairTotal);
if(sender == tokenUniswapPair)
require(lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal, "Liquidity withdrawals forbidden");
// console.log('Sender is pair' , sender == tokenUniswapPair);
// console.log('lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal' , lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal);
if(sender == nanocoreVaultAddress || sender == tokenUniswapPair ) { // Dont have a fee when nanocorevault is sending, or infinite loop
console87.LOG40("Sending without fee"); // And when pair is sending ( buys are happening, no tax on it)
transferToFeeDistributorAmount = 0;
transferToAmount = amount;
}
else {
console87.LOG40("Normal fee transfer");
transferToFeeDistributorAmount = amount.MUL16(feePercentX100).DIV54(1000);
transferToAmount = amount.SUB60(transferToFeeDistributorAmount);
}
lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal;
}
} | inject NONSTANDARD NAMING
| function LOG40(address p0, address p1, bool p2, string memory p3) internal view { | 1,019,209 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
915,
2018,
7132,
12,
2867,
293,
20,
16,
1758,
293,
21,
16,
1426,
293,
22,
16,
533,
3778,
293,
23,
13,
2713,
1476,
288,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
// File: contracts\zeppelin\ownership\Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: contracts\zeppelin\math\SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// File: contracts\zeppelin\token\ERC20\ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: contracts\zeppelin\token\ERC20\BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
// File: contracts\zeppelin\token\ERC20\ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: contracts\zeppelin\token\ERC20\StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: contracts\zeppelin\token\ERC20\MintableToken.sol
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, 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;
}
}
// File: contracts\zeppelin\token\ERC20\CappedToken.sol
/**
* @title Capped token
* @dev Mintable token with a token cap.
*/
contract CappedToken is MintableToken {
uint256 public cap;
constructor(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address _to,
uint256 _amount
)
onlyOwner
canMint
public
returns (bool)
{
require(totalSupply_.add(_amount) <= cap);
return super.mint(_to, _amount);
}
}
// File: contracts\zeppelin\lifecycle\Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
// File: contracts\zeppelin\token\ERC20\PausableToken.sol
/**
* @title Pausable token
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, Pausable {
function transfer(
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transfer(_to, _value);
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
function approve(
address _spender,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.approve(_spender, _value);
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool success)
{
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool success)
{
return super.decreaseApproval(_spender, _subtractedValue);
}
}
// File: contracts\CoinolixToken.sol
/**
* @title Coinolix icoToken
* @dev Coinolix icoToken - Token code for the Coinolix icoProject
* This is a standard ERC20 token with:
* - a cap
* - ability to pause transfers
*/
contract CoinolixToken is CappedToken, PausableToken {
string public constant name = "Coinolix token";
string public constant symbol = "CLX";
uint public constant decimals = 18;
constructor(uint256 _totalSupply)
CappedToken(_totalSupply) public {
paused = true;
}
}
// File: contracts\zeppelin\token\ERC20\SafeERC20.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
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));
}
}
// File: contracts\TokenPool.sol
/**
* @title TokenPool
* @dev Token Pool contract used to store tokens for special purposes
* The pool can receive tokens and can transfer tokens to multiple beneficiaries.
* It can be used for airdrops or similar cases.
*/
contract TokenPool is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20Basic;
ERC20Basic public token;
uint256 public cap;
uint256 public totalAllocated;
/**
* @dev Contract constructor
* @param _token address token that will be stored in the pool
* @param _cap uint256 predefined cap of the pool
*/
constructor(address _token, uint256 _cap) public {
token = ERC20Basic(_token);
cap = _cap;
totalAllocated = 0;
}
/**
* @dev Transfer different amounts of tokens to multiple beneficiaries
* @param _beneficiaries addresses of the beneficiaries
* @param _amounts uint256[] amounts for each beneficiary
*/
function allocate(address[] _beneficiaries, uint256[] _amounts) public onlyOwner {
for (uint256 i = 0; i < _beneficiaries.length; i ++) {
require(totalAllocated.add(_amounts[i]) <= cap);
token.safeTransfer(_beneficiaries[i], _amounts[i]);
totalAllocated.add(_amounts[i]);
}
}
/**
* @dev Transfer the same amount of tokens to multiple beneficiaries
* @param _beneficiaries addresses of the beneficiaries
* @param _amounts uint256[] amounts for each beneficiary
*/
function allocateEqual(address[] _beneficiaries, uint256 _amounts) public onlyOwner {
uint256 totalAmount = _amounts.mul(_beneficiaries.length);
require(totalAllocated.add(totalAmount) <= cap);
require(token.balanceOf(this) >= totalAmount);
for (uint256 i = 0; i < _beneficiaries.length; i ++) {
token.safeTransfer(_beneficiaries[i], _amounts);
totalAllocated.add(_amounts);
}
}
}
// File: contracts\zeppelin\crowdsale\Crowdsale.sol
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overriden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropiate to concatenate
* behavior.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
ERC20 public token;
// Address where funds are collected
address public wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called CLX
// 1 wei will give you 1 unit, or 0.001 CLX.
uint256 public rate;
// Amount of wei raised
uint256 public weiRaised;
/**
* 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
);
/**
* @param _rate Number of token units a buyer gets per wei
* @param _wallet Address where collected funds will be forwarded to
* @param _token Address of the token being sold
*/
constructor(uint256 _rate, address _wallet, ERC20 _token) public {
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
rate = _rate;
wallet = _wallet;
token = _token;
}
// -----------------------------------------
// 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
);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
require(_beneficiary != address(0));
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
token.transfer(_beneficiary, _tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
_deliverTokens(_beneficiary, _tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param _beneficiary Address receiving the tokens
* @param _weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(
address _beneficiary,
uint256 _weiAmount
)
internal
{
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
return _weiAmount.mul(rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
// File: contracts\zeppelin\crowdsale\validation\TimedCrowdsale.sol
/**
* @title TimedCrowdsale
* @dev Crowdsale accepting contributions only within a time frame.
*/
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
// solium-disable-next-line security/no-block-members
require(block.timestamp >= openingTime && block.timestamp <= closingTime);
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param _openingTime Crowdsale opening time
* @param _closingTime Crowdsale closing time
*/
constructor(uint256 _openingTime, uint256 _closingTime) public {
// solium-disable-next-line security/no-block-members
require(_openingTime >= block.timestamp);
require(_closingTime >= _openingTime);
openingTime = _openingTime;
closingTime = _closingTime;
}
/**
* @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) {
// solium-disable-next-line security/no-block-members
return block.timestamp > closingTime;
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
onlyWhileOpen
{
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
// File: contracts\zeppelin\crowdsale\distribution\FinalizableCrowdsale.sol
/**
* @title FinalizableCrowdsale
* @dev Extension of Crowdsale where an owner can do extra work
* after finishing.
*/
contract FinalizableCrowdsale is TimedCrowdsale, Ownable {
using SafeMath for uint256;
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 Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal {
}
}
// File: contracts\zeppelin\crowdsale\distribution\utils\RefundVault.sol
/**
* @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);
}
}
// File: contracts\zeppelin\crowdsale\distribution\RefundableCrowdsale.sol
/**
* @title RefundableCrowdsale
* @dev Extension of Crowdsale contract that adds a funding goal, and
* the possibility of users getting a refund if goal is not met.
* Uses a RefundVault as the crowdsale's vault.
*/
contract RefundableCrowdsale is FinalizableCrowdsale {
using SafeMath for uint256;
// 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;
/**
* @dev Constructor, creates RefundVault.
* @param _goal Funding goal
*/
constructor(uint256 _goal) public {
require(_goal > 0);
vault = new RefundVault(wallet);
goal = _goal;
}
/**
* @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();
}
super.finalization();
}
/**
* @dev Overrides Crowdsale fund forwarding, sending funds to vault.
*/
function _forwardFunds() internal {
vault.deposit.value(msg.value)(msg.sender);
}
}
// File: contracts\zeppelin\crowdsale\emission\MintedCrowdsale.sol
/**
* @title MintedCrowdsale
* @dev Extension of Crowdsale contract whose tokens are minted in each purchase.
* Token ownership should be transferred to MintedCrowdsale for minting.
*/
contract MintedCrowdsale is Crowdsale {
/**
* @dev Overrides delivery by minting tokens upon purchase.
* @param _beneficiary Token purchaser
* @param _tokenAmount Number of tokens to be minted
*/
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
require(MintableToken(token).mint(_beneficiary, _tokenAmount));
}
}
/**
* @title AirdropAndAffiliateCrowdsale
* @dev Extension of AirdropAndAffiliateCrowdsale contract
*/
contract AirdropAndAffiliateCrowdsale is MintedCrowdsale {
uint256 public valueAirDrop;
uint256 public referrerBonus1;
uint256 public referrerBonus2;
mapping (address => uint8) public payedAddress;
mapping (address => address) public referrers;
constructor(uint256 _valueAirDrop, uint256 _referrerBonus1, uint256 _referrerBonus2) public {
valueAirDrop = _valueAirDrop;
referrerBonus1 = _referrerBonus1;
referrerBonus2 = _referrerBonus2;
}
function bytesToAddress(bytes source) internal pure returns(address) {
uint result;
uint mul = 1;
for(uint i = 20; i > 0; i--) {
result += uint8(source[i-1])*mul;
mul = mul*256;
}
return address(result);
}
/**
* @dev Overrides delivery by minting tokens upon purchase.
* @param _beneficiary Token purchaser
* @param _tokenAmount Number of tokens to be minted
*/
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
address referer1;
uint256 refererTokens1;
address referer2;
uint256 refererTokens2;
if (_tokenAmount != 0){
super._deliverTokens(_beneficiary, _tokenAmount);
//require(MintableToken(token).mint(_beneficiary, _tokenAmount));
}
else{
require(payedAddress[_beneficiary] == 0);
payedAddress[_beneficiary] = 1;
super._deliverTokens(_beneficiary, valueAirDrop);
_tokenAmount = valueAirDrop;
}
//referral system
if(msg.data.length == 20) {
referer1 = bytesToAddress(bytes(msg.data));
referrers[_beneficiary] = referer1;
if(referer1 != _beneficiary){
//add tokens to the referrer1
refererTokens1 = _tokenAmount.mul(referrerBonus1).div(100);
super._deliverTokens(referer1, refererTokens1);
referer2 = referrers[referer1];
if(referer2 != address(0)){
refererTokens2 = _tokenAmount.mul(referrerBonus2).div(100);
super._deliverTokens(referer2, refererTokens2);
}
}
}
}
}
// File: contracts\zeppelin\crowdsale\validation\CappedCrowdsale.sol
/**
* @title CappedCrowdsale
* @dev Crowdsale with a limit for total contributions.
*/
contract CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public cap;
/**
* @dev Constructor, takes maximum amount of wei accepted in the crowdsale.
* @param _cap Max amount of wei to be contributed
*/
constructor(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
/**
* @dev Checks whether the cap has been reached.
* @return Whether the cap was reached
*/
function capReached() public view returns (bool) {
return weiRaised >= cap;
}
/**
* @dev Extend parent behavior requiring purchase to respect the funding cap.
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
super._preValidatePurchase(_beneficiary, _weiAmount);
require(weiRaised.add(_weiAmount) <= cap);
}
}
// File: contracts\zeppelin\crowdsale\validation\WhitelistedCrowdsale.sol
/**
* @title WhitelistedCrowdsale
* @dev Crowdsale in which only whitelisted users can contribute.
*/
contract WhitelistedCrowdsale is Crowdsale, Ownable {
mapping(address => bool) public whitelist;
/**
* @dev Reverts if beneficiary is not whitelisted. Can be used when extending this contract.
*/
modifier isWhitelisted(address _beneficiary) {
require(whitelist[_beneficiary]);
_;
}
/**
* @dev Adds single address to whitelist.
* @param _beneficiary Address to be added to the whitelist
*/
function addToWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = true;
}
/**
* @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing.
* @param _beneficiaries Addresses to be added to the whitelist
*/
function addManyToWhitelist(address[] _beneficiaries) external onlyOwner {
for (uint256 i = 0; i < _beneficiaries.length; i++) {
whitelist[_beneficiaries[i]] = true;
}
}
/**
* @dev Removes single address from whitelist.
* @param _beneficiary Address to be removed to the whitelist
*/
function removeFromWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = false;
}
/**
* @dev Extend parent behavior requiring beneficiary to be in whitelist.
* @param _beneficiary Token beneficiary
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
isWhitelisted(_beneficiary)
{
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
// File: contracts\zeppelin\token\ERC20\TokenTimelock.sol
/**
* @title TokenTimelock
* @dev TokenTimelock is a token holder contract that will allow a
* beneficiary to extract the tokens after a given release time
*/
contract TokenTimelock {
using SafeERC20 for ERC20Basic;
// ERC20 basic token contract being held
ERC20Basic public token;
// beneficiary of tokens after they are released
address public beneficiary;
// timestamp when token release is enabled
uint256 public releaseTime;
constructor(
ERC20Basic _token,
address _beneficiary,
uint256 _releaseTime
)
public
{
// solium-disable-next-line security/no-block-members
require(_releaseTime > block.timestamp);
token = _token;
beneficiary = _beneficiary;
releaseTime = _releaseTime;
}
/**
* @notice Transfers tokens held by timelock to beneficiary.
*/
function release() public {
// solium-disable-next-line security/no-block-members
require(block.timestamp >= releaseTime);
uint256 amount = token.balanceOf(this);
require(amount > 0);
token.safeTransfer(beneficiary, amount);
}
}
// File: contracts\CoinolixCrowdsale.sol
/**
* @title Coinolix ico Crowdsale Contract
* @dev Coinolix ico Crowdsale Contract
* The contract is for the crowdsale of the Coinolix icotoken. It is:
* - With a hard cap in ETH
* - With a soft cap in ETH
* - Limited in time (start/end date)
* - Only for whitelisted participants to purchase tokens
* - Ether is securely stored in RefundVault until the end of the crowdsale
* - At the end of the crowdsale if the goal is reached funds can be used
* ...otherwise the participants can refund their investments
* - Tokens are minted on each purchase
* - Sale can be paused if needed by the admin
*/
contract CoinolixCrowdsale is
AirdropAndAffiliateCrowdsale,
//MintedCrowdsale,
CappedCrowdsale,
TimedCrowdsale,
FinalizableCrowdsale,
WhitelistedCrowdsale,
RefundableCrowdsale,
Pausable {
using SafeMath for uint256;
// Initial distribution
uint256 public constant PUBLIC_TOKENS = 50; // 50% from totalSupply CROWDSALE + PRESALE
uint256 public constant PVT_INV_TOKENS = 15; // 15% from totalSupply PRIVATE SALE INVESTOR
uint256 public constant TEAM_TOKENS = 20; // 20% from totalSupply FOUNDERS
uint256 public constant ADV_TEAM_TOKENS = 10; // 10% from totalSupply ADVISORS
uint256 public constant BOUNTY_TOKENS = 2; // 2% from totalSupply BOUNTY
uint256 public constant REFF_TOKENS = 3; // 3% from totalSupply REFFERALS
uint256 public constant TEAM_LOCK_TIME = 31540000; // 1 year in seconds
uint256 public constant ADV_TEAM_LOCK_TIME = 15770000; // 6 months in seconds
// Rate bonuses
uint256 public initialRate;
uint256[4] public bonuses = [20,10,5,0];
uint256[4] public stages = [
1541635200, // 1st two week of crowdsale -> 20% Bonus
1542844800, // 3rd week of crowdsale -> 10% Bonus
1543449600, // 4th week of crowdsale -> 5% Bonus
1544054400 // 5th week of crowdsale -> 0% Bonus
];
// Min investment
uint256 public minInvestmentInWei;
// Max individual investment
uint256 public maxInvestmentInWei;
mapping (address => uint256) internal invested;
TokenTimelock public teamWallet;
TokenTimelock public advteamPool;
TokenPool public reffalPool;
TokenPool public pvt_inv_Pool;
// Events for this contract
/**
* Event triggered when changing the current rate on different stages
* @param rate new rate
*/
event CurrentRateChange(uint256 rate);
/**
* @dev Contract constructor
* @param _cap uint256 hard cap of the crowdsale
* @param _goal uint256 soft cap of the crowdsale
* @param _openingTime uint256 crowdsale start date/time
* @param _closingTime uint256 crowdsale end date/time
* @param _rate uint256 initial rate CLX for 1 ETH
* @param _minInvestmentInWei uint256 minimum investment amount
* @param _maxInvestmentInWei uint256 maximum individual investment amount
* @param _wallet address address where the collected funds will be transferred
* @param _token CoinolixToken our token
*/
constructor(
uint256 _cap,
uint256 _goal,
uint256 _openingTime,
uint256 _closingTime,
uint256 _rate,
uint256 _minInvestmentInWei,
uint256 _maxInvestmentInWei,
address _wallet,
CoinolixToken _token,
uint256 _valueAirDrop,
uint256 _referrerBonus1,
uint256 _referrerBonus2)
Crowdsale(_rate, _wallet, _token)
CappedCrowdsale(_cap)
AirdropAndAffiliateCrowdsale(_valueAirDrop, _referrerBonus1, _referrerBonus2)
TimedCrowdsale(_openingTime, _closingTime)
RefundableCrowdsale(_goal) public {
require(_goal <= _cap);
initialRate = _rate;
minInvestmentInWei = _minInvestmentInWei;
maxInvestmentInWei = _maxInvestmentInWei;
}
/**
* @dev Perform the initial token distribution according to the Coinolix icocrowdsale rules
* @param _teamAddress address address for the team tokens
* @param _bountyPoolAddress address address for the prize pool
* @param _advisorPoolAdddress address address for the reserve pool
*/
function doInitialDistribution(
address _teamAddress,
address _bountyPoolAddress,
address _advisorPoolAdddress) external onlyOwner {
// Create locks for team and visor pools
teamWallet = new TokenTimelock(token, _teamAddress, closingTime.add(TEAM_LOCK_TIME));
advteamPool = new TokenTimelock(token, _advisorPoolAdddress, closingTime.add(ADV_TEAM_LOCK_TIME));
// Perform initial distribution
uint256 tokenCap = CappedToken(token).cap();
//private investor pool
pvt_inv_Pool= new TokenPool(token, tokenCap.mul(PVT_INV_TOKENS).div(100));
//airdrop,bounty and reffalPool
reffalPool = new TokenPool(token, tokenCap.mul(REFF_TOKENS).div(100));
// Distribute tokens to pools
MintableToken(token).mint(teamWallet, tokenCap.mul(TEAM_TOKENS).div(100));
MintableToken(token).mint(_bountyPoolAddress, tokenCap.mul(BOUNTY_TOKENS).div(100));
MintableToken(token).mint(pvt_inv_Pool, tokenCap.mul(PVT_INV_TOKENS).div(100));
MintableToken(token).mint(reffalPool, tokenCap.mul(REFF_TOKENS).div(100));
MintableToken(token).mint(advteamPool, tokenCap.mul(ADV_TEAM_TOKENS).div(100));
// Ensure that only sale tokens left
assert(tokenCap.sub(token.totalSupply()) == tokenCap.mul(PUBLIC_TOKENS).div(100));
}
/**
* @dev Update the current rate based on the scheme
* 1st of Sep - 30rd of Sep -> 30% Bonus
* 1st of Oct - 31st of Oct -> 20% Bonus
* 1st of Nov - 30rd of Oct -> 10% Bonus
* 1st of Dec - 31st of Dec -> 0% Bonus
*/
function updateRate() external onlyOwner {
uint256 i = stages.length;
while (i-- > 0) {
if (block.timestamp >= stages[i]) {
rate = initialRate.add(initialRate.mul(bonuses[i]).div(100));
emit CurrentRateChange(rate);
break;
}
}
}
//update rate function by owner to keep stable rate in USD
function updateInitialRate(uint256 _rate) external onlyOwner {
initialRate = _rate;
uint256 i = stages.length;
while (i-- > 0) {
if (block.timestamp >= stages[i]) {
rate = initialRate.add(initialRate.mul(bonuses[i]).div(100));
emit CurrentRateChange(rate);
break;
}
}
}
/**
* @dev Perform an airdrop from the airdrop pool to multiple beneficiaries
* @param _beneficiaries address[] list of beneficiaries
* @param _amount uint256 amount to airdrop
*/
function airdropTokens(address[] _beneficiaries, uint256 _amount) external onlyOwner {
PausableToken(token).unpause();
reffalPool.allocateEqual(_beneficiaries, _amount);
PausableToken(token).pause();
}
/**
* @dev Transfer tokens to advisors and private investor from the pool
* @param _beneficiaries address[] list of beneficiaries
* @param _amounts uint256[] amounts
*/
function allocatePVT_InvTokens(address[] _beneficiaries, uint256[] _amounts) external onlyOwner {
PausableToken(token).unpause();
pvt_inv_Pool.allocate(_beneficiaries, _amounts);
PausableToken(token).pause();
}
/**
* @dev Transfer the ownership of the token conctract
* @param _newOwner address the new owner of the token
*/
function transferTokenOwnership(address _newOwner) onlyOwner public {
Ownable(token).transferOwnership(_newOwner);
}
/**
* @dev Validate min and max amounts and other purchase conditions
* @param _beneficiary address token purchaser
* @param _weiAmount uint256 amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
super._preValidatePurchase(_beneficiary, _weiAmount);
require(_weiAmount >= minInvestmentInWei);
require(invested[_beneficiary].add(_weiAmount) <= maxInvestmentInWei);
require(!paused);
}
/**
* @dev Update invested amount
* @param _beneficiary address receiving the tokens
* @param _weiAmount uint256 value in wei involved in the purchase
*/
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal {
super._updatePurchasingState(_beneficiary, _weiAmount);
invested[_beneficiary] = invested[_beneficiary].add(_weiAmount);
}
/**
* @dev Perform crowdsale finalization.
* - Finish token minting
* - Enable transfers
* - Give back the token ownership to the admin
*/
function finalization() internal {
CoinolixToken clxToken = CoinolixToken(token);
clxToken.finishMinting();
clxToken.unpause();
super.finalization();
transferTokenOwnership(owner);
reffalPool.transferOwnership(owner);
pvt_inv_Pool.transferOwnership(owner);
}
}
// File: contracts\CoinolixPresale.sol
/**
* @title Coinolix icoPresale Contract
* @dev Coinolix icoPresale Contract
* The contract is for the private sale of the Coinolix icotoken. It is:
* - With a hard cap in ETH
* - Limited in time (start/end date)
* - Only for whitelisted participants to purchase tokens
* - Tokens are minted on each purchase
*/
contract CoinolixPresale is
AirdropAndAffiliateCrowdsale,
//MintedCrowdsale,
CappedCrowdsale,
TimedCrowdsale,
WhitelistedCrowdsale {
using SafeMath for uint256;
// Min investment
uint256 public presaleRate;
uint256 public minInvestmentInWei;
event CurrentRateChange(uint256 rate);
// Investments
mapping (address => uint256) internal invested;
/**
* @dev Contract constructor
* @param _cap uint256 hard cap of the crowdsale
* @param _openingTime uint256 crowdsale start date/time
* @param _closingTime uint256 crowdsale end date/time
* @param _rate uint256 initial rate CLX for 1 ETH
* @param _wallet address address where the collected funds will be transferred
* @param _token CoinolixToken our token
*/
constructor(
uint256 _cap,
uint256 _openingTime,
uint256 _closingTime,
uint256 _rate,
uint256 _minInvestmentInWei,
address _wallet,
CoinolixToken _token,
uint256 _valueAirDrop,
uint256 _referrerBonus1,
uint256 _referrerBonus2)
Crowdsale(_rate, _wallet, _token)
AirdropAndAffiliateCrowdsale(_valueAirDrop, _referrerBonus1, _referrerBonus2)
CappedCrowdsale(_cap)
TimedCrowdsale(_openingTime, _closingTime) public {
minInvestmentInWei = _minInvestmentInWei;
presaleRate = _rate;
}
//update rate function by owner to keep stable rate in USD
function updatepresaleRate(uint256 _rate) external onlyOwner {
presaleRate = _rate;
rate = presaleRate;
}
/**
* @dev Validate min investment amount
* @param _beneficiary address token purchaser
* @param _weiAmount uint256 amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
super._preValidatePurchase(_beneficiary, _weiAmount);
require(_weiAmount >= minInvestmentInWei);
}
/**
* @dev Transfer the ownership of the token conctract
* @param _newOwner address the new owner of the token
*/
function transferTokenOwnership(address _newOwner) onlyOwner public {
Ownable(token).transferOwnership(_newOwner);
}
} | * @dev Transfer tokens to advisors and private investor from the pool @param _beneficiaries address[] list of beneficiaries @param _amounts uint256[] amounts/ | function allocatePVT_InvTokens(address[] _beneficiaries, uint256[] _amounts) external onlyOwner {
PausableToken(token).unpause();
pvt_inv_Pool.allocate(_beneficiaries, _amounts);
PausableToken(token).pause();
}
| 919,050 | [
1,
5912,
2430,
358,
1261,
3516,
1383,
471,
3238,
2198,
395,
280,
628,
326,
225,
2845,
225,
389,
70,
4009,
74,
14463,
5646,
1758,
8526,
666,
434,
27641,
74,
14463,
5646,
225,
389,
8949,
87,
2254,
5034,
8526,
30980,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
10101,
30201,
56,
67,
3605,
5157,
12,
2867,
8526,
389,
70,
4009,
74,
14463,
5646,
16,
2254,
5034,
8526,
389,
8949,
87,
13,
3903,
1338,
5541,
288,
203,
3639,
21800,
16665,
1345,
12,
2316,
2934,
318,
19476,
5621,
203,
3639,
9770,
88,
67,
5768,
67,
2864,
18,
16247,
24899,
70,
4009,
74,
14463,
5646,
16,
389,
8949,
87,
1769,
203,
3639,
21800,
16665,
1345,
12,
2316,
2934,
19476,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2020-08-11
*/
pragma solidity 0.6.0;
/**
* @title Offering contract
* @dev Offering logic and mining logic
*/
contract Nest_NToken_OfferMain {
using SafeMath for uint256;
using address_make_payable for address;
using SafeERC20 for ERC20;
// Offering data structure
struct Nest_NToken_OfferPriceData {
// The unique identifier is determined by the position of the offer in the array, and is converted to each other through a fixed algorithm (toindex(), toaddress())
address owner; // Offering owner
bool deviate; // Whether it deviates
address tokenAddress; // The erc20 contract address of the target offer token
uint256 ethAmount; // The ETH amount in the offer list
uint256 tokenAmount; // The token amount in the offer list
uint256 dealEthAmount; // The remaining number of tradable ETH
uint256 dealTokenAmount; // The remaining number of tradable tokens
uint256 blockNum; // The block number where the offer is located
uint256 serviceCharge; // The fee for mining
// Determine whether the asset has been collected by judging that ethamount, tokenamount, and servicecharge are all 0
}
Nest_NToken_OfferPriceData [] _prices; // Array used to save offers
Nest_3_VoteFactory _voteFactory; // Voting contract
Nest_3_OfferPrice _offerPrice; // Price contract
Nest_NToken_TokenMapping _tokenMapping; // NToken mapping contract
ERC20 _nestToken; // nestToken
Nest_3_Abonus _abonus; // Bonus pool
uint256 _miningETH = 10; // Offering mining fee ratio
uint256 _tranEth = 1; // Taker fee ratio
uint256 _tranAddition = 2; // Additional transaction multiple
uint256 _leastEth = 10 ether; // Minimum offer of ETH
uint256 _offerSpan = 10 ether; // ETH Offering span
uint256 _deviate = 10; // Price deviation - 10%
uint256 _deviationFromScale = 10; // Deviation from asset scale
uint256 _ownerMining = 5; // Creator ratio
uint256 _afterMiningAmount = 0.4 ether; // Stable period mining amount
uint32 _blockLimit = 25; // Block interval upper limit
uint256 _blockAttenuation = 2400000; // Block decay interval
mapping(uint256 => mapping(address => uint256)) _blockOfferAmount; // Block offer times - block number=>token address=>offer fee
mapping(uint256 => mapping(address => uint256)) _blockMining; // Offering block mining amount - block number=>token address=>mining amount
uint256[10] _attenuationAmount; // Mining decay list
// Log token contract address
event OfferTokenContractAddress(address contractAddress);
// Log offering contract, token address, amount of ETH, amount of ERC20, delayed block, mining fee
event OfferContractAddress(address contractAddress, address tokenAddress, uint256 ethAmount, uint256 erc20Amount, uint256 continued,uint256 mining);
// Log transaction sender, transaction token, transaction amount, purchase token address, purchase token amount, transaction offering contract address, transaction user address
event OfferTran(address tranSender, address tranToken, uint256 tranAmount,address otherToken, uint256 otherAmount, address tradedContract, address tradedOwner);
// Log current block, current block mined amount, token address
event OreDrawingLog(uint256 nowBlock, uint256 blockAmount, address tokenAddress);
// Log offering block, token address, token offered times
event MiningLog(uint256 blockNum, address tokenAddress, uint256 offerTimes);
/**
* Initialization method
* @param voteFactory Voting contract address
**/
constructor (address voteFactory) public {
Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory));
_voteFactory = voteFactoryMap;
_offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice")));
_nestToken = ERC20(voteFactoryMap.checkAddress("nest"));
_abonus = Nest_3_Abonus(voteFactoryMap.checkAddress("nest.v3.abonus"));
_tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.checkAddress("nest.nToken.tokenMapping")));
uint256 blockAmount = 4 ether;
for (uint256 i = 0; i < 10; i ++) {
_attenuationAmount[i] = blockAmount;
blockAmount = blockAmount.mul(8).div(10);
}
}
/**
* Reset voting contract method
* @param voteFactory Voting contract address
**/
function changeMapping(address voteFactory) public onlyOwner {
Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory));
_voteFactory = voteFactoryMap;
_offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice")));
_nestToken = ERC20(voteFactoryMap.checkAddress("nest"));
_abonus = Nest_3_Abonus(voteFactoryMap.checkAddress("nest.v3.abonus"));
_tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.checkAddress("nest.nToken.tokenMapping")));
}
/**
* Offering method
* @param ethAmount ETH amount
* @param erc20Amount Erc20 token amount
* @param erc20Address Erc20 token address
**/
function offer(uint256 ethAmount, uint256 erc20Amount, address erc20Address) public payable {
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
address nTokenAddress = _tokenMapping.checkTokenMapping(erc20Address);
require(nTokenAddress != address(0x0));
// Judge whether the price deviates
uint256 ethMining;
bool isDeviate = comparativePrice(ethAmount,erc20Amount,erc20Address);
if (isDeviate) {
require(ethAmount >= _leastEth.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of the minimum scale");
ethMining = _leastEth.mul(_miningETH).div(1000);
} else {
ethMining = ethAmount.mul(_miningETH).div(1000);
}
require(msg.value >= ethAmount.add(ethMining), "msg.value needs to be equal to the quoted eth quantity plus Mining handling fee");
uint256 subValue = msg.value.sub(ethAmount.add(ethMining));
if (subValue > 0) {
repayEth(address(msg.sender), subValue);
}
// Create an offer
createOffer(ethAmount, erc20Amount, erc20Address,isDeviate, ethMining);
// Transfer in offer asset - erc20 to this contract
ERC20(erc20Address).safeTransferFrom(address(msg.sender), address(this), erc20Amount);
_abonus.switchToEthForNTokenOffer.value(ethMining)(nTokenAddress);
// Mining
if (_blockOfferAmount[block.number][erc20Address] == 0) {
uint256 miningAmount = oreDrawing(nTokenAddress);
Nest_NToken nToken = Nest_NToken(nTokenAddress);
nToken.transfer(nToken.checkBidder(), miningAmount.mul(_ownerMining).div(100));
_blockMining[block.number][erc20Address] = miningAmount.sub(miningAmount.mul(_ownerMining).div(100));
}
_blockOfferAmount[block.number][erc20Address] = _blockOfferAmount[block.number][erc20Address].add(ethMining);
}
/**
* @dev Create offer
* @param ethAmount Offering ETH amount
* @param erc20Amount Offering erc20 amount
* @param erc20Address Offering erc20 address
**/
function createOffer(uint256 ethAmount, uint256 erc20Amount, address erc20Address, bool isDeviate, uint256 mining) private {
// Check offer conditions
require(ethAmount >= _leastEth, "Eth scale is smaller than the minimum scale");
require(ethAmount % _offerSpan == 0, "Non compliant asset span");
require(erc20Amount % (ethAmount.div(_offerSpan)) == 0, "Asset quantity is not divided");
require(erc20Amount > 0);
// Create offering contract
emit OfferContractAddress(toAddress(_prices.length), address(erc20Address), ethAmount, erc20Amount,_blockLimit,mining);
_prices.push(Nest_NToken_OfferPriceData(
msg.sender,
isDeviate,
erc20Address,
ethAmount,
erc20Amount,
ethAmount,
erc20Amount,
block.number,
mining
));
// Record price
_offerPrice.addPrice(ethAmount, erc20Amount, block.number.add(_blockLimit), erc20Address, address(msg.sender));
}
// Convert offer address into index in offer array
function toIndex(address contractAddress) public pure returns(uint256) {
return uint256(contractAddress);
}
// Convert index in offer array into offer address
function toAddress(uint256 index) public pure returns(address) {
return address(index);
}
/**
* Withdraw offer assets
* @param contractAddress Offer address
**/
function turnOut(address contractAddress) public {
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
uint256 index = toIndex(contractAddress);
Nest_NToken_OfferPriceData storage offerPriceData = _prices[index];
require(checkContractState(offerPriceData.blockNum) == 1, "Offer status error");
// Withdraw ETH
if (offerPriceData.ethAmount > 0) {
uint256 payEth = offerPriceData.ethAmount;
offerPriceData.ethAmount = 0;
repayEth(offerPriceData.owner, payEth);
}
// Withdraw erc20
if (offerPriceData.tokenAmount > 0) {
uint256 payErc = offerPriceData.tokenAmount;
offerPriceData.tokenAmount = 0;
ERC20(address(offerPriceData.tokenAddress)).safeTransfer(address(offerPriceData.owner), payErc);
}
// Mining settlement
if (offerPriceData.serviceCharge > 0) {
mining(offerPriceData.blockNum, offerPriceData.tokenAddress, offerPriceData.serviceCharge, offerPriceData.owner);
offerPriceData.serviceCharge = 0;
}
}
/**
* @dev Taker order - pay ETH and buy erc20
* @param ethAmount The amount of ETH of this offer
* @param tokenAmount The amount of erc20 of this offer
* @param contractAddress The target offer address
* @param tranEthAmount The amount of ETH of taker order
* @param tranTokenAmount The amount of erc20 of taker order
* @param tranTokenAddress The erc20 address of taker order
*/
function sendEthBuyErc(uint256 ethAmount, uint256 tokenAmount, address contractAddress, uint256 tranEthAmount, uint256 tranTokenAmount, address tranTokenAddress) public payable {
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
uint256 serviceCharge = tranEthAmount.mul(_tranEth).div(1000);
require(msg.value == ethAmount.add(tranEthAmount).add(serviceCharge), "msg.value needs to be equal to the quotation eth quantity plus transaction eth plus");
require(tranEthAmount % _offerSpan == 0, "Transaction size does not meet asset span");
// Get the offer data structure
uint256 index = toIndex(contractAddress);
Nest_NToken_OfferPriceData memory offerPriceData = _prices[index];
// Check the price, compare the current offer to the last effective price
bool thisDeviate = comparativePrice(ethAmount,tokenAmount,tranTokenAddress);
bool isDeviate;
if (offerPriceData.deviate == true) {
isDeviate = true;
} else {
isDeviate = thisDeviate;
}
// Limit the taker order only be twice the amount of the offer to prevent large-amount attacks
if (offerPriceData.deviate) {
// The taker order deviates x2
require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale");
} else {
if (isDeviate) {
// If the taken offer is normal and the taker order deviates x10
require(ethAmount >= tranEthAmount.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of transaction scale");
} else {
// If the taken offer is normal and the taker order is normal x2
require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale");
}
}
// Check whether the conditions for taker order are satisfied
require(checkContractState(offerPriceData.blockNum) == 0, "Offer status error");
require(offerPriceData.dealEthAmount >= tranEthAmount, "Insufficient trading eth");
require(offerPriceData.dealTokenAmount >= tranTokenAmount, "Insufficient trading token");
require(offerPriceData.tokenAddress == tranTokenAddress, "Wrong token address");
require(tranTokenAmount == offerPriceData.dealTokenAmount * tranEthAmount / offerPriceData.dealEthAmount, "Wrong token amount");
// Update the offer information
offerPriceData.ethAmount = offerPriceData.ethAmount.add(tranEthAmount);
offerPriceData.tokenAmount = offerPriceData.tokenAmount.sub(tranTokenAmount);
offerPriceData.dealEthAmount = offerPriceData.dealEthAmount.sub(tranEthAmount);
offerPriceData.dealTokenAmount = offerPriceData.dealTokenAmount.sub(tranTokenAmount);
_prices[index] = offerPriceData;
// Create a new offer
createOffer(ethAmount, tokenAmount, tranTokenAddress, isDeviate, 0);
// Transfer in erc20 + offer asset to this contract
if (tokenAmount > tranTokenAmount) {
ERC20(tranTokenAddress).safeTransferFrom(address(msg.sender), address(this), tokenAmount.sub(tranTokenAmount));
} else {
ERC20(tranTokenAddress).safeTransfer(address(msg.sender), tranTokenAmount.sub(tokenAmount));
}
// Modify price
_offerPrice.changePrice(tranEthAmount, tranTokenAmount, tranTokenAddress, offerPriceData.blockNum.add(_blockLimit));
emit OfferTran(address(msg.sender), address(0x0), tranEthAmount, address(tranTokenAddress), tranTokenAmount, contractAddress, offerPriceData.owner);
// Transfer fee
if (serviceCharge > 0) {
address nTokenAddress = _tokenMapping.checkTokenMapping(tranTokenAddress);
_abonus.switchToEth.value(serviceCharge)(nTokenAddress);
}
}
/**
* @dev Taker order - pay erc20 and buy ETH
* @param ethAmount The amount of ETH of this offer
* @param tokenAmount The amount of erc20 of this offer
* @param contractAddress The target offer address
* @param tranEthAmount The amount of ETH of taker order
* @param tranTokenAmount The amount of erc20 of taker order
* @param tranTokenAddress The erc20 address of taker order
*/
function sendErcBuyEth(uint256 ethAmount, uint256 tokenAmount, address contractAddress, uint256 tranEthAmount, uint256 tranTokenAmount, address tranTokenAddress) public payable {
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
uint256 serviceCharge = tranEthAmount.mul(_tranEth).div(1000);
require(msg.value == ethAmount.sub(tranEthAmount).add(serviceCharge), "msg.value needs to be equal to the quoted eth quantity plus transaction handling fee");
require(tranEthAmount % _offerSpan == 0, "Transaction size does not meet asset span");
// Get the offer data structure
uint256 index = toIndex(contractAddress);
Nest_NToken_OfferPriceData memory offerPriceData = _prices[index];
// Check the price, compare the current offer to the last effective price
bool thisDeviate = comparativePrice(ethAmount,tokenAmount,tranTokenAddress);
bool isDeviate;
if (offerPriceData.deviate == true) {
isDeviate = true;
} else {
isDeviate = thisDeviate;
}
// Limit the taker order only be twice the amount of the offer to prevent large-amount attacks
if (offerPriceData.deviate) {
// The taker order deviates x2
require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale");
} else {
if (isDeviate) {
// If the taken offer is normal and the taker order deviates x10
require(ethAmount >= tranEthAmount.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of transaction scale");
} else {
// If the taken offer is normal and the taker order is normal x2
require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale");
}
}
// Check whether the conditions for taker order are satisfied
require(checkContractState(offerPriceData.blockNum) == 0, "Offer status error");
require(offerPriceData.dealEthAmount >= tranEthAmount, "Insufficient trading eth");
require(offerPriceData.dealTokenAmount >= tranTokenAmount, "Insufficient trading token");
require(offerPriceData.tokenAddress == tranTokenAddress, "Wrong token address");
require(tranTokenAmount == offerPriceData.dealTokenAmount * tranEthAmount / offerPriceData.dealEthAmount, "Wrong token amount");
// Update the offer information
offerPriceData.ethAmount = offerPriceData.ethAmount.sub(tranEthAmount);
offerPriceData.tokenAmount = offerPriceData.tokenAmount.add(tranTokenAmount);
offerPriceData.dealEthAmount = offerPriceData.dealEthAmount.sub(tranEthAmount);
offerPriceData.dealTokenAmount = offerPriceData.dealTokenAmount.sub(tranTokenAmount);
_prices[index] = offerPriceData;
// Create a new offer
createOffer(ethAmount, tokenAmount, tranTokenAddress, isDeviate, 0);
// Transfer in erc20 + offer asset to this contract
ERC20(tranTokenAddress).safeTransferFrom(address(msg.sender), address(this), tranTokenAmount.add(tokenAmount));
// Modify price
_offerPrice.changePrice(tranEthAmount, tranTokenAmount, tranTokenAddress, offerPriceData.blockNum.add(_blockLimit));
emit OfferTran(address(msg.sender), address(tranTokenAddress), tranTokenAmount, address(0x0), tranEthAmount, contractAddress, offerPriceData.owner);
// Transfer fee
if (serviceCharge > 0) {
address nTokenAddress = _tokenMapping.checkTokenMapping(tranTokenAddress);
_abonus.switchToEth.value(serviceCharge)(nTokenAddress);
}
}
/**
* Offering mining
* @param ntoken NToken address
**/
function oreDrawing(address ntoken) private returns(uint256) {
Nest_NToken miningToken = Nest_NToken(ntoken);
(uint256 createBlock, uint256 recentlyUsedBlock) = miningToken.checkBlockInfo();
uint256 attenuationPointNow = block.number.sub(createBlock).div(_blockAttenuation);
uint256 miningAmount = 0;
uint256 attenuation;
if (attenuationPointNow > 9) {
attenuation = _afterMiningAmount;
} else {
attenuation = _attenuationAmount[attenuationPointNow];
}
miningAmount = attenuation.mul(block.number.sub(recentlyUsedBlock));
miningToken.increaseTotal(miningAmount);
emit OreDrawingLog(block.number, miningAmount, ntoken);
return miningAmount;
}
/**
* Retrieve mining
* @param token Token address
**/
function mining(uint256 blockNum, address token, uint256 serviceCharge, address owner) private returns(uint256) {
// Block mining amount*offer fee/block offer fee
uint256 miningAmount = _blockMining[blockNum][token].mul(serviceCharge).div(_blockOfferAmount[blockNum][token]);
// Transfer NToken
Nest_NToken nToken = Nest_NToken(address(_tokenMapping.checkTokenMapping(token)));
require(nToken.transfer(address(owner), miningAmount), "Transfer failure");
emit MiningLog(blockNum, token,_blockOfferAmount[blockNum][token]);
return miningAmount;
}
// Compare order prices
function comparativePrice(uint256 myEthValue, uint256 myTokenValue, address token) private view returns(bool) {
(uint256 frontEthValue, uint256 frontTokenValue) = _offerPrice.updateAndCheckPricePrivate(token);
if (frontEthValue == 0 || frontTokenValue == 0) {
return false;
}
uint256 maxTokenAmount = myEthValue.mul(frontTokenValue).mul(uint256(100).add(_deviate)).div(frontEthValue.mul(100));
if (myTokenValue <= maxTokenAmount) {
uint256 minTokenAmount = myEthValue.mul(frontTokenValue).mul(uint256(100).sub(_deviate)).div(frontEthValue.mul(100));
if (myTokenValue >= minTokenAmount) {
return false;
}
}
return true;
}
// Check contract status
function checkContractState(uint256 createBlock) public view returns (uint256) {
if (block.number.sub(createBlock) > _blockLimit) {
return 1;
}
return 0;
}
// Transfer ETH
function repayEth(address accountAddress, uint256 asset) private {
address payable addr = accountAddress.make_payable();
addr.transfer(asset);
}
// View the upper limit of the block interval
function checkBlockLimit() public view returns(uint256) {
return _blockLimit;
}
// View taker fee ratio
function checkTranEth() public view returns (uint256) {
return _tranEth;
}
// View additional transaction multiple
function checkTranAddition() public view returns(uint256) {
return _tranAddition;
}
// View minimum offering ETH
function checkleastEth() public view returns(uint256) {
return _leastEth;
}
// View offering ETH span
function checkOfferSpan() public view returns(uint256) {
return _offerSpan;
}
// View block offering amount
function checkBlockOfferAmount(uint256 blockNum, address token) public view returns (uint256) {
return _blockOfferAmount[blockNum][token];
}
// View offering block mining amount
function checkBlockMining(uint256 blockNum, address token) public view returns (uint256) {
return _blockMining[blockNum][token];
}
// View offering mining amount
function checkOfferMining(uint256 blockNum, address token, uint256 serviceCharge) public view returns (uint256) {
if (serviceCharge == 0) {
return 0;
} else {
return _blockMining[blockNum][token].mul(serviceCharge).div(_blockOfferAmount[blockNum][token]);
}
}
// View the owner allocation ratio
function checkOwnerMining() public view returns(uint256) {
return _ownerMining;
}
// View the mining decay
function checkAttenuationAmount(uint256 num) public view returns(uint256) {
return _attenuationAmount[num];
}
// Modify taker order fee ratio
function changeTranEth(uint256 num) public onlyOwner {
_tranEth = num;
}
// Modify block interval upper limit
function changeBlockLimit(uint32 num) public onlyOwner {
_blockLimit = num;
}
// Modify additional transaction multiple
function changeTranAddition(uint256 num) public onlyOwner {
require(num > 0, "Parameter needs to be greater than 0");
_tranAddition = num;
}
// Modify minimum offering ETH
function changeLeastEth(uint256 num) public onlyOwner {
require(num > 0, "Parameter needs to be greater than 0");
_leastEth = num;
}
// Modify offering ETH span
function changeOfferSpan(uint256 num) public onlyOwner {
require(num > 0, "Parameter needs to be greater than 0");
_offerSpan = num;
}
// Modify price deviation
function changekDeviate(uint256 num) public onlyOwner {
_deviate = num;
}
// Modify the deviation from scale
function changeDeviationFromScale(uint256 num) public onlyOwner {
_deviationFromScale = num;
}
// Modify the owner allocation ratio
function changeOwnerMining(uint256 num) public onlyOwner {
_ownerMining = num;
}
// Modify the mining decay
function changeAttenuationAmount(uint256 firstAmount, uint256 top, uint256 bottom) public onlyOwner {
uint256 blockAmount = firstAmount;
for (uint256 i = 0; i < 10; i ++) {
_attenuationAmount[i] = blockAmount;
blockAmount = blockAmount.mul(top).div(bottom);
}
}
// Vote administrators only
modifier onlyOwner(){
require(_voteFactory.checkOwners(msg.sender), "No authority");
_;
}
/**
* Get the number of offers stored in the offer array
* @return The number of offers stored in the offer array
**/
function getPriceCount() view public returns (uint256) {
return _prices.length;
}
/**
* Get offer information according to the index
* @param priceIndex Offer index
* @return Offer information
**/
function getPrice(uint256 priceIndex) view public returns (string memory) {
// The buffer array used to generate the result string
bytes memory buf = new bytes(500000);
uint256 index = 0;
index = writeOfferPriceData(priceIndex, _prices[priceIndex], buf, index);
// Generate the result string and return
bytes memory str = new bytes(index);
while(index-- > 0) {
str[index] = buf[index];
}
return string(str);
}
/**
* Search the contract address list of the target account (reverse order)
* @param start Search forward from the index corresponding to the given contract address (not including the record corresponding to start address)
* @param count Maximum number of records to return
* @param maxFindCount The max index to search
* @param owner Target account address
* @return Separate the offer records with symbols. use , to divide fields:
* uuid,owner,tokenAddress,ethAmount,tokenAmount,dealEthAmount,dealTokenAmount,blockNum,serviceCharge
**/
function find(address start, uint256 count, uint256 maxFindCount, address owner) view public returns (string memory) {
// Buffer array used to generate result string
bytes memory buf = new bytes(500000);
uint256 index = 0;
// Calculate search interval i and end
uint256 i = _prices.length;
uint256 end = 0;
if (start != address(0)) {
i = toIndex(start);
}
if (i > maxFindCount) {
end = i - maxFindCount;
}
// Loop search, write qualified records into buffer
while (count > 0 && i-- > end) {
Nest_NToken_OfferPriceData memory price = _prices[i];
if (price.owner == owner) {
--count;
index = writeOfferPriceData(i, price, buf, index);
}
}
// Generate result string and return
bytes memory str = new bytes(index);
while(index-- > 0) {
str[index] = buf[index];
}
return string(str);
}
/**
* Get the list of offers by page
* @param offset Skip the first offset records
* @param count Maximum number of records to return
* @param order Sort rules. 0 means reverse order, non-zero means positive order
* @return Separate the offer records with symbols. use , to divide fields:
* uuid,owner,tokenAddress,ethAmount,tokenAmount,dealEthAmount,dealTokenAmount,blockNum,serviceCharge
**/
function list(uint256 offset, uint256 count, uint256 order) view public returns (string memory) {
// Buffer array used to generate result string
bytes memory buf = new bytes(500000);
uint256 index = 0;
// Find search interval i and end
uint256 i = 0;
uint256 end = 0;
if (order == 0) {
// Reverse order, in default
// Calculate search interval i and end
if (offset < _prices.length) {
i = _prices.length - offset;
}
if (count < i) {
end = i - count;
}
// Write records in the target interval into the buffer
while (i-- > end) {
index = writeOfferPriceData(i, _prices[i], buf, index);
}
} else {
// Ascending order
// Calculate the search interval i and end
if (offset < _prices.length) {
i = offset;
} else {
i = _prices.length;
}
end = i + count;
if(end > _prices.length) {
end = _prices.length;
}
// Write the records in the target interval into the buffer
while (i < end) {
index = writeOfferPriceData(i, _prices[i], buf, index);
++i;
}
}
// Generate the result string and return
bytes memory str = new bytes(index);
while(index-- > 0) {
str[index] = buf[index];
}
return string(str);
}
// Write the offer data into the buffer and return the buffer index
function writeOfferPriceData(uint256 priceIndex, Nest_NToken_OfferPriceData memory price, bytes memory buf, uint256 index) pure private returns (uint256) {
index = writeAddress(toAddress(priceIndex), buf, index);
buf[index++] = byte(uint8(44));
index = writeAddress(price.owner, buf, index);
buf[index++] = byte(uint8(44));
index = writeAddress(price.tokenAddress, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.ethAmount, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.tokenAmount, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.dealEthAmount, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.dealTokenAmount, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.blockNum, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.serviceCharge, buf, index);
buf[index++] = byte(uint8(44));
return index;
}
// Convert integer to string in decimal form, write the string into the buffer, and return the buffer index
function writeUInt(uint256 iv, bytes memory buf, uint256 index) pure public returns (uint256) {
uint256 i = index;
do {
buf[index++] = byte(uint8(iv % 10 +48));
iv /= 10;
} while (iv > 0);
for (uint256 j = index; j > i; ++i) {
byte t = buf[i];
buf[i] = buf[--j];
buf[j] = t;
}
return index;
}
// Convert the address to a hexadecimal string and write it into the buffer, and return the buffer index
function writeAddress(address addr, bytes memory buf, uint256 index) pure private returns (uint256) {
uint256 iv = uint256(addr);
uint256 i = index + 40;
do {
uint256 w = iv % 16;
if(w < 10) {
buf[index++] = byte(uint8(w +48));
} else {
buf[index++] = byte(uint8(w +87));
}
iv /= 16;
} while (index < i);
i -= 40;
for (uint256 j = index; j > i; ++i) {
byte t = buf[i];
buf[i] = buf[--j];
buf[j] = t;
}
return index;
}
}
// Price contract
interface Nest_3_OfferPrice {
// Add price data
function addPrice(uint256 ethAmount, uint256 tokenAmount, uint256 endBlock, address tokenAddress, address offerOwner) external;
// Modify price
function changePrice(uint256 ethAmount, uint256 tokenAmount, address tokenAddress, uint256 endBlock) external;
function updateAndCheckPricePrivate(address tokenAddress) external view returns(uint256 ethAmount, uint256 erc20Amount);
}
// Voting contract
interface Nest_3_VoteFactory {
// Check address
function checkAddress(string calldata name) external view returns (address contractAddress);
// Check whether an administrator
function checkOwners(address man) external view returns (bool);
}
// NToken contract
interface Nest_NToken {
// Additional issuance
function increaseTotal(uint256 value) external;
// Check mining information
function checkBlockInfo() external view returns(uint256 createBlock, uint256 recentlyUsedBlock);
// Check creator
function checkBidder() external view returns(address);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// NToken mapping contract
interface Nest_NToken_TokenMapping {
// Check token mapping
function checkTokenMapping(address token) external view returns (address);
}
// Bonus pool contract
interface Nest_3_Abonus {
function switchToEth(address token) external payable;
function switchToEthForNTokenOffer(address token) external payable;
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
library address_make_payable {
function make_payable(address x) internal pure returns (address payable) {
return address(uint160(x));
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(ERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(ERC20 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 safeIncreaseAllowance(ERC20 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(ERC20 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));
}
function callOptionalReturn(ERC20 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");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface ERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
} | Modify minimum offering ETH | function changeLeastEth(uint256 num) public onlyOwner {
require(num > 0, "Parameter needs to be greater than 0");
_leastEth = num;
}
| 7,993,999 | [
1,
11047,
5224,
10067,
310,
512,
2455,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
17319,
41,
451,
12,
11890,
5034,
818,
13,
1071,
1338,
5541,
288,
203,
3639,
2583,
12,
2107,
405,
374,
16,
315,
1662,
4260,
358,
506,
6802,
2353,
374,
8863,
203,
3639,
389,
16446,
41,
451,
273,
818,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-02-23
*/
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() public {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @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 Required interface of an ERC721 compliant contract.
*/
interface IERC721 {
/**
* @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;
/**
* @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);
}
interface IERC1155 {
// Events
/**
* @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning
* Operator MUST be msg.sender
* When minting/creating tokens, the `_from` field MUST be set to `0x0`
* When burning/destroying tokens, the `_to` field MUST be set to `0x0`
* The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID
* To broadcast the existence of a token ID with no initial balance, the contract SHOULD emit the TransferSingle event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0
*/
event TransferSingle(
address indexed _operator,
address indexed _from,
address indexed _to,
uint256 _id,
uint256 _amount
);
/**
* @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning
* Operator MUST be msg.sender
* When minting/creating tokens, the `_from` field MUST be set to `0x0`
* When burning/destroying tokens, the `_to` field MUST be set to `0x0`
* The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID
* To broadcast the existence of multiple token IDs with no initial balance, this SHOULD emit the TransferBatch event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0
*/
event TransferBatch(
address indexed _operator,
address indexed _from,
address indexed _to,
uint256[] _ids,
uint256[] _amounts
);
/**
* @dev MUST emit when an approval is updated
*/
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
/**
* @dev MUST emit when the URI is updated for a token ID
* URIs are defined in RFC 3986
* The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata JSON Schema"
*/
event URI(string _amount, uint256 indexed _id);
/**
* @notice Transfers amount of an _id from the _from address to the _to address specified
* @dev MUST emit TransferSingle event on success
* Caller must be approved to manage the _from account's tokens (see isApprovedForAll)
* MUST throw if `_to` is the zero address
* MUST throw if balance of sender for token `_id` is lower than the `_amount` sent
* MUST throw on any other error
* When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155Received` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _id,
uint256 _amount,
bytes calldata _data
) external;
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @dev MUST emit TransferBatch event on success
* Caller must be approved to manage the _from account's tokens (see isApprovedForAll)
* MUST throw if `_to` is the zero address
* MUST throw if length of `_ids` is not the same as length of `_amounts`
* MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_amounts` sent
* MUST throw on any other error
* When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* Transfers and events MUST occur in the array order they were submitted (_ids[0] before _ids[1], etc)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeBatchTransferFrom(
address _from,
address _to,
uint256[] calldata _ids,
uint256[] calldata _amounts,
bytes calldata _data
) external;
/**
* @notice Get the balance of an account's Tokens
* @param _owner The address of the token holder
* @param _id ID of the Token
* @return The _owner's balance of the Token type requested
*/
function balanceOf(address _owner, uint256 _id)
external
view
returns (uint256);
/**
* @notice Get the balance of multiple account/token pairs
* @param _owners The addresses of the token holders
* @param _ids ID of the Tokens
* @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids)
external
view
returns (uint256[] memory);
/**
* @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens
* @dev MUST emit the ApprovalForAll event on success
* @param _operator Address to add to the set of authorized operators
* @param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved) external;
/**
* @notice Queries the approval status of an operator for a given owner
* @param _owner The owner of the Tokens
* @param _operator Address of authorized operator
* @return True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator)
external
view
returns (bool);
}
interface IERC1155Metadata {
/***********************************|
| Metadata Public Function s |
|__________________________________*/
/**
* @notice A distinct Uniform Resource Identifier (URI) for a given token.
* @dev URIs are defined in RFC 3986.
* URIs are assumed to be deterministically generated based on token ID
* Token IDs are assumed to be represented in their hex format in URIs
* @return URI string
*/
function uri(uint256 _id) external view returns (string memory);
}
library Strings {
// via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol
function strConcat(
string memory _a,
string memory _b,
string memory _c,
string memory _d,
string memory _e
) internal pure returns (string memory) {
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);
uint256 k = 0;
for (uint256 i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (uint256 i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (uint256 i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (uint256 i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (uint256 i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(
string memory _a,
string memory _b,
string memory _c,
string memory _d
) internal pure returns (string memory) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(
string memory _a,
string memory _b,
string memory _c
) internal pure returns (string memory) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string memory _a, string memory _b)
internal
pure
returns (string memory)
{
return strConcat(_a, _b, "", "", "");
}
function uint2str(uint256 _i)
internal
pure
returns (string memory _uintAsString)
{
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len - 1;
while (_i != 0) {
bstr[k--] = bytes1(uint8(48 + (_i % 10)));
_i /= 10;
}
return string(bstr);
}
}
/**
* @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, "SafeMath#mul: OVERFLOW");
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, "SafeMath#div: 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 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, "SafeMath#sub: UNDERFLOW");
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, "SafeMath#add: OVERFLOW");
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, "SafeMath#mod: DIVISION_BY_ZERO");
return a % b;
}
}
/**
* Copyright 2018 ZeroEx Intl.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* 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) {
bytes32 codehash;
bytes32 accountHash =
0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// 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.
assembly {
codehash := extcodehash(account)
}
return (codehash != 0x0 && codehash != accountHash);
}
}
// SPDX-License-Identifier: MIT
/////////////////////////////////////////////////
// ____ _ _ //
// | __ ) ___ _ __ __| | | | _ _ //
// | _ \ / _ \ | '_ \ / _` | | | | | | | //
// | |_) | | (_) | | | | | | (_| | | | | |_| | //
// |____/ \___/ |_| |_| \__,_| |_| \__, | //
// |___/ //
/////////////////////////////////////////////////
contract BondlySwap is Ownable {
using Strings for string;
using SafeMath for uint256;
using Address for address;
// TokenType Definition
enum TokenType {T20, T1155, T721}
// SwapType Definition
enum SwapType {TimedSwap, FixedSwap}
struct Collection {
address[] cardContractAddrs;
uint256[] cardTokenIds; // amount for T20
TokenType[] tokenTypes;
uint256 nLength;
address collectionOwner;
}
struct BSwap {
uint256 totalAmount;
uint256 currentAmount;
Collection maker;
bool isPrivate;
uint256 startTime;
uint256 endTime;
bool isActive;
SwapType swapType;
Collection target;
uint256 nAllowedBiddersLength;
mapping(address => bool) allowedBidders;
}
mapping(uint256 => BSwap) private listings;
uint256 public listIndex;
uint256 public platformFee;
address payable public feeCollector;
uint256 public t20Fee;
address private originCreator;
// apply 0 fee to our NFTs
mapping(address => bool) public whitelist;
mapping(address => bool) public supportTokens;
bool private emergencyStop;
event AddedNewToken(address indexed tokenAddress);
event BatchAddedNewToken(address[] tokenAddress);
event NFTListed(uint256 listId, address indexed lister);
event ListVisibilityChanged(uint256 listId, bool isPrivate);
event ListEndTimeChanged(uint256 listId, uint256 endTime);
event NFTSwapped(uint256 listId, address indexed buyer, uint256 count);
event NFTClosed(uint256 listId, address indexed closer);
event WhiteListAdded(address indexed addr);
event WhiteListRemoved(address indexed addr);
event BatchWhiteListAdded(address[] addr);
event BatchWhiteListRemoved(address[] addr);
constructor() public {
originCreator = msg.sender;
emergencyStop = false;
listIndex = 0;
platformFee = 1;
feeCollector = msg.sender;
t20Fee = 5;
}
modifier onlyNotEmergency() {
require(emergencyStop == false, "BSwap: emergency stop");
_;
}
modifier onlyValidList(uint256 listId) {
require(listIndex >= listId, "Bswap: list not found");
_;
}
modifier onlyListOwner(uint256 listId) {
require(
listings[listId].maker.collectionOwner == msg.sender || isOwner(),
"Bswap: not your list"
);
_;
}
function _addNewToken(address contractAddr)
public
onlyOwner
returns (bool)
{
require(
supportTokens[contractAddr] == false,
"BSwap: already supported"
);
supportTokens[contractAddr] = true;
emit AddedNewToken(contractAddr);
return true;
}
function _batchAddNewToken(address[] memory contractAddrs)
public
onlyOwner
returns (bool)
{
for (uint256 i = 0; i < contractAddrs.length; i++) {
require(
supportTokens[contractAddrs[i]] == false,
"BSwap: already supported"
);
supportTokens[contractAddrs[i]] = true;
}
emit BatchAddedNewToken(contractAddrs);
return true;
}
function _sendToken(
TokenType tokenType,
address contractAddr,
uint256 tokenId,
address from,
address to
) internal {
if (tokenType == TokenType.T1155) {
IERC1155(contractAddr).safeTransferFrom(from, to, tokenId, 1, "");
} else if (tokenType == TokenType.T721) {
IERC721(contractAddr).safeTransferFrom(from, to, tokenId, "");
} else {
IERC20(contractAddr).transferFrom(from, to, tokenId);
}
}
function createSwap(
uint256[] memory arrTokenTypes,
address[] memory arrContractAddr,
uint256[] memory arrTokenIds,
uint256 swapType,
uint256 endTime,
bool _isPrivate,
address[] memory bidders,
uint256 batchCount
) public payable onlyNotEmergency {
bool isWhitelisted = false;
require(
arrContractAddr.length == arrTokenIds.length &&
arrTokenIds.length == arrTokenTypes.length,
"BSwap: array lengths are different"
);
require(
arrContractAddr.length > 1,
"BSwap: expected more than 1 desire"
);
require(batchCount >= 1, "BSwap: expected more than 1 count");
for (uint256 i = 0; i < arrTokenTypes.length; i++) {
require(
supportTokens[arrContractAddr[i]] == true,
"BSwap: not supported"
);
if (isWhitelisted == false) {
isWhitelisted = whitelist[arrContractAddr[i]];
}
if (i == 0) {
if (arrTokenTypes[i] == uint256(TokenType.T1155)) {
IERC1155 _t1155Contract = IERC1155(arrContractAddr[i]);
require(
_t1155Contract.balanceOf(msg.sender, arrTokenIds[i]) >=
batchCount,
"BSwap: Do not have nft"
);
require(
_t1155Contract.isApprovedForAll(
msg.sender,
address(this)
) == true,
"BSwap: Must be approved"
);
} else if (arrTokenTypes[i] == uint256(TokenType.T721)) {
IERC721 _t721Contract = IERC721(arrContractAddr[i]);
require(
_t721Contract.ownerOf(arrTokenIds[i]) == msg.sender,
"BSwap: Do not have nft"
);
require(
batchCount == 1,
"BSwap: Don't support T721 Batch Swap"
);
require(
_t721Contract.isApprovedForAll(
msg.sender,
address(this)
) == true,
"BSwap: Must be approved"
);
}
}
}
if (isWhitelisted == false) {
uint256 _fee = msg.value;
require(_fee >= platformFee.mul(10**16), "BSwap: out of fee");
feeCollector.transfer(_fee);
}
address _makerContract = arrContractAddr[0];
uint256 _makerTokenId = arrTokenIds[0];
TokenType _makerTokenType = TokenType(arrTokenTypes[0]);
// maker config
Collection memory _maker;
_maker.nLength = 1;
_maker.collectionOwner = msg.sender;
_maker.cardContractAddrs = new address[](1);
_maker.cardTokenIds = new uint256[](1);
_maker.tokenTypes = new TokenType[](1);
_maker.cardContractAddrs[0] = _makerContract;
_maker.cardTokenIds[0] = _makerTokenId;
_maker.tokenTypes[0] = _makerTokenType;
// target config
Collection memory _target;
uint256 _targetLength = arrTokenTypes.length - 1;
_target.nLength = _targetLength;
_target.collectionOwner = address(0);
_target.cardContractAddrs = new address[](_targetLength);
_target.cardTokenIds = new uint256[](_targetLength);
_target.tokenTypes = new TokenType[](_targetLength);
for (uint256 i = 0; i < _targetLength; i++) {
_target.cardContractAddrs[i] = arrContractAddr[i + 1];
_target.cardTokenIds[i] = arrTokenIds[i + 1];
_target.tokenTypes[i] = TokenType(arrTokenTypes[i + 1]);
}
uint256 _id = _getNextListID();
_incrementListId();
BSwap storage list = listings[_id];
list.totalAmount = batchCount;
list.currentAmount = batchCount;
list.maker = _maker;
list.target = _target;
list.isPrivate = _isPrivate;
list.startTime = block.timestamp;
list.endTime = block.timestamp + endTime;
list.isActive = true;
list.swapType = SwapType(swapType);
list.nAllowedBiddersLength = bidders.length;
for (uint256 i = 0; i < bidders.length; i++) {
list.allowedBidders[bidders[i]] = true;
}
emit NFTListed(_id, msg.sender);
}
function swapNFT(uint256 listId, uint256 batchCount)
public
payable
onlyValidList(listId)
onlyNotEmergency
{
require(batchCount >= 1, "BSwap: expected more than 1 count");
// maker config
BSwap storage list = listings[listId];
Collection memory _target = list.target;
Collection memory _maker = list.maker;
address lister = _maker.collectionOwner;
bool isWhitelisted = false;
require(
list.isActive == true && list.currentAmount > 0,
"BSwap: list is closed"
);
require(
list.currentAmount >= batchCount,
"BSwap: exceed current supply"
);
require(
list.swapType == SwapType.FixedSwap ||
list.endTime > block.timestamp,
"BSwap: time is over"
);
require(
list.isPrivate == false || list.allowedBidders[msg.sender] == true,
"Bswap: not whiltelisted"
);
for (uint256 i = 0; i < _target.tokenTypes.length; i++) {
if (isWhitelisted == false) {
isWhitelisted = whitelist[_target.cardContractAddrs[i]];
}
if (_target.tokenTypes[i] == TokenType.T1155) {
IERC1155 _t1155Contract =
IERC1155(_target.cardContractAddrs[i]);
require(
_t1155Contract.balanceOf(
msg.sender,
_target.cardTokenIds[i]
) > 0,
"BSwap: Do not have nft"
);
require(
_t1155Contract.isApprovedForAll(
msg.sender,
address(this)
) == true,
"BSwap: Must be approved"
);
_t1155Contract.safeTransferFrom(
msg.sender,
lister,
_target.cardTokenIds[i],
batchCount,
""
);
} else if (_target.tokenTypes[i] == TokenType.T721) {
IERC721 _t721Contract = IERC721(_target.cardContractAddrs[i]);
require(
batchCount == 1,
"BSwap: Don't support T721 Batch Swap"
);
require(
_t721Contract.ownerOf(_target.cardTokenIds[i]) ==
msg.sender,
"BSwap: Do not have nft"
);
require(
_t721Contract.isApprovedForAll(msg.sender, address(this)) ==
true,
"BSwap: Must be approved"
);
_t721Contract.safeTransferFrom(
msg.sender,
lister,
_target.cardTokenIds[i],
""
);
} else {
IERC20 _t20Contract = IERC20(_target.cardContractAddrs[i]);
uint256 tokenAmount = _target.cardTokenIds[i].mul(batchCount);
require(
_t20Contract.balanceOf(msg.sender) >= tokenAmount,
"BSwap: Do not enough funds"
);
require(
_t20Contract.allowance(msg.sender, address(this)) >=
tokenAmount,
"BSwap: Must be approved"
);
// T20 fee
uint256 amountToPlatform = tokenAmount.mul(t20Fee).div(100);
uint256 amountToLister = tokenAmount.sub(amountToPlatform);
_t20Contract.transferFrom(
msg.sender,
feeCollector,
amountToPlatform
);
_t20Contract.transferFrom(msg.sender, lister, amountToLister);
}
}
if (isWhitelisted == false) {
isWhitelisted = whitelist[_maker.cardContractAddrs[0]];
}
if (isWhitelisted == false) {
uint256 _fee = msg.value;
require(_fee >= platformFee.mul(10**16), "BSwap: out of fee");
feeCollector.transfer(_fee);
}
_sendToken(
_maker.tokenTypes[0],
_maker.cardContractAddrs[0],
_maker.cardTokenIds[0],
lister,
msg.sender
);
list.currentAmount = list.currentAmount.sub(batchCount);
if (list.currentAmount == 0) {
list.isActive = false;
}
emit NFTSwapped(listId, msg.sender, batchCount);
}
function closeList(uint256 listId)
public
onlyValidList(listId)
onlyListOwner(listId)
returns (bool)
{
BSwap storage list = listings[listId];
list.isActive = false;
emit NFTClosed(listId, msg.sender);
return true;
}
function setVisibility(uint256 listId, bool _isPrivate)
public
onlyValidList(listId)
onlyListOwner(listId)
returns (bool)
{
BSwap storage list = listings[listId];
list.isPrivate = _isPrivate;
emit ListVisibilityChanged(listId, _isPrivate);
return true;
}
function increaseEndTime(uint256 listId, uint256 amount)
public
onlyValidList(listId)
onlyListOwner(listId)
returns (bool)
{
BSwap storage list = listings[listId];
list.endTime = list.endTime.add(amount);
emit ListEndTimeChanged(listId, list.endTime);
return true;
}
function decreaseEndTime(uint256 listId, uint256 amount)
public
onlyValidList(listId)
onlyListOwner(listId)
returns (bool)
{
BSwap storage list = listings[listId];
require(
list.endTime.sub(amount) > block.timestamp,
"BSwap: can't revert time"
);
list.endTime = list.endTime.sub(amount);
emit ListEndTimeChanged(listId, list.endTime);
return true;
}
function addWhiteListAddress(address addr) public onlyOwner returns (bool) {
whitelist[addr] = true;
emit WhiteListAdded(addr);
return true;
}
function batchAddWhiteListAddress(address[] memory addr)
public
onlyOwner
returns (bool)
{
for (uint256 i = 0; i < addr.length; i++) {
whitelist[addr[i]] = true;
}
emit BatchWhiteListAdded(addr);
return true;
}
function removeWhiteListAddress(address addr)
public
onlyOwner
returns (bool)
{
whitelist[addr] = false;
emit WhiteListRemoved(addr);
return true;
}
function batchRemoveWhiteListAddress(address[] memory addr)
public
onlyOwner
returns (bool)
{
for (uint256 i = 0; i < addr.length; i++) {
whitelist[addr[i]] = false;
}
emit BatchWhiteListRemoved(addr);
return true;
}
function _setPlatformFee(uint256 _fee) public onlyOwner returns (uint256) {
platformFee = _fee;
return platformFee;
}
function _setFeeCollector(address payable addr)
public
onlyOwner
returns (bool)
{
feeCollector = addr;
return true;
}
function _setT20Fee(uint256 _fee) public onlyOwner returns (uint256) {
t20Fee = _fee;
return t20Fee;
}
function getOfferingTokens(uint256 listId)
public
view
onlyValidList(listId)
returns (
TokenType[] memory,
address[] memory,
uint256[] memory
)
{
BSwap storage list = listings[listId];
Collection memory maker = list.maker;
address[] memory cardContractAddrs =
new address[](maker.cardContractAddrs.length);
TokenType[] memory tokenTypes =
new TokenType[](maker.tokenTypes.length);
uint256[] memory cardTokenIds =
new uint256[](maker.cardTokenIds.length);
for (uint256 i = 0; i < maker.cardContractAddrs.length; i++) {
cardContractAddrs[i] = maker.cardContractAddrs[i];
tokenTypes[i] = maker.tokenTypes[i];
cardTokenIds[i] = maker.cardTokenIds[i];
}
return (tokenTypes, cardContractAddrs, cardTokenIds);
}
function getDesiredTokens(uint256 listId)
public
view
onlyValidList(listId)
returns (
TokenType[] memory,
address[] memory,
uint256[] memory
)
{
BSwap storage list = listings[listId];
Collection memory target = list.target;
address[] memory cardContractAddrs =
new address[](target.cardContractAddrs.length);
TokenType[] memory tokenTypes =
new TokenType[](target.tokenTypes.length);
uint256[] memory cardTokenIds =
new uint256[](target.cardTokenIds.length);
for (uint256 i = 0; i < target.cardContractAddrs.length; i++) {
cardContractAddrs[i] = target.cardContractAddrs[i];
tokenTypes[i] = target.tokenTypes[i];
cardTokenIds[i] = target.cardTokenIds[i];
}
return (tokenTypes, cardContractAddrs, cardTokenIds);
}
function isAvailable(uint256 listId)
public
view
onlyValidList(listId)
returns (bool)
{
BSwap storage list = listings[listId];
Collection memory maker = list.maker;
address lister = maker.collectionOwner;
for (uint256 i = 0; i < maker.cardContractAddrs.length; i++) {
if (maker.tokenTypes[i] == TokenType.T1155) {
IERC1155 _t1155Contract = IERC1155(maker.cardContractAddrs[i]);
if (
_t1155Contract.balanceOf(lister, maker.cardTokenIds[i]) == 0
) {
return false;
}
} else if (maker.tokenTypes[i] == TokenType.T721) {
IERC721 _t721Contract = IERC721(maker.cardContractAddrs[i]);
if (_t721Contract.ownerOf(maker.cardTokenIds[i]) != lister) {
return false;
}
}
}
return true;
}
function isWhitelistedToken(address addr)
public
view
returns (bool)
{
return whitelist[addr];
}
function isSupportedToken(address addr)
public
view
returns (bool)
{
return supportTokens[addr];
}
function isAcive(uint256 listId)
public
view
onlyValidList(listId)
returns (bool)
{
BSwap memory list = listings[listId];
return
list.isActive &&
(list.swapType == SwapType.FixedSwap ||
list.endTime > block.timestamp);
}
function isPrivate(uint256 listId)
public
view
onlyValidList(listId)
returns (bool)
{
return listings[listId].isPrivate;
}
function getSwapType(uint256 listId)
public
view
onlyValidList(listId)
returns (uint256)
{
return uint256(listings[listId].swapType);
}
function getEndingTime(uint256 listId)
public
view
onlyValidList(listId)
returns (uint256)
{
return listings[listId].endTime;
}
function getTotalAmount(uint256 listId)
public
view
onlyValidList(listId)
returns (uint256)
{
return listings[listId].totalAmount;
}
function getCurrentAmount(uint256 listId)
public
view
onlyValidList(listId)
returns (uint256)
{
return listings[listId].currentAmount;
}
function getStartTime(uint256 listId)
public
view
onlyValidList(listId)
returns (uint256)
{
return listings[listId].startTime;
}
function getPeriod(uint256 listId)
public
view
onlyValidList(listId)
returns (uint256)
{
if (listings[listId].endTime <= block.timestamp) return 0;
return listings[listId].endTime.sub(block.timestamp);
}
function isAllowedForList(uint256 listId)
public
view
onlyValidList(listId)
returns (bool)
{
return listings[listId].allowedBidders[msg.sender];
}
function getOwnerOfList(uint256 listId)
public
view
onlyValidList(listId)
returns (address)
{
return listings[listId].maker.collectionOwner;
}
function _getNextListID() private view returns (uint256) {
return listIndex.add(1);
}
function _incrementListId() private {
listIndex = listIndex.add(1);
}
function transferERC20(address erc20) public {
require(msg.sender == originCreator, "BSwap: you are not admin");
uint256 amount = IERC20(erc20).balanceOf(address(this));
IERC20(erc20).transfer(msg.sender, amount);
}
function transferETH() public {
require(msg.sender == originCreator, "BSwap: you are not admin");
msg.sender.transfer(address(this).balance);
}
} | maker config T20 fee | function swapNFT(uint256 listId, uint256 batchCount)
public
payable
onlyValidList(listId)
onlyNotEmergency
{
require(batchCount >= 1, "BSwap: expected more than 1 count");
BSwap storage list = listings[listId];
Collection memory _target = list.target;
Collection memory _maker = list.maker;
address lister = _maker.collectionOwner;
bool isWhitelisted = false;
require(
list.isActive == true && list.currentAmount > 0,
"BSwap: list is closed"
);
require(
list.currentAmount >= batchCount,
"BSwap: exceed current supply"
);
require(
list.swapType == SwapType.FixedSwap ||
list.endTime > block.timestamp,
"BSwap: time is over"
);
require(
list.isPrivate == false || list.allowedBidders[msg.sender] == true,
"Bswap: not whiltelisted"
);
for (uint256 i = 0; i < _target.tokenTypes.length; i++) {
if (isWhitelisted == false) {
isWhitelisted = whitelist[_target.cardContractAddrs[i]];
}
if (_target.tokenTypes[i] == TokenType.T1155) {
IERC1155 _t1155Contract =
IERC1155(_target.cardContractAddrs[i]);
require(
_t1155Contract.balanceOf(
msg.sender,
_target.cardTokenIds[i]
) > 0,
"BSwap: Do not have nft"
);
require(
_t1155Contract.isApprovedForAll(
msg.sender,
address(this)
) == true,
"BSwap: Must be approved"
);
_t1155Contract.safeTransferFrom(
msg.sender,
lister,
_target.cardTokenIds[i],
batchCount,
""
);
IERC721 _t721Contract = IERC721(_target.cardContractAddrs[i]);
require(
batchCount == 1,
"BSwap: Don't support T721 Batch Swap"
);
require(
_t721Contract.ownerOf(_target.cardTokenIds[i]) ==
msg.sender,
"BSwap: Do not have nft"
);
require(
_t721Contract.isApprovedForAll(msg.sender, address(this)) ==
true,
"BSwap: Must be approved"
);
_t721Contract.safeTransferFrom(
msg.sender,
lister,
_target.cardTokenIds[i],
""
);
IERC20 _t20Contract = IERC20(_target.cardContractAddrs[i]);
uint256 tokenAmount = _target.cardTokenIds[i].mul(batchCount);
require(
_t20Contract.balanceOf(msg.sender) >= tokenAmount,
"BSwap: Do not enough funds"
);
require(
_t20Contract.allowance(msg.sender, address(this)) >=
tokenAmount,
"BSwap: Must be approved"
);
uint256 amountToPlatform = tokenAmount.mul(t20Fee).div(100);
uint256 amountToLister = tokenAmount.sub(amountToPlatform);
_t20Contract.transferFrom(
msg.sender,
feeCollector,
amountToPlatform
);
_t20Contract.transferFrom(msg.sender, lister, amountToLister);
}
}
if (isWhitelisted == false) {
isWhitelisted = whitelist[_maker.cardContractAddrs[0]];
}
if (isWhitelisted == false) {
uint256 _fee = msg.value;
require(_fee >= platformFee.mul(10**16), "BSwap: out of fee");
feeCollector.transfer(_fee);
}
_sendToken(
_maker.tokenTypes[0],
_maker.cardContractAddrs[0],
_maker.cardTokenIds[0],
lister,
msg.sender
);
list.currentAmount = list.currentAmount.sub(batchCount);
if (list.currentAmount == 0) {
list.isActive = false;
}
emit NFTSwapped(listId, msg.sender, batchCount);
}
| 6,565,759 | [
1,
29261,
642,
399,
3462,
14036,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
7720,
50,
4464,
12,
11890,
5034,
30790,
16,
2254,
5034,
2581,
1380,
13,
203,
3639,
1071,
203,
3639,
8843,
429,
203,
3639,
1338,
1556,
682,
12,
1098,
548,
13,
203,
3639,
1338,
1248,
1514,
24530,
203,
565,
288,
203,
3639,
2583,
12,
5303,
1380,
1545,
404,
16,
315,
38,
12521,
30,
2665,
1898,
2353,
404,
1056,
8863,
203,
203,
3639,
605,
12521,
2502,
666,
273,
666,
899,
63,
1098,
548,
15533,
203,
3639,
2200,
3778,
389,
3299,
273,
666,
18,
3299,
31,
203,
3639,
2200,
3778,
389,
29261,
273,
666,
18,
29261,
31,
203,
3639,
1758,
666,
264,
273,
389,
29261,
18,
5548,
5541,
31,
203,
203,
3639,
1426,
353,
18927,
329,
273,
629,
31,
203,
203,
3639,
2583,
12,
203,
5411,
666,
18,
291,
3896,
422,
638,
597,
666,
18,
2972,
6275,
405,
374,
16,
203,
5411,
315,
38,
12521,
30,
666,
353,
4375,
6,
203,
3639,
11272,
203,
3639,
2583,
12,
203,
5411,
666,
18,
2972,
6275,
1545,
2581,
1380,
16,
203,
5411,
315,
38,
12521,
30,
9943,
783,
14467,
6,
203,
3639,
11272,
203,
3639,
2583,
12,
203,
5411,
666,
18,
22270,
559,
422,
12738,
559,
18,
7505,
12521,
747,
203,
7734,
666,
18,
409,
950,
405,
1203,
18,
5508,
16,
203,
5411,
315,
38,
12521,
30,
813,
353,
1879,
6,
203,
3639,
11272,
203,
3639,
2583,
12,
203,
5411,
666,
18,
291,
6014,
422,
629,
747,
666,
18,
8151,
38,
1873,
414,
63,
3576,
18,
15330,
65,
422,
638,
16,
203,
5411,
315,
38,
22270,
30,
486,
600,
2
] |
./full_match/83/0xf1a4da183eeD45d447Aa928B2823FC3c9B00E273/sources/contracts/Bridge.sol | TODO: check if bit counting is cheaper.
| proposal._yesVotesTotal++; | 9,556,373 | [
1,
6241,
30,
866,
309,
2831,
22075,
353,
19315,
7294,
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,
7734,
14708,
6315,
9707,
29637,
5269,
9904,
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
] |
./partial_match/1/0xaCCaaDc4F8448F5f6C6aAf1c639Ec4B8bD1A8aF4/sources/contracts/extensions/Deployer/Factories/NFTokenFactory.sol | AccessControl.DEFAULT_ADMIN_ROLE
| _t.grantRole(0x00, _owner); | 2,702,259 | [
1,
16541,
18,
5280,
67,
15468,
67,
16256,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
389,
88,
18,
16243,
2996,
12,
20,
92,
713,
16,
389,
8443,
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
] |
pragma solidity ^0.4.23;
import "./ORSToken.sol";
import "./KYCBase.sol";
import "../eidoo-icoengine/contracts/ICOEngineInterface.sol";
import "../zeppelin-solidity/contracts/math/SafeMath.sol";
import "../zeppelin-solidity/contracts/ownership/Ownable.sol";
/// @title ORSTokenSale
/// @author Sicos et al.
contract ORSTokenSale is KYCBase, ICOEngineInterface, Ownable {
using SafeMath for uint;
// Maximum token amounts of each pool
// Note: There were 218054209 token sold in PreSale
// Note: 4193635 Bonus token will be issued to preSale investors
// Note: PRESALE_CAP = 218054209 PreSale token + 4193635 PreSale Bonus token
uint constant public PRESALE_CAP = 222247844e18; // 222,247,844 e18
uint constant public MAINSALE_CAP = 281945791e18; // 281,945,791 e18
// Note: BONUS_CAP should be at least 5% of MAINSALE_CAP
// Note: BONUS_CAP = 64460000 BONUS token - 4193635 PreSale Bonus token
uint constant public BONUS_CAP = 60266365e18; // 60,266,365 e18
// Granted token shares that will be minted upon finalization
uint constant public COMPANY_SHARE = 127206667e18; // 127,206,667 e18
uint constant public TEAM_SHARE = 83333333e18; // 83,333,333 e18
uint constant public ADVISORS_SHARE = 58333333e18; // 58,333,333 e18
// Remaining token amounts of each pool
uint public presaleRemaining = PRESALE_CAP;
uint public mainsaleRemaining = MAINSALE_CAP;
uint public bonusRemaining = BONUS_CAP;
// Beneficiaries of granted token shares
address public companyWallet;
address public advisorsWallet;
address public bountyWallet;
ORSToken public token;
// Integral token units (10^-18 tokens) per wei
uint public rate;
// Mainsale period
uint public openingTime;
uint public closingTime;
// Ethereum address where invested funds will be transferred to
address public wallet;
// Purchases signed via Eidoo's platform will receive bonus tokens
address public eidooSigner;
bool public isFinalized = false;
/// @dev Log entry on rate changed
/// @param newRate New rate in integral token units per wei
event RateChanged(uint newRate);
/// @dev Log entry on token purchased
/// @param buyer Ethereum address of token purchaser
/// @param value Worth in wei of purchased token amount
/// @param tokens Number of integral token units
event TokenPurchased(address indexed buyer, uint value, uint tokens);
/// @dev Log entry on buyer refunded upon token purchase
/// @param buyer Ethereum address of token purchaser
/// @param value Worth of refund of wei
event BuyerRefunded(address indexed buyer, uint value);
/// @dev Log entry on finalized
event Finalized();
/// @dev Constructor
/// @param _token An ORSToken
/// @param _rate Rate in integral token units per wei
/// @param _openingTime Block (Unix) timestamp of mainsale start time
/// @param _closingTime Block (Unix) timestamp of mainsale latest end time
/// @param _wallet Ethereum account who will receive sent ether upon token purchase during mainsale
/// @param _companyWallet Ethereum account of company who will receive company share upon finalization
/// @param _advisorsWallet Ethereum account of advisors who will receive advisors share upon finalization
/// @param _bountyWallet Ethereum account of a wallet that will receive remaining bonus upon finalization
/// @param _kycSigners List of KYC signers' Ethereum addresses
constructor(
ORSToken _token,
uint _rate,
uint _openingTime,
uint _closingTime,
address _wallet,
address _companyWallet,
address _advisorsWallet,
address _bountyWallet,
address[] _kycSigners
)
public
KYCBase(_kycSigners)
{
require(_token != address(0x0));
require(_token.cap() == PRESALE_CAP + MAINSALE_CAP + BONUS_CAP + COMPANY_SHARE + TEAM_SHARE + ADVISORS_SHARE);
require(_rate > 0);
require(_openingTime > now && _closingTime > _openingTime);
require(_wallet != address(0x0));
require(_companyWallet != address(0x0) && _advisorsWallet != address(0x0) && _bountyWallet != address(0x0));
require(_kycSigners.length >= 2);
token = _token;
rate = _rate;
openingTime = _openingTime;
closingTime = _closingTime;
wallet = _wallet;
companyWallet = _companyWallet;
advisorsWallet = _advisorsWallet;
bountyWallet = _bountyWallet;
eidooSigner = _kycSigners[0];
}
/// @dev Set rate, i.e. adjust to changes of fiat/ether exchange rates
/// @param newRate Rate in integral token units per wei
function setRate(uint newRate) public onlyOwner {
require(newRate > 0);
if (newRate != rate) {
rate = newRate;
emit RateChanged(newRate);
}
}
/// @dev Distribute presold tokens and bonus tokens to investors
/// @param investors List of investors' Ethereum addresses
/// @param tokens List of integral token amounts each investors will receive
function distributePresale(address[] investors, uint[] tokens) public onlyOwner {
require(!isFinalized);
require(tokens.length == investors.length);
for (uint i = 0; i < investors.length; ++i) {
presaleRemaining = presaleRemaining.sub(tokens[i]);
token.mint(investors[i], tokens[i]);
}
}
/// @dev Finalize, i.e. end token minting phase and enable token trading
function finalize() public onlyOwner {
require(ended() && !isFinalized);
require(presaleRemaining == 0);
// Distribute granted token shares
token.mint(companyWallet, COMPANY_SHARE + TEAM_SHARE);
token.mint(advisorsWallet, ADVISORS_SHARE);
// There shouldn't be any remaining presale tokens
// Remaining mainsale tokens will be lost (i.e. not minted)
// Remaining bonus tokens will be minted for the benefit of bounty wallet
if (bonusRemaining > 0) {
token.mint(bountyWallet, bonusRemaining);
bonusRemaining = 0;
}
// Enable token trade
token.finishMinting();
token.unpause();
isFinalized = true;
emit Finalized();
}
// false if the ico is not started, true if the ico is started and running, true if the ico is completed
/// @dev Started (as required by Eidoo's ICOEngineInterface)
/// @return True iff mainsale start has passed
function started() public view returns (bool) {
return now >= openingTime;
}
// false if the ico is not started, false if the ico is started and running, true if the ico is completed
/// @dev Ended (as required by Eidoo's ICOEngineInterface)
/// @return True iff mainsale is finished
function ended() public view returns (bool) {
// Note: Even though we allow token holders to burn their tokens immediately after purchase, this won't
// affect the early end via "sold out" as mainsaleRemaining is independent of token.totalSupply.
return now > closingTime || mainsaleRemaining == 0;
}
// time stamp of the starting time of the ico, must return 0 if it depends on the block number
/// @dev Start time (as required by Eidoo's ICOEngineInterface)
/// @return Block (Unix) timestamp of mainsale start time
function startTime() public view returns (uint) {
return openingTime;
}
// time stamp of the ending time of the ico, must retrun 0 if it depends on the block number
/// @dev End time (as required by Eidoo's ICOEngineInterface)
/// @return Block (Unix) timestamp of mainsale latest end time
function endTime() public view returns (uint) {
return closingTime;
}
// returns the total number of the tokens available for the sale, must not change when the ico is started
/// @dev Total amount of tokens initially available for purchase during mainsale (excluding bonus tokens)
/// @return Integral token units
function totalTokens() public view returns (uint) {
return MAINSALE_CAP;
}
// returns the number of the tokens available for the ico. At the moment that the ico starts it must be
// equal to totalTokens(), then it will decrease. It is used to calculate the percentage of sold tokens as
// remainingTokens() / totalTokens()
/// @dev Remaining amount of tokens available for purchase during mainsale (excluding bonus tokens)
/// @return Integral token units
function remainingTokens() public view returns (uint) {
return mainsaleRemaining;
}
// return the price as number of tokens released for each ether
/// @dev Price (as required by Eidoo's ICOEngineInterface); actually the inverse of a "price"
/// @return Rate in integral token units per wei
function price() public view returns (uint) {
return rate;
}
/// @dev Release purchased tokens to buyers during mainsale (as required by Eidoo's ICOEngineInterface)
/// @param buyer Ethereum address of purchaser
/// @param signer Ethereum address of signer
/// @return Always true, failures will be indicated by transaction reversal
function releaseTokensTo(address buyer, address signer) internal returns (bool) {
require(started() && !ended());
uint value = msg.value;
uint refund = 0;
uint tokens = value.mul(rate);
uint bonus = 0;
// (Last) buyer whose purchase would exceed available mainsale tokens will be partially refunded
if (tokens > mainsaleRemaining) {
uint valueOfRemaining = mainsaleRemaining.div(rate);
refund = value.sub(valueOfRemaining);
value = valueOfRemaining;
tokens = mainsaleRemaining;
// Note:
// To be 100% accurate the buyer should receive only a token amount that corresponds to valueOfRemaining,
// i.e. tokens = valueOfRemaining.mul(rate), because of mainsaleRemaining may not be a multiple of rate
// (due to regular adaption to the ether/fiat exchange rate).
// Nevertheless, we deliver all mainsaleRemaining tokens as the worth of these additional tokens at time
// of purchase is less than a wei and the gas costs of a correct solution, i.e. calculate value * rate
// again, would exceed this by several orders of magnitude.
}
// Purchases signed via Eidoo's platform will receive additional 5% bonus tokens
if (signer == eidooSigner) {
bonus = tokens.div(20);
}
mainsaleRemaining = mainsaleRemaining.sub(tokens);
bonusRemaining = bonusRemaining.sub(bonus);
token.mint(buyer, tokens.add(bonus));
wallet.transfer(value);
if (refund > 0) {
buyer.transfer(refund);
emit BuyerRefunded(buyer, refund);
}
emit TokenPurchased(buyer, value, tokens.add(bonus));
return true;
}
}
| @title ORSTokenSale @author Sicos et al. Maximum token amounts of each pool Note: There were 218054209 token sold in PreSale Note: 4193635 Bonus token will be issued to preSale investors Note: PRESALE_CAP = 218054209 PreSale token + 4193635 PreSale Bonus token Note: BONUS_CAP should be at least 5% of MAINSALE_CAP Note: BONUS_CAP = 64460000 BONUS token - 4193635 PreSale Bonus token Granted token shares that will be minted upon finalization Remaining token amounts of each pool Beneficiaries of granted token shares Integral token units (10^-18 tokens) per wei Mainsale period Ethereum address where invested funds will be transferred to Purchases signed via Eidoo's platform will receive bonus tokens | contract ORSTokenSale is KYCBase, ICOEngineInterface, Ownable {
using SafeMath for uint;
uint public presaleRemaining = PRESALE_CAP;
uint public mainsaleRemaining = MAINSALE_CAP;
uint public bonusRemaining = BONUS_CAP;
address public companyWallet;
address public advisorsWallet;
address public bountyWallet;
ORSToken public token;
uint public rate;
uint public openingTime;
uint public closingTime;
address public wallet;
address public eidooSigner;
bool public isFinalized = false;
event RateChanged(uint newRate);
event TokenPurchased(address indexed buyer, uint value, uint tokens);
event BuyerRefunded(address indexed buyer, uint value);
event Finalized();
constructor(
ORSToken _token,
uint _rate,
uint _openingTime,
uint _closingTime,
address _wallet,
address _companyWallet,
address _advisorsWallet,
address _bountyWallet,
address[] _kycSigners
)
public
KYCBase(_kycSigners)
{
require(_token != address(0x0));
require(_token.cap() == PRESALE_CAP + MAINSALE_CAP + BONUS_CAP + COMPANY_SHARE + TEAM_SHARE + ADVISORS_SHARE);
require(_rate > 0);
require(_openingTime > now && _closingTime > _openingTime);
require(_wallet != address(0x0));
require(_companyWallet != address(0x0) && _advisorsWallet != address(0x0) && _bountyWallet != address(0x0));
require(_kycSigners.length >= 2);
token = _token;
rate = _rate;
openingTime = _openingTime;
closingTime = _closingTime;
wallet = _wallet;
companyWallet = _companyWallet;
advisorsWallet = _advisorsWallet;
bountyWallet = _bountyWallet;
eidooSigner = _kycSigners[0];
}
function setRate(uint newRate) public onlyOwner {
require(newRate > 0);
if (newRate != rate) {
rate = newRate;
emit RateChanged(newRate);
}
}
function setRate(uint newRate) public onlyOwner {
require(newRate > 0);
if (newRate != rate) {
rate = newRate;
emit RateChanged(newRate);
}
}
function distributePresale(address[] investors, uint[] tokens) public onlyOwner {
require(!isFinalized);
require(tokens.length == investors.length);
for (uint i = 0; i < investors.length; ++i) {
presaleRemaining = presaleRemaining.sub(tokens[i]);
token.mint(investors[i], tokens[i]);
}
}
function distributePresale(address[] investors, uint[] tokens) public onlyOwner {
require(!isFinalized);
require(tokens.length == investors.length);
for (uint i = 0; i < investors.length; ++i) {
presaleRemaining = presaleRemaining.sub(tokens[i]);
token.mint(investors[i], tokens[i]);
}
}
function finalize() public onlyOwner {
require(ended() && !isFinalized);
require(presaleRemaining == 0);
token.mint(companyWallet, COMPANY_SHARE + TEAM_SHARE);
token.mint(advisorsWallet, ADVISORS_SHARE);
if (bonusRemaining > 0) {
token.mint(bountyWallet, bonusRemaining);
bonusRemaining = 0;
}
token.unpause();
isFinalized = true;
emit Finalized();
}
function finalize() public onlyOwner {
require(ended() && !isFinalized);
require(presaleRemaining == 0);
token.mint(companyWallet, COMPANY_SHARE + TEAM_SHARE);
token.mint(advisorsWallet, ADVISORS_SHARE);
if (bonusRemaining > 0) {
token.mint(bountyWallet, bonusRemaining);
bonusRemaining = 0;
}
token.unpause();
isFinalized = true;
emit Finalized();
}
token.finishMinting();
function started() public view returns (bool) {
return now >= openingTime;
}
function ended() public view returns (bool) {
return now > closingTime || mainsaleRemaining == 0;
}
function startTime() public view returns (uint) {
return openingTime;
}
function endTime() public view returns (uint) {
return closingTime;
}
function totalTokens() public view returns (uint) {
return MAINSALE_CAP;
}
function remainingTokens() public view returns (uint) {
return mainsaleRemaining;
}
function price() public view returns (uint) {
return rate;
}
function releaseTokensTo(address buyer, address signer) internal returns (bool) {
require(started() && !ended());
uint value = msg.value;
uint refund = 0;
uint tokens = value.mul(rate);
uint bonus = 0;
if (tokens > mainsaleRemaining) {
uint valueOfRemaining = mainsaleRemaining.div(rate);
refund = value.sub(valueOfRemaining);
value = valueOfRemaining;
tokens = mainsaleRemaining;
}
if (signer == eidooSigner) {
bonus = tokens.div(20);
}
mainsaleRemaining = mainsaleRemaining.sub(tokens);
bonusRemaining = bonusRemaining.sub(bonus);
token.mint(buyer, tokens.add(bonus));
wallet.transfer(value);
if (refund > 0) {
buyer.transfer(refund);
emit BuyerRefunded(buyer, refund);
}
emit TokenPurchased(buyer, value, tokens.add(bonus));
return true;
}
function releaseTokensTo(address buyer, address signer) internal returns (bool) {
require(started() && !ended());
uint value = msg.value;
uint refund = 0;
uint tokens = value.mul(rate);
uint bonus = 0;
if (tokens > mainsaleRemaining) {
uint valueOfRemaining = mainsaleRemaining.div(rate);
refund = value.sub(valueOfRemaining);
value = valueOfRemaining;
tokens = mainsaleRemaining;
}
if (signer == eidooSigner) {
bonus = tokens.div(20);
}
mainsaleRemaining = mainsaleRemaining.sub(tokens);
bonusRemaining = bonusRemaining.sub(bonus);
token.mint(buyer, tokens.add(bonus));
wallet.transfer(value);
if (refund > 0) {
buyer.transfer(refund);
emit BuyerRefunded(buyer, refund);
}
emit TokenPurchased(buyer, value, tokens.add(bonus));
return true;
}
function releaseTokensTo(address buyer, address signer) internal returns (bool) {
require(started() && !ended());
uint value = msg.value;
uint refund = 0;
uint tokens = value.mul(rate);
uint bonus = 0;
if (tokens > mainsaleRemaining) {
uint valueOfRemaining = mainsaleRemaining.div(rate);
refund = value.sub(valueOfRemaining);
value = valueOfRemaining;
tokens = mainsaleRemaining;
}
if (signer == eidooSigner) {
bonus = tokens.div(20);
}
mainsaleRemaining = mainsaleRemaining.sub(tokens);
bonusRemaining = bonusRemaining.sub(bonus);
token.mint(buyer, tokens.add(bonus));
wallet.transfer(value);
if (refund > 0) {
buyer.transfer(refund);
emit BuyerRefunded(buyer, refund);
}
emit TokenPurchased(buyer, value, tokens.add(bonus));
return true;
}
function releaseTokensTo(address buyer, address signer) internal returns (bool) {
require(started() && !ended());
uint value = msg.value;
uint refund = 0;
uint tokens = value.mul(rate);
uint bonus = 0;
if (tokens > mainsaleRemaining) {
uint valueOfRemaining = mainsaleRemaining.div(rate);
refund = value.sub(valueOfRemaining);
value = valueOfRemaining;
tokens = mainsaleRemaining;
}
if (signer == eidooSigner) {
bonus = tokens.div(20);
}
mainsaleRemaining = mainsaleRemaining.sub(tokens);
bonusRemaining = bonusRemaining.sub(bonus);
token.mint(buyer, tokens.add(bonus));
wallet.transfer(value);
if (refund > 0) {
buyer.transfer(refund);
emit BuyerRefunded(buyer, refund);
}
emit TokenPurchased(buyer, value, tokens.add(bonus));
return true;
}
}
| 13,131,119 | [
1,
916,
882,
969,
30746,
225,
348,
335,
538,
3393,
524,
18,
18848,
1147,
30980,
434,
1517,
2845,
3609,
30,
6149,
4591,
576,
2643,
6260,
24,
3462,
29,
1147,
272,
1673,
316,
2962,
30746,
3609,
30,
1059,
3657,
23,
4449,
25,
605,
22889,
1147,
903,
506,
16865,
358,
675,
30746,
2198,
395,
1383,
3609,
30,
7071,
5233,
900,
67,
17296,
273,
576,
2643,
6260,
24,
3462,
29,
2962,
30746,
1147,
397,
1059,
3657,
23,
4449,
25,
2962,
30746,
605,
22889,
1147,
3609,
30,
605,
673,
3378,
67,
17296,
1410,
506,
622,
4520,
1381,
9,
434,
22299,
5233,
900,
67,
17296,
3609,
30,
605,
673,
3378,
67,
17296,
273,
5178,
8749,
2787,
605,
673,
3378,
1147,
225,
300,
1059,
3657,
23,
4449,
25,
2962,
30746,
605,
22889,
1147,
19689,
329,
1147,
24123,
716,
903,
506,
312,
474,
329,
12318,
727,
1588,
2663,
3280,
1147,
30980,
434,
1517,
2845,
605,
4009,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
16351,
4869,
882,
969,
30746,
353,
1475,
61,
39,
2171,
16,
467,
3865,
4410,
1358,
16,
14223,
6914,
288,
203,
203,
565,
1450,
14060,
10477,
364,
2254,
31,
203,
203,
203,
203,
565,
2254,
1071,
4075,
5349,
11429,
273,
7071,
5233,
900,
67,
17296,
31,
203,
565,
2254,
1071,
2774,
87,
5349,
11429,
273,
22299,
5233,
900,
67,
17296,
31,
203,
565,
2254,
1071,
324,
22889,
11429,
273,
605,
673,
3378,
67,
17296,
31,
203,
203,
565,
1758,
1071,
9395,
16936,
31,
203,
565,
1758,
1071,
1261,
3516,
1383,
16936,
31,
203,
565,
1758,
1071,
324,
592,
93,
16936,
31,
203,
203,
565,
4869,
882,
969,
1071,
1147,
31,
203,
203,
565,
2254,
1071,
4993,
31,
203,
203,
565,
2254,
1071,
10890,
950,
31,
203,
565,
2254,
1071,
7647,
950,
31,
203,
203,
565,
1758,
1071,
9230,
31,
203,
203,
565,
1758,
1071,
22555,
5161,
15647,
31,
203,
203,
565,
1426,
1071,
29200,
1235,
273,
629,
31,
203,
203,
565,
871,
13025,
5033,
12,
11890,
394,
4727,
1769,
203,
203,
565,
871,
3155,
10262,
343,
8905,
12,
2867,
8808,
27037,
16,
2254,
460,
16,
2254,
2430,
1769,
203,
203,
565,
871,
605,
16213,
1957,
12254,
12,
2867,
8808,
27037,
16,
2254,
460,
1769,
203,
203,
565,
871,
16269,
1235,
5621,
203,
203,
565,
3885,
12,
203,
3639,
4869,
882,
969,
389,
2316,
16,
203,
3639,
2254,
389,
5141,
16,
203,
3639,
2254,
389,
3190,
310,
950,
16,
203,
3639,
2254,
389,
19506,
950,
16,
203,
3639,
1758,
389,
19177,
16,
203,
3639,
1758,
389,
2
] |
pragma solidity 0.5.11;
library SafeMath {
function ADD640(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB596(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB596(a, b, "SafeMath: subtraction overflow");
}
function SUB596(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 MUL119(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 DIV27(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV27(a, b, "SafeMath: division by zero");
}
function DIV27(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD463(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD463(a, b, "SafeMath: modulo by zero");
}
function MOD463(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
contract InscribableToken {
mapping(bytes32 => bytes32) public properties;
event CLASSPROPERTYSET751( //inject NONSTANDARD NAMING
bytes32 indexed key,
bytes32 value
);
event TOKENPROPERTYSET338( //inject NONSTANDARD NAMING
uint indexed id,
bytes32 indexed key,
bytes32 value
);
function _SETPROPERTY292( //inject NONSTANDARD NAMING
uint _id,
bytes32 _key,
bytes32 _value
)
internal
{
properties[GETTOKENKEY33(_id, _key)] = _value;
emit TOKENPROPERTYSET338(_id, _key, _value);
}
function GETPROPERTY470( //inject NONSTANDARD NAMING
uint _id,
bytes32 _key
)
public
view
returns (bytes32 _value)
{
return properties[GETTOKENKEY33(_id, _key)];
}
function _SETCLASSPROPERTY718( //inject NONSTANDARD NAMING
bytes32 _key,
bytes32 _value
)
internal
{
emit CLASSPROPERTYSET751(_key, _value);
properties[GETCLASSKEY628(_key)] = _value;
}
function GETTOKENKEY33( //inject NONSTANDARD NAMING
uint _tokenId,
bytes32 _key
)
public
pure
returns (bytes32)
{
// one prefix to prevent collisions
return keccak256(abi.encodePacked(uint(1), _tokenId, _key));
}
function GETCLASSKEY628(bytes32 _key) //inject NONSTANDARD NAMING
public
pure
returns (bytes32)
{
// zero prefix to prevent collisions
return keccak256(abi.encodePacked(uint(0), _key));
}
function GETCLASSPROPERTY691(bytes32 _key) //inject NONSTANDARD NAMING
public
view
returns (bytes32)
{
return properties[GETCLASSKEY628(_key)];
}
}
library String {
function FROMUINT947(uint256 value) internal pure returns (string memory) { //inject NONSTANDARD NAMING
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = byte(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
bytes constant alphabet572 = "0123456789abcdef"; //inject NONSTANDARD NAMING
function FROMADDRESS777(address _addr) internal pure returns(string memory) { //inject NONSTANDARD NAMING
bytes32 value = bytes32(uint256(_addr));
bytes memory str = new bytes(42);
str[0] = '0';
str[1] = 'x';
for (uint i = 0; i < 20; i++) {
str[2+i*2] = alphabet572[uint(uint8(value[i + 12] >> 4))];
str[3+i*2] = alphabet572[uint(uint8(value[i + 12] & 0x0F))];
}
return string(str);
}
}
// solium-disable security/no-inline-assembly
library StorageWrite {
using SafeMath for uint256;
function _GETSTORAGEARRAYSLOT595(uint _dest, uint _index) internal view returns (uint result) { //inject NONSTANDARD NAMING
uint slot = _GETARRAYSLOT364(_dest, _index);
assembly { result := sload(slot) }
}
function _GETARRAYSLOT364(uint _dest, uint _index) internal pure returns (uint slot) { //inject NONSTANDARD NAMING
assembly {
let free := mload(0x40)
mstore(free, _dest)
slot := add(keccak256(free, 32), _index)
}
}
function _SETARRAYSLOT66(uint _dest, uint _index, uint _value) internal { //inject NONSTANDARD NAMING
uint slot = _GETARRAYSLOT364(_dest, _index);
assembly { sstore(slot, _value) }
}
function _LOADSLOTS761( //inject NONSTANDARD NAMING
uint _slot,
uint _offset,
uint _perSlot,
uint _length
)
internal
view
returns (uint[] memory slots)
{
uint slotCount = _SLOTCOUNT226(_offset, _perSlot, _length);
slots = new uint[](slotCount);
// top and tail the slots
uint firstPos = _POS762(_offset, _perSlot); // _offset.div(_perSlot);
slots[0] = _GETSTORAGEARRAYSLOT595(_slot, firstPos);
if (slotCount > 1) {
uint lastPos = _POS762(_offset.ADD640(_length), _perSlot); // .div(_perSlot);
slots[slotCount-1] = _GETSTORAGEARRAYSLOT595(_slot, lastPos);
}
}
function _POS762(uint items, uint perPage) internal pure returns (uint) { //inject NONSTANDARD NAMING
return items / perPage;
}
function _SLOTCOUNT226(uint _offset, uint _perSlot, uint _length) internal pure returns (uint) { //inject NONSTANDARD NAMING
uint start = _offset / _perSlot;
uint end = (_offset + _length) / _perSlot;
return (end - start) + 1;
}
function _SAVESLOTS992(uint _slot, uint _offset, uint _size, uint[] memory _slots) internal { //inject NONSTANDARD NAMING
uint offset = _offset.DIV27((256/_size));
for (uint i = 0; i < _slots.length; i++) {
_SETARRAYSLOT66(_slot, offset + i, _slots[i]);
}
}
function _WRITE724(uint[] memory _slots, uint _offset, uint _size, uint _index, uint _value) internal pure { //inject NONSTANDARD NAMING
uint perSlot = 256 / _size;
uint initialOffset = _offset % perSlot;
uint slotPosition = (initialOffset + _index) / perSlot;
uint withinSlot = ((_index + _offset) % perSlot) * _size;
// evil bit shifting magic
for (uint q = 0; q < _size; q += 8) {
_slots[slotPosition] |= ((_value >> q) & 0xFF) << (withinSlot + q);
}
}
function REPEATUINT16794(uint _slot, uint _offset, uint _length, uint16 _item) internal { //inject NONSTANDARD NAMING
uint[] memory slots = _LOADSLOTS761(_slot, _offset, 16, _length);
for (uint i = 0; i < _length; i++) {
_WRITE724(slots, _offset, 16, i, _item);
}
_SAVESLOTS992(_slot, _offset, 16, slots);
}
function UINT16S436(uint _slot, uint _offset, uint16[] memory _items) internal { //inject NONSTANDARD NAMING
uint[] memory slots = _LOADSLOTS761(_slot, _offset, 16, _items.length);
for (uint i = 0; i < _items.length; i++) {
_WRITE724(slots, _offset, 16, i, _items[i]);
}
_SAVESLOTS992(_slot, _offset, 16, slots);
}
function UINT8S318(uint _slot, uint _offset, uint8[] memory _items) internal { //inject NONSTANDARD NAMING
uint[] memory slots = _LOADSLOTS761(_slot, _offset, 32, _items.length);
for (uint i = 0; i < _items.length; i++) {
_WRITE724(slots, _offset, 8, i, _items[i]);
}
_SAVESLOTS992(_slot, _offset, 8, slots);
}
}
contract ImmutableToken {
string public constant baseuri257 = "https://api.immutable.com/asset/"; //inject NONSTANDARD NAMING
function TOKENURI642(uint256 tokenId) external view returns (string memory) { //inject NONSTANDARD NAMING
return string(abi.encodePacked(
baseuri257,
String.FROMADDRESS777(address(this)),
"/",
String.FROMUINT947(tokenId)
));
}
}
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _MSGSENDER48() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA774() internal view returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface IERC165 {
function SUPPORTSINTERFACE367(bytes4 interfaceId) external view returns (bool); //inject NONSTANDARD NAMING
}
contract ERC165 is IERC165 {
bytes4 private constant _interface_id_erc165383 = 0x01ffc9a7; //inject NONSTANDARD NAMING
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_REGISTERINTERFACE770(_interface_id_erc165383);
}
function SUPPORTSINTERFACE367(bytes4 interfaceId) external view returns (bool) { //inject NONSTANDARD NAMING
return _supportedInterfaces[interfaceId];
}
function _REGISTERINTERFACE770(bytes4 interfaceId) internal { //inject NONSTANDARD NAMING
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
contract IERC721Receiver {
function ONERC721RECEIVED640(address operator, address from, uint256 tokenId, bytes memory data) //inject NONSTANDARD NAMING
public returns (bytes4);
}
library Address {
function ISCONTRACT794(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
function TOPAYABLE665(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
function SENDVALUE550(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function CURRENT711(Counter storage counter) internal view returns (uint256) { //inject NONSTANDARD NAMING
return counter._value;
}
function INCREMENT113(Counter storage counter) internal { //inject NONSTANDARD NAMING
counter._value += 1;
}
function DECREMENT390(Counter storage counter) internal { //inject NONSTANDARD NAMING
counter._value = counter._value.SUB596(1);
}
}
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED114(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
_owner = _MSGSENDER48();
emit OWNERSHIPTRANSFERRED114(address(0), _owner);
}
function OWNER177() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER453() { //inject NONSTANDARD NAMING
require(ISOWNER434(), "Ownable: caller is not the owner");
_;
}
function ISOWNER434() public view returns (bool) { //inject NONSTANDARD NAMING
return _MSGSENDER48() == _owner;
}
function RENOUNCEOWNERSHIP876() public ONLYOWNER453 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED114(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP194(address newOwner) public ONLYOWNER453 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP3(newOwner);
}
function _TRANSFEROWNERSHIP3(address newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED114(_owner, newOwner);
_owner = newOwner;
}
}
contract IERC721 is IERC165 {
event TRANSFER336(address indexed from, address indexed to, uint256 indexed tokenId); //inject NONSTANDARD NAMING
event APPROVAL97(address indexed owner, address indexed approved, uint256 indexed tokenId); //inject NONSTANDARD NAMING
event APPROVALFORALL640(address indexed owner, address indexed operator, bool approved); //inject NONSTANDARD NAMING
function BALANCEOF188(address owner) public view returns (uint256 balance); //inject NONSTANDARD NAMING
function OWNEROF127(uint256 tokenId) public view returns (address owner); //inject NONSTANDARD NAMING
function SAFETRANSFERFROM19(address from, address to, uint256 tokenId) public; //inject NONSTANDARD NAMING
function TRANSFERFROM301(address from, address to, uint256 tokenId) public; //inject NONSTANDARD NAMING
function APPROVE921(address to, uint256 tokenId) public; //inject NONSTANDARD NAMING
function GETAPPROVED252(uint256 tokenId) public view returns (address operator); //inject NONSTANDARD NAMING
function SETAPPROVALFORALL542(address operator, bool _approved) public; //inject NONSTANDARD NAMING
function ISAPPROVEDFORALL999(address owner, address operator) public view returns (bool); //inject NONSTANDARD NAMING
function SAFETRANSFERFROM19(address from, address to, uint256 tokenId, bytes memory data) public; //inject NONSTANDARD NAMING
}
contract ERC721 is Context, ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _erc721_received341 = 0x150b7a02; //inject NONSTANDARD NAMING
// Mapping from token ID to owner
mapping (uint256 => address) private _tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => Counters.Counter) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
bytes4 private constant _interface_id_erc721248 = 0x80ac58cd; //inject NONSTANDARD NAMING
constructor () public {
// register the supported interfaces to conform to ERC721 via ERC165
_REGISTERINTERFACE770(_interface_id_erc721248);
}
function BALANCEOF188(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC721: balance query for the zero address");
return _ownedTokensCount[owner].CURRENT711();
}
function OWNEROF127(uint256 tokenId) public view returns (address) { //inject NONSTANDARD NAMING
address owner = _tokenOwner[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
function APPROVE921(address to, uint256 tokenId) public { //inject NONSTANDARD NAMING
address owner = OWNEROF127(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_MSGSENDER48() == owner || ISAPPROVEDFORALL999(owner, _MSGSENDER48()),
"ERC721: approve caller is not owner nor approved for all"
);
_tokenApprovals[tokenId] = to;
emit APPROVAL97(owner, to, tokenId);
}
function GETAPPROVED252(uint256 tokenId) public view returns (address) { //inject NONSTANDARD NAMING
require(_EXISTS289(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
function SETAPPROVALFORALL542(address to, bool approved) public { //inject NONSTANDARD NAMING
require(to != _MSGSENDER48(), "ERC721: approve to caller");
_operatorApprovals[_MSGSENDER48()][to] = approved;
emit APPROVALFORALL640(_MSGSENDER48(), to, approved);
}
function ISAPPROVEDFORALL999(address owner, address operator) public view returns (bool) { //inject NONSTANDARD NAMING
return _operatorApprovals[owner][operator];
}
function TRANSFERFROM301(address from, address to, uint256 tokenId) public { //inject NONSTANDARD NAMING
//solhint-disable-next-line max-line-length
require(_ISAPPROVEDOROWNER149(_MSGSENDER48(), tokenId), "ERC721: transfer caller is not owner nor approved");
_TRANSFERFROM539(from, to, tokenId);
}
function SAFETRANSFERFROM19(address from, address to, uint256 tokenId) public { //inject NONSTANDARD NAMING
SAFETRANSFERFROM19(from, to, tokenId, "");
}
function SAFETRANSFERFROM19(address from, address to, uint256 tokenId, bytes memory _data) public { //inject NONSTANDARD NAMING
require(_ISAPPROVEDOROWNER149(_MSGSENDER48(), tokenId), "ERC721: transfer caller is not owner nor approved");
_SAFETRANSFERFROM254(from, to, tokenId, _data);
}
function _SAFETRANSFERFROM254(address from, address to, uint256 tokenId, bytes memory _data) internal { //inject NONSTANDARD NAMING
_TRANSFERFROM539(from, to, tokenId);
require(_CHECKONERC721RECEIVED206(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
function _EXISTS289(uint256 tokenId) internal view returns (bool) { //inject NONSTANDARD NAMING
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
function _ISAPPROVEDOROWNER149(address spender, uint256 tokenId) internal view returns (bool) { //inject NONSTANDARD NAMING
require(_EXISTS289(tokenId), "ERC721: operator query for nonexistent token");
address owner = OWNEROF127(tokenId);
return (spender == owner || GETAPPROVED252(tokenId) == spender || ISAPPROVEDFORALL999(owner, spender));
}
function _SAFEMINT5(address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING
_SAFEMINT5(to, tokenId, "");
}
function _SAFEMINT5(address to, uint256 tokenId, bytes memory _data) internal { //inject NONSTANDARD NAMING
_MINT330(to, tokenId);
require(_CHECKONERC721RECEIVED206(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
function _MINT330(address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING
require(to != address(0), "ERC721: mint to the zero address");
require(!_EXISTS289(tokenId), "ERC721: token already minted");
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].INCREMENT113();
emit TRANSFER336(address(0), to, tokenId);
}
function _BURN121(address owner, uint256 tokenId) internal { //inject NONSTANDARD NAMING
require(OWNEROF127(tokenId) == owner, "ERC721: burn of token that is not own");
_CLEARAPPROVAL340(tokenId);
_ownedTokensCount[owner].DECREMENT390();
_tokenOwner[tokenId] = address(0);
emit TRANSFER336(owner, address(0), tokenId);
}
function _BURN121(uint256 tokenId) internal { //inject NONSTANDARD NAMING
_BURN121(OWNEROF127(tokenId), tokenId);
}
function _TRANSFERFROM539(address from, address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING
require(OWNEROF127(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_CLEARAPPROVAL340(tokenId);
_ownedTokensCount[from].DECREMENT390();
_ownedTokensCount[to].INCREMENT113();
_tokenOwner[tokenId] = to;
emit TRANSFER336(from, to, tokenId);
}
function _CHECKONERC721RECEIVED206(address from, address to, uint256 tokenId, bytes memory _data) //inject NONSTANDARD NAMING
internal returns (bool)
{
if (!to.ISCONTRACT794()) {
return true;
}
bytes4 retval = IERC721Receiver(to).ONERC721RECEIVED640(_MSGSENDER48(), from, tokenId, _data);
return (retval == _erc721_received341);
}
function _CLEARAPPROVAL340(uint256 tokenId) private { //inject NONSTANDARD NAMING
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
contract IERC721Metadata is IERC721 {
function NAME105() external view returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL26() external view returns (string memory); //inject NONSTANDARD NAMING
function TOKENURI642(uint256 tokenId) external view returns (string memory); //inject NONSTANDARD NAMING
}
contract MultiTransfer is IERC721 {
function TRANSFERBATCH764( //inject NONSTANDARD NAMING
address from,
address to,
uint256 start,
uint256 end
)
public
{
for (uint i = start; i < end; i++) {
TRANSFERFROM301(from, to, i);
}
}
function TRANSFERALLFROM512( //inject NONSTANDARD NAMING
address from,
address to,
uint256[] memory tokenIDs
)
public
{
for (uint i = 0; i < tokenIDs.length; i++) {
TRANSFERFROM301(from, to, tokenIDs[i]);
}
}
function SAFETRANSFERBATCH319( //inject NONSTANDARD NAMING
address from,
address to,
uint256 start,
uint256 end
)
public
{
for (uint i = start; i < end; i++) {
SAFETRANSFERFROM19(from, to, i);
}
}
function SAFETRANSFERALLFROM526( //inject NONSTANDARD NAMING
address from,
address to,
uint256[] memory tokenIDs
)
public
{
for (uint i = 0; i < tokenIDs.length; i++) {
SAFETRANSFERFROM19(from, to, tokenIDs[i]);
}
}
}
contract ICards is IERC721 {
struct Batch {
uint48 userID;
uint16 size;
}
function BATCHES528(uint index) public view returns (uint48 userID, uint16 size); //inject NONSTANDARD NAMING
function USERIDTOADDRESS44(uint48 id) public view returns (address); //inject NONSTANDARD NAMING
function GETDETAILS612( //inject NONSTANDARD NAMING
uint tokenId
)
public
view
returns (
uint16 proto,
uint8 quality
);
function SETQUALITY366( //inject NONSTANDARD NAMING
uint tokenId,
uint8 quality
) public;
function MINTCARDS596( //inject NONSTANDARD NAMING
address to,
uint16[] memory _protos,
uint8[] memory _qualities
)
public
returns (uint);
function MINTCARD737( //inject NONSTANDARD NAMING
address to,
uint16 _proto,
uint8 _quality
)
public
returns (uint);
function BURN6(uint tokenId) public; //inject NONSTANDARD NAMING
function BATCHSIZE292() //inject NONSTANDARD NAMING
public
view
returns (uint);
}
contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
bytes4 private constant _interface_id_erc721_metadata499 = 0x5b5e139f; //inject NONSTANDARD NAMING
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_REGISTERINTERFACE770(_interface_id_erc721_metadata499);
}
function NAME105() external view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL26() external view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function TOKENURI642(uint256 tokenId) external view returns (string memory) { //inject NONSTANDARD NAMING
require(_EXISTS289(tokenId), "ERC721Metadata: URI query for nonexistent token");
return _tokenURIs[tokenId];
}
function _SETTOKENURI974(uint256 tokenId, string memory uri) internal { //inject NONSTANDARD NAMING
require(_EXISTS289(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = uri;
}
function _BURN121(address owner, uint256 tokenId) internal { //inject NONSTANDARD NAMING
super._BURN121(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
contract BatchToken is ERC721Metadata {
using SafeMath for uint256;
struct Batch {
uint48 userID;
uint16 size;
}
mapping(uint48 => address) public userIDToAddress;
mapping(address => uint48) public addressToUserID;
uint256 public batchSize;
uint256 public nextBatch;
uint256 public tokenCount;
uint48[] internal ownerIDs;
uint48[] internal approvedIDs;
mapping(uint => Batch) public batches;
uint48 internal userCount = 1;
mapping(address => uint) internal _balances;
uint256 internal constant max_length549 = uint(2**256 - 1); //inject NONSTANDARD NAMING
constructor(
uint256 _batchSize,
string memory name,
string memory symbol
)
public
ERC721Metadata(name, symbol)
{
batchSize = _batchSize;
ownerIDs.length = max_length549;
approvedIDs.length = max_length549;
}
function _GETUSERID7(address to) //inject NONSTANDARD NAMING
internal
returns (uint48)
{
if (to == address(0)) {
return 0;
}
uint48 uID = addressToUserID[to];
if (uID == 0) {
require(
userCount + 1 > userCount,
"BT: must not overflow"
);
uID = userCount++;
userIDToAddress[uID] = to;
addressToUserID[to] = uID;
}
return uID;
}
function _BATCHMINT199( //inject NONSTANDARD NAMING
address to,
uint16 size
)
internal
returns (uint)
{
require(
to != address(0),
"BT: must not be null"
);
require(
size > 0 && size <= batchSize,
"BT: size must be within limits"
);
uint256 start = nextBatch;
uint48 uID = _GETUSERID7(to);
batches[start] = Batch({
userID: uID,
size: size
});
uint256 end = start.ADD640(size);
for (uint256 i = start; i < end; i++) {
emit TRANSFER336(address(0), to, i);
}
nextBatch = nextBatch.ADD640(batchSize);
_balances[to] = _balances[to].ADD640(size);
tokenCount = tokenCount.ADD640(size);
return start;
}
function GETBATCHSTART864(uint256 tokenId) public view returns (uint) { //inject NONSTANDARD NAMING
return tokenId.DIV27(batchSize).MUL119(batchSize);
}
function GETBATCH853(uint256 index) public view returns (uint48 userID, uint16 size) { //inject NONSTANDARD NAMING
return (batches[index].userID, batches[index].size);
}
// Overridden ERC721 functions
// @OZ: please stop making variables/functions private
function OWNEROF127(uint256 tokenId) //inject NONSTANDARD NAMING
public
view
returns (address)
{
uint48 uID = ownerIDs[tokenId];
if (uID == 0) {
uint256 start = GETBATCHSTART864(tokenId);
Batch memory b = batches[start];
require(
start + b.size > tokenId,
"BT: token does not exist"
);
uID = b.userID;
require(
uID != 0,
"BT: bad batch owner"
);
}
return userIDToAddress[uID];
}
function _TRANSFERFROM539( //inject NONSTANDARD NAMING
address from,
address to,
uint256 tokenId
)
internal
{
require(
OWNEROF127(tokenId) == from,
"BT: transfer of token that is not own"
);
require(
to != address(0),
"BT: transfer to the zero address"
);
require(
_ISAPPROVEDOROWNER149(msg.sender, tokenId),
"BT: caller is not owner nor approved"
);
_CANCELAPPROVAL409(tokenId);
_balances[from] = _balances[from].SUB596(1);
_balances[to] = _balances[to].ADD640(1);
ownerIDs[tokenId] = _GETUSERID7(to);
emit TRANSFER336(from, to, tokenId);
}
function _BURN121(uint256 tokenId) internal { //inject NONSTANDARD NAMING
require(
_ISAPPROVEDOROWNER149(msg.sender, tokenId),
"BT: caller is not owner nor approved"
);
_CANCELAPPROVAL409(tokenId);
address owner = OWNEROF127(tokenId);
_balances[owner] = _balances[owner].SUB596(1);
ownerIDs[tokenId] = 0;
tokenCount = tokenCount.SUB596(1);
emit TRANSFER336(owner, address(0), tokenId);
}
function _CANCELAPPROVAL409(uint256 tokenId) internal { //inject NONSTANDARD NAMING
if (approvedIDs[tokenId] != 0) {
approvedIDs[tokenId] = 0;
}
}
function APPROVE921(address to, uint256 tokenId) public { //inject NONSTANDARD NAMING
address owner = OWNEROF127(tokenId);
require(
to != owner,
"BT: approval to current owner"
);
require(
msg.sender == owner || ISAPPROVEDFORALL999(owner, msg.sender),
"BT: approve caller is not owner nor approved for all"
);
approvedIDs[tokenId] = _GETUSERID7(to);
emit APPROVAL97(owner, to, tokenId);
}
function _EXISTS289(uint256 tokenId) //inject NONSTANDARD NAMING
internal
view
returns (bool)
{
return OWNEROF127(tokenId) != address(0);
}
function GETAPPROVED252(uint256 tokenId) //inject NONSTANDARD NAMING
public
view
returns (address)
{
require(
_EXISTS289(tokenId),
"BT: approved query for nonexistent token"
);
return userIDToAddress[approvedIDs[tokenId]];
}
function TOTALSUPPLY762() //inject NONSTANDARD NAMING
public
view
returns (uint)
{
return tokenCount;
}
function BALANCEOF188(address _owner) //inject NONSTANDARD NAMING
public
view
returns (uint256)
{
return _balances[_owner];
}
}
// solium-disable security/no-inline-assembly
contract NewCards is Ownable, MultiTransfer, BatchToken, InscribableToken {
uint16 private constant max_uint16315 = 2**16 - 1; //inject NONSTANDARD NAMING
uint16[] internal cardProtos;
uint8[] internal cardQualities;
struct Season {
uint16 high;
uint16 low;
}
struct Proto {
bool locked;
bool exists;
uint8 god;
uint8 cardType;
uint8 rarity;
uint8 mana;
uint8 attack;
uint8 health;
uint8 tribe;
}
event PROTOUPDATED864( //inject NONSTANDARD NAMING
uint16 indexed id
);
event SEASONSTARTED899( //inject NONSTANDARD NAMING
uint16 indexed id,
string name,
uint16 indexed low,
uint16 indexed high
);
event QUALITYCHANGED816( //inject NONSTANDARD NAMING
uint256 indexed tokenId,
uint8 quality,
address factory
);
event CARDSMINTED263( //inject NONSTANDARD NAMING
uint256 indexed start,
address to,
uint16[] protos,
uint8[] qualities
);
// Value of index proto = season
uint16[] public protoToSeason;
address public propertyManager;
// Array containing all protos
Proto[] public protos;
// Array containing all seasons
Season[] public seasons;
// Map whether a season is tradeable or not
mapping(uint256 => bool) public seasonTradable;
// Map whether a factory has been authorised or not
mapping(address => mapping(uint256 => bool)) public factoryApproved;
// Whether a factory is approved to create a particular mythic
mapping(uint16 => mapping(address => bool)) public mythicApproved;
// Whether a mythic is tradable
mapping(uint16 => bool) public mythicTradable;
// Map whether a mythic exists or not
mapping(uint16 => bool) public mythicCreated;
uint16 public constant mythic_threshold683 = 65000; //inject NONSTANDARD NAMING
constructor(
uint256 _batchSize,
string memory _name,
string memory _symbol
)
public
BatchToken(_batchSize, _name, _symbol)
{
cardProtos.length = max_length549;
cardQualities.length = max_length549;
protoToSeason.length = max_length549;
protos.length = max_length549;
propertyManager = msg.sender;
}
function GETDETAILS612( //inject NONSTANDARD NAMING
uint256 tokenId
)
public
view
returns (uint16 proto, uint8 quality)
{
return (cardProtos[tokenId], cardQualities[tokenId]);
}
function MINTCARD737( //inject NONSTANDARD NAMING
address to,
uint16 _proto,
uint8 _quality
)
public
returns (uint id)
{
id = _BATCHMINT199(to, 1);
_VALIDATEPROTO247(_proto);
cardProtos[id] = _proto;
cardQualities[id] = _quality;
uint16[] memory ps = new uint16[](1);
ps[0] = _proto;
uint8[] memory qs = new uint8[](1);
qs[0] = _quality;
emit CARDSMINTED263(id, to, ps, qs);
return id;
}
function MINTCARDS596( //inject NONSTANDARD NAMING
address to,
uint16[] memory _protos,
uint8[] memory _qualities
)
public
returns (uint)
{
require(
_protos.length > 0,
"Core: must be some protos"
);
require(
_protos.length == _qualities.length,
"Core: must be the same number of protos/qualities"
);
uint256 start = _BATCHMINT199(to, uint16(_protos.length));
_VALIDATEANDSAVEDETAILS366(start, _protos, _qualities);
emit CARDSMINTED263(start, to, _protos, _qualities);
return start;
}
function ADDFACTORY224( //inject NONSTANDARD NAMING
address _factory,
uint256 _season
)
public
ONLYOWNER453
{
require(
seasons.length >= _season,
"Core: season must exist"
);
require(
_season > 0,
"Core: season must not be 0"
);
require(
!factoryApproved[_factory][_season],
"Core: this factory is already approved"
);
require(
!seasonTradable[_season],
"Core: season must not be tradable"
);
factoryApproved[_factory][_season] = true;
}
function APPROVEFORMYTHIC801( //inject NONSTANDARD NAMING
address _factory,
uint16 _mythic
)
public
ONLYOWNER453
{
require(
_mythic >= mythic_threshold683,
"not a mythic"
);
require(
!mythicApproved[_mythic][_factory],
"Core: this factory is already approved for this mythic"
);
mythicApproved[_mythic][_factory] = true;
}
function MAKEMYTHICTRADABLE762( //inject NONSTANDARD NAMING
uint16 _mythic
)
public
ONLYOWNER453
{
require(
_mythic >= mythic_threshold683,
"Core: not a mythic"
);
require(
!mythicTradable[_mythic],
"Core: must not be tradable already"
);
mythicTradable[_mythic] = true;
}
function UNLOCKTRADING32( //inject NONSTANDARD NAMING
uint256 _season
)
public
ONLYOWNER453
{
require(
_season > 0 && _season <= seasons.length,
"Core: must be a current season"
);
require(
!seasonTradable[_season],
"Core: season must not be tradable"
);
seasonTradable[_season] = true;
}
function _TRANSFERFROM539( //inject NONSTANDARD NAMING
address from,
address to,
uint256 tokenId
)
internal
{
require(
ISTRADABLE528(tokenId),
"Core: not yet tradable"
);
super._TRANSFERFROM539(from, to, tokenId);
}
function BURN6(uint256 _tokenId) public { //inject NONSTANDARD NAMING
require(
ISTRADABLE528(_tokenId),
"Core: not yet tradable"
);
super._BURN121(_tokenId);
}
function BURNALL763(uint256[] memory tokenIDs) public { //inject NONSTANDARD NAMING
for (uint256 i = 0; i < tokenIDs.length; i++) {
BURN6(tokenIDs[i]);
}
}
function ISTRADABLE528(uint256 _tokenId) public view returns (bool) { //inject NONSTANDARD NAMING
uint16 proto = cardProtos[_tokenId];
if (proto >= mythic_threshold683) {
return mythicTradable[proto];
}
return seasonTradable[protoToSeason[proto]];
}
function STARTSEASON259( //inject NONSTANDARD NAMING
string memory name,
uint16 low,
uint16 high
)
public
ONLYOWNER453
returns (uint)
{
require(
low > 0,
"Core: must not be zero proto"
);
require(
high > low,
"Core: must be a valid range"
);
require(
seasons.length == 0 || low > seasons[seasons.length - 1].high,
"Core: seasons cannot overlap"
);
require(
mythic_threshold683 > high,
"Core: cannot go into mythic territory"
);
// seasons start at 1
uint16 id = uint16(seasons.push(Season({ high: high, low: low })));
uint256 cp;
assembly { cp := protoToSeason_slot }
StorageWrite.REPEATUINT16794(cp, low, (high - low) + 1, id);
emit SEASONSTARTED899(id, name, low, high);
return id;
}
function UPDATEPROTOS359( //inject NONSTANDARD NAMING
uint16[] memory _ids,
uint8[] memory _gods,
uint8[] memory _cardTypes,
uint8[] memory _rarities,
uint8[] memory _manas,
uint8[] memory _attacks,
uint8[] memory _healths,
uint8[] memory _tribes
) public ONLYOWNER453 {
for (uint256 i = 0; i < _ids.length; i++) {
uint16 id = _ids[i];
require(
id > 0,
"Core: proto must not be zero"
);
Proto memory proto = protos[id];
require(
!proto.locked,
"Core: proto is locked"
);
protos[id] = Proto({
locked: false,
exists: true,
god: _gods[i],
cardType: _cardTypes[i],
rarity: _rarities[i],
mana: _manas[i],
attack: _attacks[i],
health: _healths[i],
tribe: _tribes[i]
});
emit PROTOUPDATED864(id);
}
}
function LOCKPROTOS122(uint16[] memory _ids) public ONLYOWNER453 { //inject NONSTANDARD NAMING
require(
_ids.length > 0,
"must lock some"
);
for (uint256 i = 0; i < _ids.length; i++) {
uint16 id = _ids[i];
require(
id > 0,
"proto must not be zero"
);
Proto storage proto = protos[id];
require(
!proto.locked,
"proto is locked"
);
require(
proto.exists,
"proto must exist"
);
proto.locked = true;
emit PROTOUPDATED864(id);
}
}
function _VALIDATEANDSAVEDETAILS366( //inject NONSTANDARD NAMING
uint256 start,
uint16[] memory _protos,
uint8[] memory _qualities
)
internal
{
_VALIDATEPROTOS731(_protos);
uint256 cp;
assembly { cp := cardProtos_slot }
StorageWrite.UINT16S436(cp, start, _protos);
uint256 cq;
assembly { cq := cardQualities_slot }
StorageWrite.UINT8S318(cq, start, _qualities);
}
function _VALIDATEPROTO247(uint16 proto) internal { //inject NONSTANDARD NAMING
if (proto >= mythic_threshold683) {
_CHECKCANCREATEMYTHIC255(proto);
} else {
uint256 season = protoToSeason[proto];
require(
season != 0,
"Core: must have season set"
);
require(
factoryApproved[msg.sender][season],
"Core: must be approved factory for this season"
);
}
}
function _VALIDATEPROTOS731(uint16[] memory _protos) internal { //inject NONSTANDARD NAMING
uint16 maxProto = 0;
uint16 minProto = max_uint16315;
for (uint256 i = 0; i < _protos.length; i++) {
uint16 proto = _protos[i];
if (proto >= mythic_threshold683) {
_CHECKCANCREATEMYTHIC255(proto);
} else {
if (proto > maxProto) {
maxProto = proto;
}
if (minProto > proto) {
minProto = proto;
}
}
}
if (maxProto != 0) {
uint256 season = protoToSeason[maxProto];
// cards must be from the same season
require(
season != 0,
"Core: must have season set"
);
require(
season == protoToSeason[minProto],
"Core: can only create cards from the same season"
);
require(
factoryApproved[msg.sender][season],
"Core: must be approved factory for this season"
);
}
}
function _CHECKCANCREATEMYTHIC255(uint16 proto) internal { //inject NONSTANDARD NAMING
require(
mythicApproved[proto][msg.sender],
"Core: not approved to create this mythic"
);
require(
!mythicCreated[proto],
"Core: mythic has already been created"
);
mythicCreated[proto] = true;
}
function SETQUALITY366( //inject NONSTANDARD NAMING
uint256 _tokenId,
uint8 _quality
)
public
{
uint16 proto = cardProtos[_tokenId];
// wont' be able to change mythic season
uint256 season = protoToSeason[proto];
require(
factoryApproved[msg.sender][season],
"Core: factory can't change quality of this season"
);
cardQualities[_tokenId] = _quality;
emit QUALITYCHANGED816(_tokenId, _quality, msg.sender);
}
function SETPROPERTYMANAGER70(address _manager) public ONLYOWNER453 { //inject NONSTANDARD NAMING
propertyManager = _manager;
}
function SETPROPERTY942(uint256 _id, bytes32 _key, bytes32 _value) public { //inject NONSTANDARD NAMING
require(
msg.sender == propertyManager,
"Core: must be property manager"
);
_SETPROPERTY292(_id, _key, _value);
}
function SETCLASSPROPERTY520(bytes32 _key, bytes32 _value) public { //inject NONSTANDARD NAMING
require(
msg.sender == propertyManager,
"Core: must be property manager"
);
_SETCLASSPROPERTY718(_key, _value);
}
string public baseURI = "https://api.immutable.com/asset/";
function SETBASEURI249(string memory uri) public ONLYOWNER453 { //inject NONSTANDARD NAMING
baseURI = uri;
}
function TOKENURI642(uint256 tokenId) external view returns (string memory) { //inject NONSTANDARD NAMING
return string(abi.encodePacked(
baseURI,
String.FROMADDRESS777(address(this)),
"/",
String.FROMUINT947(tokenId)
));
}
}
// solium-disable security/no-inline-assembly
contract Cards is Ownable, MultiTransfer, BatchToken, ImmutableToken, InscribableToken {
uint16 private constant max_uint16315 = 2**16 - 1; //inject NONSTANDARD NAMING
uint16[] public cardProtos;
uint8[] public cardQualities;
struct Season {
uint16 high;
uint16 low;
}
struct Proto {
bool locked;
bool exists;
uint8 god;
uint8 cardType;
uint8 rarity;
uint8 mana;
uint8 attack;
uint8 health;
uint8 tribe;
}
event PROTOUPDATED864( //inject NONSTANDARD NAMING
uint16 indexed id
);
event SEASONSTARTED899( //inject NONSTANDARD NAMING
uint16 indexed id,
string name,
uint16 indexed low,
uint16 indexed high
);
event QUALITYCHANGED816( //inject NONSTANDARD NAMING
uint256 indexed tokenId,
uint8 quality,
address factory
);
event CARDSMINTED263( //inject NONSTANDARD NAMING
uint256 indexed start,
address to,
uint16[] protos,
uint8[] qualities
);
// Value of index proto = season
uint16[] public protoToSeason;
address public propertyManager;
// Array containing all protos
Proto[] public protos;
// Array containing all seasons
Season[] public seasons;
// Map whether a season is tradeable or not
mapping(uint256 => bool) public seasonTradable;
// Map whether a factory has been authorised or not
mapping(address => mapping(uint256 => bool)) public factoryApproved;
// Whether a factory is approved to create a particular mythic
mapping(uint16 => mapping(address => bool)) public mythicApproved;
// Whether a mythic is tradable
mapping(uint16 => bool) public mythicTradable;
// Map whether a mythic exists or not
mapping(uint16 => bool) public mythicCreated;
uint16 public constant mythic_threshold683 = 65000; //inject NONSTANDARD NAMING
constructor(
uint256 _batchSize,
string memory _name,
string memory _symbol
)
public
BatchToken(_batchSize, _name, _symbol)
{
cardProtos.length = max_length549;
cardQualities.length = max_length549;
protoToSeason.length = max_length549;
protos.length = max_length549;
propertyManager = msg.sender;
}
function GETDETAILS612( //inject NONSTANDARD NAMING
uint256 tokenId
)
public
view
returns (uint16 proto, uint8 quality)
{
return (cardProtos[tokenId], cardQualities[tokenId]);
}
function MINTCARD737( //inject NONSTANDARD NAMING
address to,
uint16 _proto,
uint8 _quality
)
external
returns (uint id)
{
id = _BATCHMINT199(to, 1);
_VALIDATEPROTO247(_proto);
cardProtos[id] = _proto;
cardQualities[id] = _quality;
uint16[] memory ps = new uint16[](1);
ps[0] = _proto;
uint8[] memory qs = new uint8[](1);
qs[0] = _quality;
emit CARDSMINTED263(id, to, ps, qs);
return id;
}
function MINTCARDS596( //inject NONSTANDARD NAMING
address to,
uint16[] calldata _protos,
uint8[] calldata _qualities
)
external
returns (uint)
{
require(
_protos.length > 0,
"Core: must be some protos"
);
require(
_protos.length == _qualities.length,
"Core: must be the same number of protos/qualities"
);
uint256 start = _BATCHMINT199(to, uint16(_protos.length));
_VALIDATEANDSAVEDETAILS366(start, _protos, _qualities);
emit CARDSMINTED263(start, to, _protos, _qualities);
return start;
}
function ADDFACTORY224( //inject NONSTANDARD NAMING
address _factory,
uint256 _season
)
public
ONLYOWNER453
{
require(
seasons.length >= _season,
"Core: season must exist"
);
require(
_season > 0,
"Core: season must not be 0"
);
require(
!factoryApproved[_factory][_season],
"Core: this factory is already approved"
);
require(
!seasonTradable[_season],
"Core: season must not be tradable"
);
factoryApproved[_factory][_season] = true;
}
function APPROVEFORMYTHIC801( //inject NONSTANDARD NAMING
address _factory,
uint16 _mythic
)
public
ONLYOWNER453
{
require(
_mythic >= mythic_threshold683,
"not a mythic"
);
require(
!mythicApproved[_mythic][_factory],
"Core: this factory is already approved for this mythic"
);
mythicApproved[_mythic][_factory] = true;
}
function MAKEMYTHICTRADABLE762( //inject NONSTANDARD NAMING
uint16 _mythic
)
public
ONLYOWNER453
{
require(
_mythic >= mythic_threshold683,
"Core: not a mythic"
);
require(
!mythicTradable[_mythic],
"Core: must not be tradable already"
);
mythicTradable[_mythic] = true;
}
function UNLOCKTRADING32( //inject NONSTANDARD NAMING
uint256 _season
)
public
ONLYOWNER453
{
require(
_season > 0 && _season <= seasons.length,
"Core: must be a current season"
);
require(
!seasonTradable[_season],
"Core: season must not be tradable"
);
seasonTradable[_season] = true;
}
function TRANSFERFROM301( //inject NONSTANDARD NAMING
address from,
address to,
uint256 tokenId
)
public
{
require(
ISTRADABLE528(tokenId),
"Core: not yet tradable"
);
super.TRANSFERFROM301(from, to, tokenId);
}
function BURN6(uint256 _tokenId) public { //inject NONSTANDARD NAMING
require(
ISTRADABLE528(_tokenId),
"Core: not yet tradable"
);
super._BURN121(_tokenId);
}
function BURNALL763(uint256[] memory tokenIDs) public { //inject NONSTANDARD NAMING
for (uint256 i = 0; i < tokenIDs.length; i++) {
BURN6(tokenIDs[i]);
}
}
function ISTRADABLE528(uint256 _tokenId) public view returns (bool) { //inject NONSTANDARD NAMING
uint16 proto = cardProtos[_tokenId];
if (proto >= mythic_threshold683) {
return mythicTradable[proto];
}
return seasonTradable[protoToSeason[proto]];
}
function STARTSEASON259( //inject NONSTANDARD NAMING
string memory name,
uint16 low,
uint16 high
)
public
ONLYOWNER453
returns (uint)
{
require(
low > 0,
"Core: must not be zero proto"
);
require(
high > low,
"Core: must be a valid range"
);
require(
seasons.length == 0 || low > seasons[seasons.length - 1].high,
"Core: seasons cannot overlap"
);
require(
mythic_threshold683 > high,
"Core: cannot go into mythic territory"
);
// seasons start at 1
uint16 id = uint16(seasons.push(Season({ high: high, low: low })));
uint256 cp;
assembly { cp := protoToSeason_slot }
StorageWrite.REPEATUINT16794(cp, low, (high - low) + 1, id);
emit SEASONSTARTED899(id, name, low, high);
return id;
}
function UPDATEPROTOS359( //inject NONSTANDARD NAMING
uint16[] memory _ids,
uint8[] memory _gods,
uint8[] memory _cardTypes,
uint8[] memory _rarities,
uint8[] memory _manas,
uint8[] memory _attacks,
uint8[] memory _healths,
uint8[] memory _tribes
) public ONLYOWNER453 {
for (uint256 i = 0; i < _ids.length; i++) {
uint16 id = _ids[i];
require(
id > 0,
"Core: proto must not be zero"
);
Proto memory proto = protos[id];
require(
!proto.locked,
"Core: proto is locked"
);
protos[id] = Proto({
locked: false,
exists: true,
god: _gods[i],
cardType: _cardTypes[i],
rarity: _rarities[i],
mana: _manas[i],
attack: _attacks[i],
health: _healths[i],
tribe: _tribes[i]
});
emit PROTOUPDATED864(id);
}
}
function LOCKPROTOS122(uint16[] memory _ids) public ONLYOWNER453 { //inject NONSTANDARD NAMING
require(
_ids.length > 0,
"must lock some"
);
for (uint256 i = 0; i < _ids.length; i++) {
uint16 id = _ids[i];
require(
id > 0,
"proto must not be zero"
);
Proto storage proto = protos[id];
require(
!proto.locked,
"proto is locked"
);
require(
proto.exists,
"proto must exist"
);
proto.locked = true;
emit PROTOUPDATED864(id);
}
}
function _VALIDATEANDSAVEDETAILS366( //inject NONSTANDARD NAMING
uint256 start,
uint16[] memory _protos,
uint8[] memory _qualities
)
internal
{
_VALIDATEPROTOS731(_protos);
uint256 cp;
assembly { cp := cardProtos_slot }
StorageWrite.UINT16S436(cp, start, _protos);
uint256 cq;
assembly { cq := cardQualities_slot }
StorageWrite.UINT8S318(cq, start, _qualities);
}
function _VALIDATEPROTO247(uint16 proto) internal { //inject NONSTANDARD NAMING
if (proto >= mythic_threshold683) {
_CHECKCANCREATEMYTHIC255(proto);
} else {
uint256 season = protoToSeason[proto];
require(
season != 0,
"Core: must have season set"
);
require(
factoryApproved[msg.sender][season],
"Core: must be approved factory for this season"
);
}
}
function _VALIDATEPROTOS731(uint16[] memory _protos) internal { //inject NONSTANDARD NAMING
uint16 maxProto = 0;
uint16 minProto = max_uint16315;
for (uint256 i = 0; i < _protos.length; i++) {
uint16 proto = _protos[i];
if (proto >= mythic_threshold683) {
_CHECKCANCREATEMYTHIC255(proto);
} else {
if (proto > maxProto) {
maxProto = proto;
}
if (minProto > proto) {
minProto = proto;
}
}
}
if (maxProto != 0) {
uint256 season = protoToSeason[maxProto];
// cards must be from the same season
require(
season != 0,
"Core: must have season set"
);
require(
season == protoToSeason[minProto],
"Core: can only create cards from the same season"
);
require(
factoryApproved[msg.sender][season],
"Core: must be approved factory for this season"
);
}
}
function _CHECKCANCREATEMYTHIC255(uint16 proto) internal { //inject NONSTANDARD NAMING
require(
mythicApproved[proto][msg.sender],
"Core: not approved to create this mythic"
);
require(
!mythicCreated[proto],
"Core: mythic has already been created"
);
mythicCreated[proto] = true;
}
function SETQUALITY366( //inject NONSTANDARD NAMING
uint256 _tokenId,
uint8 _quality
)
public
{
uint16 proto = cardProtos[_tokenId];
// wont' be able to change mythic season
uint256 season = protoToSeason[proto];
require(
factoryApproved[msg.sender][season],
"Core: factory can't change quality of this season"
);
cardQualities[_tokenId] = _quality;
emit QUALITYCHANGED816(_tokenId, _quality, msg.sender);
}
function SETPROPERTYMANAGER70(address _manager) public ONLYOWNER453 { //inject NONSTANDARD NAMING
propertyManager = _manager;
}
function SETPROPERTY942(uint256 _id, bytes32 _key, bytes32 _value) public { //inject NONSTANDARD NAMING
require(
msg.sender == propertyManager,
"Core: must be property manager"
);
_SETPROPERTY292(_id, _key, _value);
}
function SETCLASSPROPERTY520(bytes32 _key, bytes32 _value) public { //inject NONSTANDARD NAMING
require(
msg.sender == propertyManager,
"Core: must be property manager"
);
_SETCLASSPROPERTY718(_key, _value);
}
}
contract BatchWrapper is NewCards {
uint16 private constant max_uint16315 = 2**16 - 1; //inject NONSTANDARD NAMING
Cards public old;
bool public migrating;
constructor(
Cards _old,
uint256 _batchSize,
string memory _name,
string memory _symbol
) public NewCards(_batchSize, _name, _symbol) {
old = _old;
}
function SETMIGRATING202(bool _migrating) public ONLYOWNER453 { //inject NONSTANDARD NAMING
migrating = _migrating;
}
function COPYUNTIL891(uint gasThreshold) public { //inject NONSTANDARD NAMING
while (gasleft() > gasThreshold) {
COPYNEXTBATCH144();
}
}
function MINTCARDS596(address _to, uint16[] memory _protos, uint8[] memory _qualities) public returns (uint id) { //inject NONSTANDARD NAMING
require(!migrating, "must not be migrating");
super.MINTCARDS596(_to, _protos, _qualities);
}
function MINTCARD737(address _to, uint16 _proto, uint8 _quality) public returns (uint id) { //inject NONSTANDARD NAMING
require(!migrating, "must not be migrating");
super.MINTCARD737(_to, _proto, _quality);
}
// copy all batches from the old contracts
// leave ids intact
function COPYNEXTBATCH144() public { //inject NONSTANDARD NAMING
require(migrating, "must be migrating");
uint256 start = nextBatch;
(uint48 userID, uint16 size) = old.batches(start);
require(size > 0 && userID > 0, "incorrect batch or limit reached");
if (old.cardProtos(start) != 0) {
address to = old.userIDToAddress(userID);
uint48 uID = _GETUSERID7(to);
batches[start] = Batch({
userID: uID,
size: size
});
uint256 end = start.ADD640(size);
for (uint256 i = start; i < end; i++) {
emit TRANSFER336(address(0), to, i);
}
_balances[to] = _balances[to].ADD640(size);
tokenCount = tokenCount.ADD640(size);
}
nextBatch = nextBatch.ADD640(batchSize);
}
function ISOLD374(uint _tokenId) public view returns (bool) { //inject NONSTANDARD NAMING
require(_EXISTS289(_tokenId), "card does not exist");
return cardProtos[_tokenId] == 0;
}
function GETPROTO912(uint _tokenId) public view returns (uint16) { //inject NONSTANDARD NAMING
return ISOLD374(_tokenId) ? old.cardProtos(_tokenId) : cardProtos[_tokenId];
}
function GETQUALITY41(uint _tokenId) public view returns (uint8) { //inject NONSTANDARD NAMING
return ISOLD374(_tokenId) ? old.cardQualities(_tokenId) : cardQualities[_tokenId];
}
function GETDETAILS612(uint256 tokenId) public view returns (uint16 proto, uint8 quality) { //inject NONSTANDARD NAMING
return ISOLD374(tokenId) ? old.GETDETAILS612(tokenId) : (cardProtos[tokenId], cardQualities[tokenId]);
}
function ISTRADABLE528(uint256 _tokenId) public view returns (bool) { //inject NONSTANDARD NAMING
uint16 proto = GETPROTO912(_tokenId);
if (proto >= mythic_threshold683) {
return mythicTradable[proto];
}
return seasonTradable[protoToSeason[proto]];
}
function _TRANSFERFROM539(address from, address to, uint tokenId) internal { //inject NONSTANDARD NAMING
require(
ISTRADABLE528(tokenId),
"BW: not yet tradable"
);
super._TRANSFERFROM539(from, to, tokenId);
}
// update validate protos to check if a proto is 0
// prevent untradable cards
function _VALIDATEPROTOS731(uint16[] memory _protos) internal { //inject NONSTANDARD NAMING
uint16 maxProto = 0;
uint16 minProto = max_uint16315;
for (uint256 i = 0; i < _protos.length; i++) {
uint16 proto = _protos[i];
if (proto >= mythic_threshold683) {
_CHECKCANCREATEMYTHIC255(proto);
} else {
require(proto != 0, "proto is zero");
if (proto > maxProto) {
maxProto = proto;
}
if (minProto > proto) {
minProto = proto;
}
}
}
if (maxProto != 0) {
uint256 season = protoToSeason[maxProto];
// cards must be from the same season
require(
season != 0,
"Core: must have season set"
);
require(
season == protoToSeason[minProto],
"Core: can only create cards from the same season"
);
require(
factoryApproved[msg.sender][season],
"Core: must be approved factory for this season"
);
}
}
} | inject NONSTANDARD NAMING
| function GETBATCH853(uint256 index) public view returns (uint48 userID, uint16 size) { | 2,483,558 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4978,
25147,
7140,
23,
12,
11890,
5034,
770,
13,
1071,
1476,
1135,
261,
11890,
8875,
16299,
16,
2254,
2313,
963,
13,
288,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.19;
/*
Game: CryptoPokemon
Domain: CryptoPokemon.com
Dev: CryptoPokemon Team
*/
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;
}
}
contract CryptoPokemon {
using SafeMath for uint256;
mapping (address => bool) private admins;
mapping (uint => uint256) public levels;
mapping (uint => bool) private lock;
address contractCreator;
address devFeeAddress;
address tournamentPrizeAddress;
function CryptoPokemon () public {
contractCreator = msg.sender;
devFeeAddress = 0xFb2D26b0caa4C331bd0e101460ec9dbE0A4783A4;
tournamentPrizeAddress = 0xC6784e712229087fC91E0c77fcCb6b2F1fDE2Dc2;
admins[contractCreator] = true;
}
struct Pokemon {
string pokemonName;
address ownerAddress;
uint256 currentPrice;
}
Pokemon[] pokemons;
//modifiers
modifier onlyContractCreator() {
require (msg.sender == contractCreator);
_;
}
modifier onlyAdmins() {
require(admins[msg.sender]);
_;
}
//Owners and admins
/* Owner */
function setOwner (address _owner) onlyContractCreator() public {
contractCreator = _owner;
}
function addAdmin (address _admin) onlyContractCreator() public {
admins[_admin] = true;
}
function removeAdmin (address _admin) onlyContractCreator() public {
delete admins[_admin];
}
// Adresses
function setdevFeeAddress (address _devFeeAddress) onlyContractCreator() public {
devFeeAddress = _devFeeAddress;
}
function settournamentPrizeAddress (address _tournamentPrizeAddress) onlyContractCreator() public {
tournamentPrizeAddress = _tournamentPrizeAddress;
}
bool isPaused;
/*
When countdowns and events happening, use the checker.
*/
function pauseGame() public onlyContractCreator {
isPaused = true;
}
function unPauseGame() public onlyContractCreator {
isPaused = false;
}
function GetGamestatus() public view returns(bool) {
return(isPaused);
}
function addLock (uint _pokemonId) onlyContractCreator() public {
lock[_pokemonId] = true;
}
function removeLock (uint _pokemonId) onlyContractCreator() public {
lock[_pokemonId] = false;
}
function getPokemonLock(uint _pokemonId) public view returns(bool) {
return(lock[_pokemonId]);
}
/*
This function allows users to purchase PokeMon.
The price is automatically multiplied by 1.5 after each purchase.
Users can purchase multiple PokeMon.
*/
function purchasePokemon(uint _pokemonId) public payable {
// Check new price >= currentPrice & gameStatus
require(msg.value >= pokemons[_pokemonId].currentPrice);
require(pokemons[_pokemonId].ownerAddress != address(0));
require(pokemons[_pokemonId].ownerAddress != msg.sender);
require(lock[_pokemonId] == false);
require(msg.sender != address(0));
require(isPaused == false);
// Calculate the excess
address newOwner = msg.sender;
uint256 price = pokemons[_pokemonId].currentPrice;
uint256 excess = msg.value.sub(price);
uint256 realValue = pokemons[_pokemonId].currentPrice;
// If excess>0 send back the amount
if (excess > 0) {
newOwner.transfer(excess);
}
// Calculate the 10% value as tournment prize and dev fee
uint256 cutFee = realValue.div(10);
// Calculate the pokemon owner commission on this sale & transfer the commission to the owner.
uint256 commissionOwner = realValue - cutFee; // => 90%
pokemons[_pokemonId].ownerAddress.transfer(commissionOwner);
// Transfer the 5% commission to the developer & %5 to tournamentPrizeAddress
devFeeAddress.transfer(cutFee.div(2)); // => 10%
tournamentPrizeAddress.transfer(cutFee.div(2));
// Update the hero owner and set the new price
pokemons[_pokemonId].ownerAddress = msg.sender;
pokemons[_pokemonId].currentPrice = pokemons[_pokemonId].currentPrice.mul(3).div(2);
levels[_pokemonId] = levels[_pokemonId] + 1;
}
// This function will return all of the details of the pokemons
function getPokemonDetails(uint _pokemonId) public view returns (
string pokemonName,
address ownerAddress,
uint256 currentPrice
) {
Pokemon storage _pokemon = pokemons[_pokemonId];
pokemonName = _pokemon.pokemonName;
ownerAddress = _pokemon.ownerAddress;
currentPrice = _pokemon.currentPrice;
}
// This function will return only the price of a specific pokemon
function getPokemonCurrentPrice(uint _pokemonId) public view returns(uint256) {
return(pokemons[_pokemonId].currentPrice);
}
// This function will return only the owner address of a specific pokemon
function getPokemonOwner(uint _pokemonId) public view returns(address) {
return(pokemons[_pokemonId].ownerAddress);
}
// This function will return only the levels of pokemons
function getPokemonLevel(uint _pokemonId) public view returns(uint256) {
return(levels[_pokemonId]);
}
// delete function, used when bugs comeout
function deletePokemon(uint _pokemonId) public onlyContractCreator() {
delete pokemons[_pokemonId];
delete pokemons[_pokemonId];
delete lock[_pokemonId];
}
// Set function, used when bugs comeout
function setPokemon(uint _pokemonId, string _pokemonName, address _ownerAddress, uint256 _currentPrice, uint256 _levels) public onlyContractCreator() {
pokemons[_pokemonId].ownerAddress = _ownerAddress;
pokemons[_pokemonId].pokemonName = _pokemonName;
pokemons[_pokemonId].currentPrice = _currentPrice;
levels[_pokemonId] = _levels;
lock[_pokemonId] = false;
}
// This function will be used to add a new hero by the contract creator
function addPokemon(string pokemonName, address ownerAddress, uint256 currentPrice) public onlyAdmins {
pokemons.push(Pokemon(pokemonName,ownerAddress,currentPrice));
levels[pokemons.length - 1] = 0;
lock[pokemons.length - 1] = false;
}
function totalSupply() public view returns (uint256 _totalSupply) {
return pokemons.length;
}
} | This function will return all of the details of the pokemons | function getPokemonDetails(uint _pokemonId) public view returns (
string pokemonName,
address ownerAddress,
uint256 currentPrice
) {
Pokemon storage _pokemon = pokemons[_pokemonId];
pokemonName = _pokemon.pokemonName;
ownerAddress = _pokemon.ownerAddress;
currentPrice = _pokemon.currentPrice;
}
| 6,666,341 | [
1,
2503,
445,
903,
327,
777,
434,
326,
3189,
434,
326,
293,
601,
4758,
87,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
915,
1689,
601,
4758,
3790,
12,
11890,
389,
84,
601,
4758,
548,
13,
1071,
1476,
1135,
261,
203,
1080,
293,
601,
4758,
461,
16,
203,
2867,
3410,
1887,
16,
203,
11890,
5034,
783,
5147,
203,
13,
288,
203,
52,
601,
4758,
2502,
389,
84,
601,
4758,
273,
293,
601,
4758,
87,
63,
67,
84,
601,
4758,
548,
15533,
203,
203,
84,
601,
4758,
461,
273,
389,
84,
601,
4758,
18,
84,
601,
4758,
461,
31,
203,
8443,
1887,
273,
389,
84,
601,
4758,
18,
8443,
1887,
31,
203,
2972,
5147,
273,
389,
84,
601,
4758,
18,
2972,
5147,
31,
203,
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
] |
./full_match/43113/0xB7b593a46dDBb9288Bc9A98041866F84b515952E/sources/contracts/aaaaaaa.sol | * @notice approves contract and moons Yak to mini Yak (mints mini Yak ) @param amount amount of YAK that will be mooned @param to address of caller or the address to which miniYAK would be transferred to/ | function moonWithPermit(uint amount, address to, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
IERC20Permit(YAK).permit(msg.sender, address(this), amount, deadline, v, r, s);
uint mint_amount = Math.min(amount, IERC20(YAK).balanceOf(msg.sender));
IERC20(YAK).safeTransferFrom(msg.sender,address(this),mint_amount);
_mint(to, mint_amount);
}
| 7,135,078 | [
1,
12908,
3324,
6835,
471,
7344,
7008,
1624,
581,
358,
21959,
1624,
581,
261,
81,
28142,
21959,
1624,
581,
262,
225,
3844,
3844,
434,
1624,
14607,
716,
903,
506,
7344,
8184,
225,
358,
1758,
434,
4894,
578,
326,
1758,
358,
1492,
21959,
61,
14607,
4102,
506,
906,
4193,
358,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7344,
265,
1190,
9123,
305,
12,
11890,
3844,
16,
1758,
358,
16,
2254,
14096,
16,
2254,
28,
331,
16,
1731,
1578,
436,
16,
1731,
1578,
272,
13,
3903,
288,
203,
3639,
467,
654,
39,
3462,
9123,
305,
12,
61,
14607,
2934,
457,
1938,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
3844,
16,
14096,
16,
331,
16,
436,
16,
272,
1769,
203,
3639,
2254,
312,
474,
67,
8949,
273,
2361,
18,
1154,
12,
8949,
16,
467,
654,
39,
3462,
12,
61,
14607,
2934,
12296,
951,
12,
3576,
18,
15330,
10019,
203,
3639,
467,
654,
39,
3462,
12,
61,
14607,
2934,
4626,
5912,
1265,
12,
3576,
18,
15330,
16,
2867,
12,
2211,
3631,
81,
474,
67,
8949,
1769,
203,
3639,
389,
81,
474,
12,
869,
16,
312,
474,
67,
8949,
1769,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.16;
import "../core/BasicDocument.sol";
import "../core/RevokableDocument.sol";
import "../core/TransfarableDocument.sol";
/**
* @title PublicDocument
* @dev Anyone who knows the contract address can issue and revoke documents.
*/
contract PublicDocument is BasicDocument, RevokableDocument, TransfarableDocument {
/**
* @dev Returns document's information.
* @dev Can be called by anyone who knows the contract address.
*/
function getDocument(bytes32 document) public constant returns (address, address, uint256) {
return (documents[document].issuer, documents[document].recipient, documents[document].block);
}
/**
* @dev Verifies if the document belongs to the given recipient.
*/
function verifyDocument(address recipient, bytes32 document) public constant returns (bool) {
return recipient != address(0) && documents[document].recipient == recipient;
}
/**
* @dev This contract accepts donations.
*/
function () payable public {
require(msg.value > 0);
owner.transfer(msg.value);
}
/**
* Forwards all funds to the owner account.
*/
function widthraw() onlyOwner external {
owner.transfer(this.balance);
}
} | * @title PublicDocument @dev Anyone who knows the contract address can issue and revoke documents./ | contract PublicDocument is BasicDocument, RevokableDocument, TransfarableDocument {
function getDocument(bytes32 document) public constant returns (address, address, uint256) {
return (documents[document].issuer, documents[document].recipient, documents[document].block);
}
function verifyDocument(address recipient, bytes32 document) public constant returns (bool) {
return recipient != address(0) && documents[document].recipient == recipient;
}
function () payable public {
require(msg.value > 0);
owner.transfer(msg.value);
}
function widthraw() onlyOwner external {
owner.transfer(this.balance);
}
} | 14,104,715 | [
1,
4782,
2519,
225,
5502,
476,
10354,
21739,
326,
6835,
1758,
848,
5672,
471,
18007,
7429,
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
] | [
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,
16351,
7224,
2519,
353,
7651,
2519,
16,
14477,
601,
429,
2519,
16,
2604,
31246,
429,
2519,
288,
203,
565,
445,
9956,
12,
3890,
1578,
1668,
13,
1071,
5381,
1135,
261,
2867,
16,
1758,
16,
2254,
5034,
13,
288,
203,
3639,
327,
261,
24795,
63,
5457,
8009,
17567,
16,
7429,
63,
5457,
8009,
20367,
16,
7429,
63,
5457,
8009,
2629,
1769,
203,
565,
289,
203,
377,
203,
565,
445,
3929,
2519,
12,
2867,
8027,
16,
1731,
1578,
1668,
13,
1071,
5381,
1135,
261,
6430,
13,
288,
203,
3639,
327,
8027,
480,
1758,
12,
20,
13,
597,
7429,
63,
5457,
8009,
20367,
422,
8027,
31,
203,
565,
289,
203,
203,
565,
445,
1832,
8843,
429,
1071,
288,
203,
3639,
2583,
12,
3576,
18,
1132,
405,
374,
1769,
203,
3639,
3410,
18,
13866,
12,
3576,
18,
1132,
1769,
203,
565,
289,
203,
203,
565,
445,
1835,
1899,
1435,
1338,
5541,
3903,
288,
203,
3639,
3410,
18,
13866,
12,
2211,
18,
12296,
1769,
203,
565,
289,
203,
97,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.16;
import "./KToken.sol";
import "./KMCD.sol";
import "./ErrorReporter.sol";
import "./Exponential.sol";
import "./KineControllerInterface.sol";
import "./ControllerStorage.sol";
import "./Unitroller.sol";
import "./KineOracleInterface.sol";
import "./KineSafeMath.sol";
/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/Comptroller.sol
* Modified to work in the Kine system.
* Main modifications:
* 1. removed Comp token related logics.
* 2. removed interest rate model related logics.
* 3. simplified calculations in mint, redeem, liquidity check, seize due to we don't use interest model/exchange rate.
* 4. user can only supply kTokens (see KToken) and borrow Kine MCDs (see KMCD). Kine MCD's underlying can be considered as itself.
* 5. removed error code propagation mechanism, using revert to fail fast and loudly.
*/
/**
* @title Kine's Controller Contract
* @author Kine
*/
contract Controller is ControllerStorage, KineControllerInterface, Exponential, ControllerErrorReporter {
/// @notice Emitted when an admin supports a market
event MarketListed(KToken kToken);
/// @notice Emitted when an account enters a market
event MarketEntered(KToken kToken, address account);
/// @notice Emitted when an account exits a market
event MarketExited(KToken kToken, address account);
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);
/// @notice Emitted when a collateral factor is changed by admin
event NewCollateralFactor(KToken kToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);
/// @notice Emitted when price oracle is changed
event NewPriceOracle(KineOracleInterface oldPriceOracle, KineOracleInterface newPriceOracle);
/// @notice Emitted when pause guardian is changed
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
/// @notice Emitted when an action is paused globally
event ActionPaused(string action, bool pauseState);
/// @notice Emitted when an action is paused on a market
event ActionPaused(KToken kToken, string action, bool pauseState);
/// @notice Emitted when borrow cap for a kToken is changed
event NewBorrowCap(KToken indexed kToken, uint newBorrowCap);
/// @notice Emitted when supply cap for a kToken is changed
event NewSupplyCap(KToken indexed kToken, uint newSupplyCap);
/// @notice Emitted when borrow/supply cap guardian is changed
event NewCapGuardian(address oldCapGuardian, address newCapGuardian);
// closeFactorMantissa must be strictly greater than this value
uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05
// closeFactorMantissa must not exceed this value
uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9
// liquidationIncentiveMantissa must be no less than this value
uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0
// liquidationIncentiveMantissa must be no greater than this value
uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5
// No collateralFactorMantissa may exceed this value
uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9
constructor() public {
admin = msg.sender;
}
modifier onlyAdmin() {
require(msg.sender == admin, "only admin can call this function");
_;
}
/*** Assets You Are In ***/
/**
* @notice Returns the assets an account has entered
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account) external view returns (KToken[] memory) {
KToken[] memory assetsIn = accountAssets[account];
return assetsIn;
}
/**
* @notice Returns whether the given account is entered in the given asset
* @param account The address of the account to check
* @param kToken The kToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, KToken kToken) external view returns (bool) {
return markets[address(kToken)].accountMembership[account];
}
/**
* @notice Add assets to be included in account liquidity calculation
* @param kTokens The list of addresses of the kToken markets to be enabled
* @dev will revert if any market entering failed
*/
function enterMarkets(address[] memory kTokens) public {
uint len = kTokens.length;
for (uint i = 0; i < len; i++) {
KToken kToken = KToken(kTokens[i]);
addToMarketInternal(kToken, msg.sender);
}
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param kToken The market to enter
* @param borrower The address of the account to modify
*/
function addToMarketInternal(KToken kToken, address borrower) internal {
Market storage marketToJoin = markets[address(kToken)];
require(marketToJoin.isListed, MARKET_NOT_LISTED);
if (marketToJoin.accountMembership[borrower] == true) {
// already joined
return;
}
// survived the gauntlet, add to list
// NOTE: we store these somewhat redundantly as a significant optimization
// this avoids having to iterate through the list for the most common use cases
// that is, only when we need to perform liquidity checks
// and not whenever we want to check if an account is in a particular market
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(kToken);
emit MarketEntered(kToken, borrower);
}
/**
* @notice Removes asset from sender's account liquidity calculation
* @dev Sender must not have an outstanding borrow balance in the asset,
* or be providing necessary collateral for an outstanding borrow.
* @param kTokenAddress The address of the asset to be removed
*/
function exitMarket(address kTokenAddress) external {
KToken kToken = KToken(kTokenAddress);
/* Get sender tokensHeld and amountOwed underlying from the kToken */
(uint tokensHeld, uint amountOwed) = kToken.getAccountSnapshot(msg.sender);
/* Fail if the sender has a borrow balance */
require(amountOwed == 0, EXIT_MARKET_BALANCE_OWED);
/* Fail if the sender is not permitted to redeem all of their tokens */
(bool allowed,) = redeemAllowedInternal(kTokenAddress, msg.sender, tokensHeld);
require(allowed, EXIT_MARKET_REJECTION);
Market storage marketToExit = markets[address(kToken)];
/* Succeed true if the sender is not already ‘in’ the market */
if (!marketToExit.accountMembership[msg.sender]) {
return;
}
/* Set kToken account membership to false */
delete marketToExit.accountMembership[msg.sender];
/* Delete kToken from the account’s list of assets */
// load into memory for faster iteration
KToken[] memory userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint assetIndex = len;
for (uint i = 0; i < len; i++) {
if (userAssetList[i] == kToken) {
assetIndex = i;
break;
}
}
// We *must* have found the asset in the list or our redundant data structure is broken
require(assetIndex < len, "accountAssets array broken");
// copy last item in list to location of item to be removed, reduce length by 1
KToken[] storage storedList = accountAssets[msg.sender];
if (assetIndex != storedList.length - 1) {
storedList[assetIndex] = storedList[storedList.length - 1];
}
storedList.length--;
emit MarketExited(kToken, msg.sender);
}
/*** Policy Hooks ***/
/**
* @notice Checks if the account should be allowed to mint tokens in the given market
* @param kToken The market to verify the mint against
* @param minter The account which would get the minted tokens
* @param mintAmount The amount of underlying being supplied to the market in exchange for tokens
* @return false and reason if mint not allowed, otherwise return true and empty string
*/
function mintAllowed(address kToken, address minter, uint mintAmount) external returns (bool allowed, string memory reason) {
if (mintGuardianPaused[kToken]) {
allowed = false;
reason = MINT_PAUSED;
return (allowed, reason);
}
uint supplyCap = supplyCaps[kToken];
// Supply cap of 0 corresponds to unlimited supplying
if (supplyCap != 0) {
uint totalSupply = KToken(kToken).totalSupply();
uint nextTotalSupply = totalSupply.add(mintAmount);
if (nextTotalSupply > supplyCap) {
allowed = false;
reason = MARKET_SUPPLY_CAP_REACHED;
return (allowed, reason);
}
}
// Shh - currently unused
minter;
if (!markets[kToken].isListed) {
allowed = false;
reason = MARKET_NOT_LISTED;
return (allowed, reason);
}
allowed = true;
return (allowed, reason);
}
/**
* @notice Validates mint and reverts on rejection. May emit logs.
* @param kToken Asset being minted
* @param minter The address minting the tokens
* @param actualMintAmount The amount of the underlying asset being minted
* @param mintTokens The number of tokens being minted
*/
function mintVerify(address kToken, address minter, uint actualMintAmount, uint mintTokens) external {
// Shh - currently unused
kToken;
minter;
actualMintAmount;
mintTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param kToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of kTokens to exchange for the underlying asset in the market
* @return false and reason if redeem not allowed, otherwise return true and empty string
*/
function redeemAllowed(address kToken, address redeemer, uint redeemTokens) external returns (bool allowed, string memory reason) {
return redeemAllowedInternal(kToken, redeemer, redeemTokens);
}
/**
* @param kToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of kTokens to exchange for the underlying asset in the market
* @return false and reason if redeem not allowed, otherwise return true and empty string
*/
function redeemAllowedInternal(address kToken, address redeemer, uint redeemTokens) internal view returns (bool allowed, string memory reason) {
if (!markets[kToken].isListed) {
allowed = false;
reason = MARKET_NOT_LISTED;
return (allowed, reason);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[kToken].accountMembership[redeemer]) {
allowed = true;
return (allowed, reason);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(, uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, KToken(kToken), redeemTokens, 0);
if (shortfall > 0) {
allowed = false;
reason = INSUFFICIENT_LIQUIDITY;
return (allowed, reason);
}
allowed = true;
return (allowed, reason);
}
/**
* @notice Validates redeem and reverts on rejection. May emit logs.
* @param kToken Asset being redeemed
* @param redeemer The address redeeming the tokens
* @param redeemTokens The number of tokens being redeemed
*/
function redeemVerify(address kToken, address redeemer, uint redeemTokens) external {
// Shh - currently unused
kToken;
redeemer;
require(redeemTokens != 0, REDEEM_TOKENS_ZERO);
}
/**
* @notice Checks if the account should be allowed to borrow the underlying asset of the given market
* @param kToken The market to verify the borrow against
* @param borrower The account which would borrow the asset
* @param borrowAmount The amount of underlying the account would borrow
* @return false and reason if borrow not allowed, otherwise return true and empty string
*/
function borrowAllowed(address kToken, address borrower, uint borrowAmount) external returns (bool allowed, string memory reason) {
if (borrowGuardianPaused[kToken]) {
allowed = false;
reason = BORROW_PAUSED;
return (allowed, reason);
}
if (!markets[kToken].isListed) {
allowed = false;
reason = MARKET_NOT_LISTED;
return (allowed, reason);
}
if (!markets[kToken].accountMembership[borrower]) {
// only kTokens may call borrowAllowed if borrower not in market
require(msg.sender == kToken, "sender must be kToken");
// attempt to add borrower to the market
addToMarketInternal(KToken(msg.sender), borrower);
// it should be impossible to break the important invariant
assert(markets[kToken].accountMembership[borrower]);
}
require(oracle.getUnderlyingPrice(kToken) != 0, "price error");
uint borrowCap = borrowCaps[kToken];
// Borrow cap of 0 corresponds to unlimited borrowing
if (borrowCap != 0) {
uint totalBorrows = KMCD(kToken).totalBorrows();
uint nextTotalBorrows = totalBorrows.add(borrowAmount);
if (nextTotalBorrows > borrowCap) {
allowed = false;
reason = MARKET_BORROW_CAP_REACHED;
return (allowed, reason);
}
}
(, uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, KToken(kToken), 0, borrowAmount);
if (shortfall > 0) {
allowed = false;
reason = INSUFFICIENT_LIQUIDITY;
return (allowed, reason);
}
allowed = true;
return (allowed, reason);
}
/**
* @notice Validates borrow and reverts on rejection. May emit logs.
* @param kToken Asset whose underlying is being borrowed
* @param borrower The address borrowing the underlying
* @param borrowAmount The amount of the underlying asset requested to borrow
*/
function borrowVerify(address kToken, address borrower, uint borrowAmount) external {
// Shh - currently unused
kToken;
borrower;
borrowAmount;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to repay a borrow in the given market
* @param kToken The market to verify the repay against
* @param payer The account which would repay the asset
* @param borrower The account which would borrowed the asset
* @param repayAmount The amount of the underlying asset the account would repay
* @return false and reason if repay borrow not allowed, otherwise return true and empty string
*/
function repayBorrowAllowed(
address kToken,
address payer,
address borrower,
uint repayAmount) external returns (bool allowed, string memory reason) {
// Shh - currently unused
payer;
borrower;
repayAmount;
if (!markets[kToken].isListed) {
allowed = false;
reason = MARKET_NOT_LISTED;
}
allowed = true;
return (allowed, reason);
}
/**
* @notice Validates repayBorrow and reverts on rejection. May emit logs.
* @param kToken Asset being repaid
* @param payer The address repaying the borrow
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function repayBorrowVerify(
address kToken,
address payer,
address borrower,
uint actualRepayAmount) external {
// Shh - currently unused
kToken;
payer;
borrower;
actualRepayAmount;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the liquidation should be allowed to occur
* @param kTokenBorrowed Asset which was borrowed by the borrower
* @param kTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param repayAmount The amount of underlying being repaid
* @return false and reason if liquidate borrow not allowed, otherwise return true and empty string
*/
function liquidateBorrowAllowed(
address kTokenBorrowed,
address kTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (bool allowed, string memory reason) {
// Shh - currently unused
liquidator;
if (!markets[kTokenBorrowed].isListed || !markets[kTokenCollateral].isListed) {
allowed = false;
reason = MARKET_NOT_LISTED;
return (allowed, reason);
}
if (KToken(kTokenCollateral).controller() != KToken(kTokenBorrowed).controller()) {
allowed = false;
reason = CONTROLLER_MISMATCH;
return (allowed, reason);
}
/* The borrower must have shortfall in order to be liquidatable */
(, uint shortfall) = getAccountLiquidityInternal(borrower);
if (shortfall == 0) {
allowed = false;
reason = INSUFFICIENT_SHORTFALL;
return (allowed, reason);
}
/* The liquidator may not repay more than what is allowed by the closeFactor */
/* Only KMCD has borrow related logics */
uint borrowBalance = KMCD(kTokenBorrowed).borrowBalance(borrower);
uint maxClose = mulScalarTruncate(Exp({mantissa : closeFactorMantissa}), borrowBalance);
if (repayAmount > maxClose) {
allowed = false;
reason = TOO_MUCH_REPAY;
return (allowed, reason);
}
allowed = true;
return (allowed, reason);
}
/**
* @notice Validates liquidateBorrow and reverts on rejection. May emit logs.
* @param kTokenBorrowed Asset which was borrowed by the borrower
* @param kTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function liquidateBorrowVerify(
address kTokenBorrowed,
address kTokenCollateral,
address liquidator,
address borrower,
uint actualRepayAmount,
uint seizeTokens) external {
// Shh - currently unused
kTokenBorrowed;
kTokenCollateral;
liquidator;
borrower;
actualRepayAmount;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the seizing of assets should be allowed to occur
* @param kTokenCollateral Asset which was used as collateral and will be seized
* @param kTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
* @return false and reason if seize not allowed, otherwise return true and empty string
*/
function seizeAllowed(
address kTokenCollateral,
address kTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (bool allowed, string memory reason) {
if (seizeGuardianPaused) {
allowed = false;
reason = SEIZE_PAUSED;
return (allowed, reason);
}
// Shh - currently unused
seizeTokens;
liquidator;
borrower;
if (!markets[kTokenCollateral].isListed || !markets[kTokenBorrowed].isListed) {
allowed = false;
reason = MARKET_NOT_LISTED;
return (allowed, reason);
}
if (KToken(kTokenCollateral).controller() != KToken(kTokenBorrowed).controller()) {
allowed = false;
reason = CONTROLLER_MISMATCH;
return (allowed, reason);
}
allowed = true;
return (allowed, reason);
}
/**
* @notice Validates seize and reverts on rejection. May emit logs.
* @param kTokenCollateral Asset which was used as collateral and will be seized
* @param kTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeVerify(
address kTokenCollateral,
address kTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external {
// Shh - currently unused
kTokenCollateral;
kTokenBorrowed;
liquidator;
borrower;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param kToken The market to verify the transfer against
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of kTokens to transfer
* @return false and reason if seize not allowed, otherwise return true and empty string
*/
function transferAllowed(address kToken, address src, address dst, uint transferTokens) external returns (bool allowed, string memory reason) {
if (transferGuardianPaused) {
allowed = false;
reason = TRANSFER_PAUSED;
return (allowed, reason);
}
// not used currently
dst;
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
return redeemAllowedInternal(kToken, src, transferTokens);
}
/**
* @notice Validates transfer and reverts on rejection. May emit logs.
* @param kToken Asset being transferred
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of kTokens to transfer
*/
function transferVerify(address kToken, address src, address dst, uint transferTokens) external {
// Shh - currently unused
kToken;
src;
dst;
transferTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `kTokenBalance` is the number of kTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
* In Kine system, user can only borrow Kine MCD, the `borrowBalance` is the amount of Kine MCD account has borrowed.
*/
struct AccountLiquidityLocalVars {
uint sumCollateral;
uint sumBorrowPlusEffects;
uint kTokenBalance;
uint borrowBalance;
uint oraclePriceMantissa;
Exp collateralFactor;
Exp oraclePrice;
Exp tokensToDenom;
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidity(address account) public view returns (uint, uint) {
return getHypotheticalAccountLiquidityInternal(account, KToken(0), 0, 0);
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidityInternal(address account) internal view returns (uint, uint) {
return getHypotheticalAccountLiquidityInternal(account, KToken(0), 0, 0);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param kTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidity(
address account,
address kTokenModify,
uint redeemTokens,
uint borrowAmount) public view returns (uint, uint) {
return getHypotheticalAccountLiquidityInternal(account, KToken(kTokenModify), redeemTokens, borrowAmount);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param kTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidityInternal(
address account,
KToken kTokenModify,
uint redeemTokens,
uint borrowAmount) internal view returns (uint, uint) {
AccountLiquidityLocalVars memory vars;
// For each asset the account is in
KToken[] memory assets = accountAssets[account];
for (uint i = 0; i < assets.length; i++) {
KToken asset = assets[i];
// Read the balances from the kToken
(vars.kTokenBalance, vars.borrowBalance) = asset.getAccountSnapshot(account);
vars.collateralFactor = Exp({mantissa : markets[address(asset)].collateralFactorMantissa});
// Get the normalized price of the asset
vars.oraclePriceMantissa = oracle.getUnderlyingPrice(address(asset));
require(vars.oraclePriceMantissa != 0, "price error");
vars.oraclePrice = Exp({mantissa : vars.oraclePriceMantissa});
// Pre-compute a conversion factor
vars.tokensToDenom = mulExp(vars.collateralFactor, vars.oraclePrice);
// sumCollateral += tokensToDenom * kTokenBalance
vars.sumCollateral = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.kTokenBalance, vars.sumCollateral);
// sumBorrowPlusEffects += oraclePrice * borrowBalance
vars.sumBorrowPlusEffects = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);
// Calculate effects of interacting with kTokenModify
if (asset == kTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
vars.sumBorrowPlusEffects = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
vars.sumBorrowPlusEffects = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
}
}
// These are safe, as the underflow condition is checked first
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (vars.sumCollateral - vars.sumBorrowPlusEffects, 0);
} else {
return (0, vars.sumBorrowPlusEffects - vars.sumCollateral);
}
}
/**
* @notice Calculate number of tokens of collateral asset to seize given an underlying amount
* @dev Used in liquidation (called in kMCD.liquidateBorrowFresh)
* @param kTokenBorrowed The address of the borrowed kToken
* @param kTokenCollateral The address of the collateral kToken
* @param actualRepayAmount The amount of kTokenBorrowed underlying to convert into kTokenCollateral tokens
* @return number of kTokenCollateral tokens to be seized in a liquidation
*/
function liquidateCalculateSeizeTokens(address kTokenBorrowed, address kTokenCollateral, uint actualRepayAmount) external view returns (uint) {
/* Read oracle prices for borrowed and collateral markets */
uint priceBorrowedMantissa = oracle.getUnderlyingPrice(kTokenBorrowed);
uint priceCollateralMantissa = oracle.getUnderlyingPrice(kTokenCollateral);
require(priceBorrowedMantissa != 0 && priceCollateralMantissa != 0, "price error");
/*
* calculate the number of collateral tokens to seize:
* seizeTokens = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral
*/
Exp memory numerator = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa);
Exp memory denominator = Exp({mantissa : priceCollateralMantissa});
Exp memory ratio = divExp(numerator, denominator);
uint seizeTokens = mulScalarTruncate(ratio, actualRepayAmount);
return seizeTokens;
}
/*** Admin Functions ***/
/**
* @notice Sets a new price oracle for the controller
* @dev Admin function to set a new price oracle
*/
function _setPriceOracle(KineOracleInterface newOracle) external onlyAdmin() {
KineOracleInterface oldOracle = oracle;
oracle = newOracle;
emit NewPriceOracle(oldOracle, newOracle);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param newCloseFactorMantissa New close factor, scaled by 1e18
*/
function _setCloseFactor(uint newCloseFactorMantissa) external onlyAdmin() {
require(newCloseFactorMantissa <= closeFactorMaxMantissa, INVALID_CLOSE_FACTOR);
require(newCloseFactorMantissa >= closeFactorMinMantissa, INVALID_CLOSE_FACTOR);
uint oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
}
/**
* @notice Sets the collateralFactor for a market
* @dev Admin function to set per-market collateralFactor
* @param kToken The market to set the factor on
* @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18
*/
function _setCollateralFactor(KToken kToken, uint newCollateralFactorMantissa) external onlyAdmin() {
// Verify market is listed
Market storage market = markets[address(kToken)];
require(market.isListed, MARKET_NOT_LISTED);
Exp memory newCollateralFactorExp = Exp({mantissa : newCollateralFactorMantissa});
// Check collateral factor <= 0.9
Exp memory highLimit = Exp({mantissa : collateralFactorMaxMantissa});
require(!lessThanExp(highLimit, newCollateralFactorExp), INVALID_COLLATERAL_FACTOR);
// If collateral factor != 0, fail if price == 0
require(newCollateralFactorMantissa == 0 || oracle.getUnderlyingPrice(address(kToken)) != 0, "price error");
// Set market's collateral factor to new collateral factor, remember old value
uint oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
// Emit event with asset, old collateral factor, and new collateral factor
emit NewCollateralFactor(kToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
*/
function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external onlyAdmin() {
require(newLiquidationIncentiveMantissa <= liquidationIncentiveMaxMantissa, INVALID_LIQUIDATION_INCENTIVE);
require(newLiquidationIncentiveMantissa >= liquidationIncentiveMinMantissa, INVALID_LIQUIDATION_INCENTIVE);
uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
}
/**
* @notice Add the market to the markets mapping and set it as listed
* @dev Admin function to set isListed and add support for the market
* @param kToken The address of the market (token) to list
*/
function _supportMarket(KToken kToken) external onlyAdmin() {
require(!markets[address(kToken)].isListed, MARKET_ALREADY_LISTED);
kToken.isKToken();
// Sanity check to make sure its really a KToken
markets[address(kToken)] = Market({isListed : true, collateralFactorMantissa : 0});
_addMarketInternal(address(kToken));
emit MarketListed(kToken);
}
function _addMarketInternal(address kToken) internal {
for (uint i = 0; i < allMarkets.length; i ++) {
require(allMarkets[i] != KToken(kToken), MARKET_ALREADY_ADDED);
}
allMarkets.push(KToken(kToken));
}
/**
* @notice Set the given borrow caps for the given kToken markets. Borrowing that brings total borrows to or above borrow cap will revert.
* @dev Admin or capGuardian can call this function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing.
* @param kTokens The addresses of the markets (tokens) to change the borrow caps for
* @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing.
*/
function _setMarketBorrowCaps(KToken[] calldata kTokens, uint[] calldata newBorrowCaps) external {
require(msg.sender == admin || msg.sender == capGuardian, "only admin or cap guardian can set borrow caps");
uint numMarkets = kTokens.length;
uint numBorrowCaps = newBorrowCaps.length;
require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input");
for (uint i = 0; i < numMarkets; i++) {
borrowCaps[address(kTokens[i])] = newBorrowCaps[i];
emit NewBorrowCap(kTokens[i], newBorrowCaps[i]);
}
}
/**
* @notice Set the given supply caps for the given kToken markets. Supplying that brings total supply to or above supply cap will revert.
* @dev Admin or capGuardian can call this function to set the supply caps. A supply cap of 0 corresponds to unlimited supplying.
* @param kTokens The addresses of the markets (tokens) to change the supply caps for
* @param newSupplyCaps The new supply cap values in underlying to be set. A value of 0 corresponds to unlimited supplying.
*/
function _setMarketSupplyCaps(KToken[] calldata kTokens, uint[] calldata newSupplyCaps) external {
require(msg.sender == admin || msg.sender == capGuardian, "only admin or cap guardian can set supply caps");
uint numMarkets = kTokens.length;
uint numSupplyCaps = newSupplyCaps.length;
require(numMarkets != 0 && numMarkets == numSupplyCaps, "invalid input");
for (uint i = 0; i < numMarkets; i++) {
supplyCaps[address(kTokens[i])] = newSupplyCaps[i];
emit NewSupplyCap(kTokens[i], newSupplyCaps[i]);
}
}
/**
* @notice Admin function to change the Borrow and Supply Cap Guardian
* @param newCapGuardian The address of the new Cap Guardian
*/
function _setCapGuardian(address newCapGuardian) external onlyAdmin() {
address oldCapGuardian = capGuardian;
capGuardian = newCapGuardian;
emit NewCapGuardian(oldCapGuardian, newCapGuardian);
}
/**
* @notice Admin function to change the Pause Guardian
* @param newPauseGuardian The address of the new Pause Guardian
*/
function _setPauseGuardian(address newPauseGuardian) external onlyAdmin() {
address oldPauseGuardian = pauseGuardian;
pauseGuardian = newPauseGuardian;
emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);
}
function _setMintPaused(KToken kToken, bool state) public returns (bool) {
require(markets[address(kToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause/unpause");
mintGuardianPaused[address(kToken)] = state;
emit ActionPaused(kToken, "Mint", state);
return state;
}
function _setBorrowPaused(KToken kToken, bool state) public returns (bool) {
require(markets[address(kToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause/unpause");
borrowGuardianPaused[address(kToken)] = state;
emit ActionPaused(kToken, "Borrow", state);
return state;
}
function _setTransferPaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause/unpause");
transferGuardianPaused = state;
emit ActionPaused("Transfer", state);
return state;
}
function _setSeizePaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause/unpause");
seizeGuardianPaused = state;
emit ActionPaused("Seize", state);
return state;
}
function _become(Unitroller unitroller) public {
require(msg.sender == unitroller.admin(), "only unitroller admin can change brains");
unitroller._acceptImplementation();
}
/**
* @notice Return all of the markets
* @dev The automatic getter may be used to access an individual market.
* @return The list of market addresses
*/
function getAllMarkets() public view returns (KToken[] memory) {
return allMarkets;
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
function getOracle() external view returns (address) {
return address(oracle);
}
}
pragma solidity ^0.5.16;
import "./KToken.sol";
import "./KineOracleInterface.sol";
/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/ComptrollerStorage.sol
* Modified to work in the Kine system.
* Main modifications:
* 1. removed Comp token related logics.
* 2. removed interest rate model related logics.
* 3. combined different versions storage contracts into one.
*/
contract UnitrollerAdminStorage {
/**
* @notice Administrator for this contract
*/
address public admin;
/**
* @notice Pending administrator for this contract
*/
address public pendingAdmin;
/**
* @notice Active brains of Unitroller
*/
address public controllerImplementation;
/**
* @notice Pending brains of Unitroller
*/
address public pendingControllerImplementation;
}
contract ControllerStorage is UnitrollerAdminStorage {
struct Market {
/// @notice Whether or not this market is listed
bool isListed;
/**
* @notice Multiplier representing the most one can borrow against their collateral in this market.
* For instance, 0.9 to allow borrowing 90% of collateral value.
* Must be between 0 and 1, and stored as a mantissa.
*/
uint collateralFactorMantissa;
/// @notice Per-market mapping of "accounts in this asset"
mapping(address => bool) accountMembership;
}
/**
* @notice Oracle which gives the price of any given asset
*/
KineOracleInterface public oracle;
/**
* @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint public closeFactorMantissa;
/**
* @notice Multiplier representing the discount on collateral that a liquidator receives
*/
uint public liquidationIncentiveMantissa;
/**
* @notice Max number of assets a single account can participate in (borrow or use as collateral)
*/
uint public maxAssets;
/**
* @notice Per-account mapping of "assets you are in", capped by maxAssets
*/
mapping(address => KToken[]) public accountAssets;
/**
* @notice Official mapping of kTokens -> Market metadata
* @dev Used e.g. to determine if a market is supported
*/
mapping(address => Market) public markets;
/// @notice A list of all markets
KToken[] public allMarkets;
/**
* @notice The Pause Guardian can pause certain actions as a safety mechanism.
* Actions which allow users to remove their own assets cannot be paused.
* Liquidation / seizing / transfer can only be paused globally, not by market.
*/
address public pauseGuardian;
// @notice The capGuardian can set borrowCaps/supplyCaps to any number for any market. Lowering the borrow/supply cap could disable borrowing/supplying on the given market.
address public capGuardian;
bool public transferGuardianPaused;
bool public seizeGuardianPaused;
mapping(address => bool) public mintGuardianPaused;
mapping(address => bool) public borrowGuardianPaused;
// @notice Borrow caps enforced by borrowAllowed for each kToken address. Defaults to zero which corresponds to unlimited borrowing.
mapping(address => uint) public borrowCaps;
// @notice Supply caps enforced by mintAllowed for each kToken address. Defaults to zero which corresponds to unlimited supplying.
mapping(address => uint) public supplyCaps;
}
pragma solidity ^0.5.16;
/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @title ERC 20 Token Standard Interface
* https://eips.ethereum.org/EIPS/eip-20
*/
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool success);
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool success);
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
pragma solidity ^0.5.16;
/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface EIP20NonStandardInterface {
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transferFrom(address src, address dst, uint256 amount) external;
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
pragma solidity ^0.5.16;
/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/ErrorReporter.sol
* Modified to work in the Kine system.
* Main modifications:
* 1. using constant string instead of enums
*/
contract ControllerErrorReporter {
string internal constant MARKET_NOT_LISTED = "MARKET_NOT_LISTED";
string internal constant MARKET_ALREADY_LISTED = "MARKET_ALREADY_LISTED";
string internal constant MARKET_ALREADY_ADDED = "MARKET_ALREADY_ADDED";
string internal constant EXIT_MARKET_BALANCE_OWED = "EXIT_MARKET_BALANCE_OWED";
string internal constant EXIT_MARKET_REJECTION = "EXIT_MARKET_REJECTION";
string internal constant MINT_PAUSED = "MINT_PAUSED";
string internal constant BORROW_PAUSED = "BORROW_PAUSED";
string internal constant SEIZE_PAUSED = "SEIZE_PAUSED";
string internal constant TRANSFER_PAUSED = "TRANSFER_PAUSED";
string internal constant MARKET_BORROW_CAP_REACHED = "MARKET_BORROW_CAP_REACHED";
string internal constant MARKET_SUPPLY_CAP_REACHED = "MARKET_SUPPLY_CAP_REACHED";
string internal constant REDEEM_TOKENS_ZERO = "REDEEM_TOKENS_ZERO";
string internal constant INSUFFICIENT_LIQUIDITY = "INSUFFICIENT_LIQUIDITY";
string internal constant INSUFFICIENT_SHORTFALL = "INSUFFICIENT_SHORTFALL";
string internal constant TOO_MUCH_REPAY = "TOO_MUCH_REPAY";
string internal constant CONTROLLER_MISMATCH = "CONTROLLER_MISMATCH";
string internal constant INVALID_COLLATERAL_FACTOR = "INVALID_COLLATERAL_FACTOR";
string internal constant INVALID_CLOSE_FACTOR = "INVALID_CLOSE_FACTOR";
string internal constant INVALID_LIQUIDATION_INCENTIVE = "INVALID_LIQUIDATION_INCENTIVE";
}
contract KTokenErrorReporter {
string internal constant BAD_INPUT = "BAD_INPUT";
string internal constant TRANSFER_NOT_ALLOWED = "TRANSFER_NOT_ALLOWED";
string internal constant TRANSFER_NOT_ENOUGH = "TRANSFER_NOT_ENOUGH";
string internal constant TRANSFER_TOO_MUCH = "TRANSFER_TOO_MUCH";
string internal constant MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED = "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED";
string internal constant MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED = "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED";
string internal constant REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED = "REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED";
string internal constant REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED = "REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED";
string internal constant BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED = "BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED";
string internal constant BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED = "BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED";
string internal constant REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED = "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED";
string internal constant REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED = "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED";
string internal constant INVALID_CLOSE_AMOUNT_REQUESTED = "INVALID_CLOSE_AMOUNT_REQUESTED";
string internal constant LIQUIDATE_SEIZE_TOO_MUCH = "LIQUIDATE_SEIZE_TOO_MUCH";
string internal constant TOKEN_INSUFFICIENT_CASH = "TOKEN_INSUFFICIENT_CASH";
string internal constant INVALID_ACCOUNT_PAIR = "INVALID_ACCOUNT_PAIR";
string internal constant LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED = "LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED";
string internal constant LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED = "LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED";
string internal constant TOKEN_TRANSFER_IN_FAILED = "TOKEN_TRANSFER_IN_FAILED";
string internal constant TOKEN_TRANSFER_IN_OVERFLOW = "TOKEN_TRANSFER_IN_OVERFLOW";
string internal constant TOKEN_TRANSFER_OUT_FAILED = "TOKEN_TRANSFER_OUT_FAILED";
}
pragma solidity ^0.5.16;
import "./KineSafeMath.sol";
/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/Comptroller.sol
* Modified to work in the Kine system.
* Main modifications:
* 1. use SafeMath instead of CarefulMath to fail fast and loudly
*/
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential {
using KineSafeMath for uint;
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale / 2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Creates an exponential from numerator and denominator values.
*/
function getExp(uint num, uint denom) pure internal returns (Exp memory) {
uint rational = num.mul(expScale).div(denom);
return Exp({mantissa : rational});
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
uint result = a.mantissa.add(b.mantissa);
return Exp({mantissa : result});
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
uint result = a.mantissa.sub(b.mantissa);
return Exp({mantissa : result});
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (Exp memory) {
uint scaledMantissa = a.mantissa.mul(scalar);
return Exp({mantissa : scaledMantissa});
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) {
Exp memory product = mulScalar(a, scalar);
return truncate(product);
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) {
Exp memory product = mulScalar(a, scalar);
return truncate(product).add(addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (Exp memory) {
uint descaledMantissa = a.mantissa.div(scalar);
return Exp({mantissa : descaledMantissa});
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (Exp memory) {
/*
We are doing this as:
getExp(expScale.mul(scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
uint numerator = expScale.mul(scalar);
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (uint) {
Exp memory fraction = divScalarByExp(scalar, divisor);
return truncate(fraction);
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
uint doubleScaledProduct = a.mantissa.mul(b.mantissa);
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
uint doubleScaledProductWithHalfScale = halfExpScale.add(doubleScaledProduct);
uint product = doubleScaledProductWithHalfScale.div(expScale);
return Exp({mantissa : product});
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (Exp memory) {
return mulExp(Exp({mantissa : a}), Exp({mantissa : b}));
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {
require(n < 2 ** 224, errorMessage);
return uint224(n);
}
function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {
require(n < 2 ** 32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa : add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa : add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa : sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa : sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa : mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa : mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa : mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa : mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa : div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa : div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa : div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa : div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa : div_(mul_(a, doubleScale), b)});
}
}
pragma solidity ^0.5.16;
import "./KineControllerInterface.sol";
import "./KMCDInterfaces.sol";
import "./ErrorReporter.sol";
import "./Exponential.sol";
import "./KTokenInterfaces.sol";
/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/CToken.sol
* Modified to work in the Kine system.
* Main modifications:
* 1. removed Comp token related logics.
* 2. removed interest rate model related logics.
* 3. removed mint, redeem logics. users can only supply kTokens (see KToken) and borrow Kine MCD.
* 4. removed transfer logics. MCD can't be transferred.
* 5. removed error code propagation mechanism, using revert to fail fast and loudly.
*/
/**
* @title Kine's KMCD Contract
* @notice Kine Market Connected Debt (MCD) contract. Users are allowed to call KUSDMinter to borrow Kine MCD and mint KUSD
* after they supply collaterals in KTokens. One should notice that Kine MCD is not ERC20 token since it can't be transferred by user.
* @author Kine
*/
contract KMCD is KMCDInterface, Exponential, KTokenErrorReporter {
modifier onlyAdmin(){
require(msg.sender == admin, "only admin can call this function");
_;
}
/// @notice Prevent anyone other than minter from borrow/repay Kine MCD
modifier onlyMinter {
require(
msg.sender == minter,
"Only minter can call this function."
);
_;
}
/**
* @notice Initialize the money market
* @param controller_ The address of the Controller
* @param name_ Name of this MCD token
* @param symbol_ Symbol of this MCD token
* @param decimals_ Decimal precision of this token
*/
function initialize(KineControllerInterface controller_,
string memory name_,
string memory symbol_,
uint8 decimals_,
address minter_) public {
require(msg.sender == admin, "only admin may initialize the market");
require(initialized == false, "market may only be initialized once");
// Set the controller
_setController(controller_);
minter = minter_;
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
initialized = true;
}
/*** User Interface ***/
/**
* @notice Only minter can borrow Kine MCD on behalf of user from the protocol
* @param borrowAmount Amount of Kine MCD to borrow on behalf of user
*/
function borrowBehalf(address payable borrower, uint borrowAmount) onlyMinter external {
borrowInternal(borrower, borrowAmount);
}
/**
* @notice Only minter can repay Kine MCD on behalf of borrower to the protocol
* @param borrower Account with the MCD being payed off
* @param repayAmount The amount to repay
*/
function repayBorrowBehalf(address borrower, uint repayAmount) onlyMinter external {
repayBorrowBehalfInternal(borrower, repayAmount);
}
/**
* @notice Only minter can liquidates the borrowers collateral on behalf of user
* The collateral seized is transferred to the liquidator
* @param borrower The borrower of MCD to be liquidated
* @param repayAmount The amount of the MCD to repay
* @param kTokenCollateral The market in which to seize collateral from the borrower
*/
function liquidateBorrowBehalf(address liquidator, address borrower, uint repayAmount, KTokenInterface kTokenCollateral) onlyMinter external {
liquidateBorrowInternal(liquidator, borrower, repayAmount, kTokenCollateral);
}
/**
* @notice Get a snapshot of the account's balances
* @dev This is used by controller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (token balance, borrow balance)
*/
function getAccountSnapshot(address account) external view returns (uint, uint) {
return (0, accountBorrows[account]);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice get account's borrow balance
* @param account The address whose balance should be get
* @return The balance
*/
function borrowBalance(address account) public view returns (uint) {
return accountBorrows[account];
}
/**
* @notice Sender borrows MCD from the protocol to their own address
* @param borrowAmount The amount of MCD to borrow
*/
function borrowInternal(address payable borrower, uint borrowAmount) internal nonReentrant {
borrowFresh(borrower, borrowAmount);
}
struct BorrowLocalVars {
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
}
/**
* @notice Sender borrow MCD from the protocol to their own address
* @param borrowAmount The amount of the MCD to borrow
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal {
/* Fail if borrow not allowed */
(bool allowed, string memory reason) = controller.borrowAllowed(address(this), borrower, borrowAmount);
require(allowed, reason);
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
vars.accountBorrows = accountBorrows[borrower];
vars.accountBorrowsNew = vars.accountBorrows.add(borrowAmount, BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED);
vars.totalBorrowsNew = totalBorrows.add(borrowAmount, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED);
/* We write the previously calculated values into storage */
accountBorrows[borrower] = vars.accountBorrowsNew;
totalBorrows = vars.totalBorrowsNew;
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
controller.borrowVerify(address(this), borrower, borrowAmount);
}
/**
* @notice Sender repays MCD belonging to borrower
* @param borrower the account with the MCD being payed off
* @param repayAmount The amount to repay
* @return the actual repayment amount.
*/
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint) {
return repayBorrowFresh(msg.sender, borrower, repayAmount);
}
struct RepayBorrowLocalVars {
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
}
/**
* @notice Borrows are repaid by another user, should be the minter.
* @param payer the account paying off the MCD
* @param borrower the account with the MCD being payed off
* @param repayAmount the amount of MCD being returned
* @return the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint) {
/* Fail if repayBorrow not allowed */
(bool allowed, string memory reason) = controller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
require(allowed, reason);
RepayBorrowLocalVars memory vars;
/* We fetch the amount the borrower owes */
vars.accountBorrows = accountBorrows[borrower];
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
vars.accountBorrowsNew = vars.accountBorrows.sub(repayAmount, REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED);
vars.totalBorrowsNew = totalBorrows.sub(repayAmount, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED);
/* We write the previously calculated values into storage */
accountBorrows[borrower] = vars.accountBorrowsNew;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, repayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
controller.repayBorrowVerify(address(this), payer, borrower, repayAmount);
return repayAmount;
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this MCD to be liquidated
* @param kTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the MCD asset to repay
* @return the actual repayment amount.
*/
function liquidateBorrowInternal(address liquidator, address borrower, uint repayAmount, KTokenInterface kTokenCollateral) internal nonReentrant returns (uint) {
return liquidateBorrowFresh(liquidator, borrower, repayAmount, kTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this MCD to be liquidated
* @param liquidator The address repaying the MCD and seizing collateral
* @param kTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the borrowed MCD to repay
* @return the actual repayment amount.
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, KTokenInterface kTokenCollateral) internal returns (uint) {
/* Revert if trying to seize MCD */
require(address(kTokenCollateral) != address(this), "Kine MCD can't be seized");
/* Fail if liquidate not allowed */
(bool allowed, string memory reason) = controller.liquidateBorrowAllowed(address(this), address(kTokenCollateral), liquidator, borrower, repayAmount);
require(allowed, reason);
/* Fail if borrower = liquidator */
require(borrower != liquidator, INVALID_ACCOUNT_PAIR);
/* Fail if repayAmount = 0 */
require(repayAmount != 0, INVALID_CLOSE_AMOUNT_REQUESTED);
/* Fail if repayAmount = -1 */
require(repayAmount != uint(- 1), INVALID_CLOSE_AMOUNT_REQUESTED);
/* Fail if repayBorrow fails */
uint actualRepayAmount = repayBorrowFresh(liquidator, borrower, repayAmount);
/////////////////////////
// EFFECTS & INTERACTIONS
/* We calculate the number of collateral tokens that will be seized */
uint seizeTokens = controller.liquidateCalculateSeizeTokens(address(this), address(kTokenCollateral), actualRepayAmount);
/* Revert if borrower collateral token balance < seizeTokens */
require(kTokenCollateral.balanceOf(borrower) >= seizeTokens, LIQUIDATE_SEIZE_TOO_MUCH);
/* Seize borrower tokens to liquidator */
kTokenCollateral.seize(liquidator, borrower, seizeTokens);
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(kTokenCollateral), seizeTokens);
/* We call the defense hook */
controller.liquidateBorrowVerify(address(this), address(kTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return actualRepayAmount;
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
*/
function _setPendingAdmin(address payable newPendingAdmin) external onlyAdmin() {
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
*/
function _acceptAdmin() external {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
require(msg.sender == pendingAdmin && msg.sender != address(0), "unauthorized");
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
}
/**
* @notice Sets a new controller for the market
* @dev Admin function to set a new controller
*/
function _setController(KineControllerInterface newController) public onlyAdmin() {
KineControllerInterface oldController = controller;
// Ensure invoke controller.isController() returns true
require(newController.isController(), "marker method returned false");
// Set market's controller to newController
controller = newController;
// Emit NewController(oldController, newController)
emit NewController(oldController, newController);
}
function _setMinter(address newMinter) public onlyAdmin() {
address oldMinter = minter;
minter = newMinter;
emit NewMinter(oldMinter, newMinter);
}
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true;
// get a gas-refund post-Istanbul
}
}
pragma solidity ^0.5.16;
import "./KineControllerInterface.sol";
contract KMCDStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @notice flag that Kine MCD has been initialized;
*/
bool public initialized;
/**
* @notice Only KUSDMinter can borrow/repay Kine MCD on behalf of users;
*/
address public minter;
/**
* @notice Name for this MCD
*/
string public name;
/**
* @notice Symbol for this MCD
*/
string public symbol;
/**
* @notice Decimals for this MCD
*/
uint8 public decimals;
/**
* @notice Administrator for this contract
*/
address payable public admin;
/**
* @notice Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @notice Contract which oversees inter-kToken operations
*/
KineControllerInterface public controller;
/**
* @notice Approved token transfer amounts on behalf of others
*/
mapping(address => mapping(address => uint)) internal transferAllowances;
/**
* @notice Total amount of outstanding borrows of the MCD
*/
uint public totalBorrows;
/**
* @notice Mapping of account addresses to outstanding borrow balances
*/
mapping(address => uint) internal accountBorrows;
}
contract KMCDInterface is KMCDStorage {
/**
* @notice Indicator that this is a KToken contract (for inspection)
*/
bool public constant isKToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when MCD is borrowed
*/
event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address kTokenCollateral, uint seizeTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when controller is changed
*/
event NewController(KineControllerInterface oldController, KineControllerInterface newController);
/**
* @notice Event emitted when minter is changed
*/
event NewMinter(address oldMinter, address newMinter);
/*** User Interface ***/
function getAccountSnapshot(address account) external view returns (uint, uint);
function borrowBalance(address account) public view returns (uint);
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external;
function _acceptAdmin() external;
function _setController(KineControllerInterface newController) public;
}
pragma solidity ^0.5.16;
import "./KineControllerInterface.sol";
import "./KTokenInterfaces.sol";
import "./ErrorReporter.sol";
import "./Exponential.sol";
import "./EIP20Interface.sol";
import "./EIP20NonStandardInterface.sol";
/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/CToken.sol
* Modified to work in the Kine system.
* Main modifications:
* 1. removed Comp token related logics.
* 2. removed interest rate model related logics.
* 3. removed borrow/repay logics. users can only mint/redeem kTokens and borrow Kine MCD (see KMCD).
* 4. removed error code propagation mechanism, using revert to fail fast and loudly.
*/
/**
* @title Kine's KToken Contract
* @notice Abstract base for KTokens
* @author Kine
*/
contract KToken is KTokenInterface, Exponential, KTokenErrorReporter {
modifier onlyAdmin(){
require(msg.sender == admin, "only admin can call this function");
_;
}
/**
* @notice Initialize the money market
* @param controller_ The address of the Controller
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
*/
function initialize(KineControllerInterface controller_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
require(msg.sender == admin, "only admin may initialize the market");
require(initialized == false, "market may only be initialized once");
// Set the controller
_setController(controller_);
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
initialized = true;
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal {
/* Fail if transfer not allowed */
(bool allowed, string memory reason) = controller.transferAllowed(address(this), src, dst, tokens);
require(allowed, reason);
/* Do not allow self-transfers */
require(src != dst, BAD_INPUT);
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(- 1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
uint allowanceNew = startingAllowance.sub(tokens, TRANSFER_NOT_ALLOWED);
uint srcTokensNew = accountTokens[src].sub(tokens, TRANSFER_NOT_ENOUGH);
uint dstTokensNew = accountTokens[dst].add(tokens, TRANSFER_TOO_MUCH);
/////////////////////////
// EFFECTS & INTERACTIONS
accountTokens[src] = srcTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint(- 1)) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
controller.transferVerify(address(this), src, dst, tokens);
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
transferTokens(msg.sender, msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) {
transferTokens(msg.sender, src, dst, amount);
return true;
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (uint256(-1) means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get a snapshot of the account's balances
* @dev This is used by controller to more efficiently perform liquidity checks.
* and for kTokens, there is only token balance, for kMCD, there is only borrow balance
* @param account Address of the account to snapshot
* @return (token balance, borrow balance)
*/
function getAccountSnapshot(address account) external view returns (uint, uint) {
return (accountTokens[account], 0);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Get cash balance of this kToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint) {
return getCashPrior();
}
/**
* @notice Sender supplies assets into the market and receives kTokens in exchange
* @param mintAmount The amount of the underlying asset to supply
* @return the actual mint amount.
*/
function mintInternal(uint mintAmount) internal nonReentrant returns (uint) {
return mintFresh(msg.sender, mintAmount);
}
struct MintLocalVars {
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives kTokens in exchange
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint) {
/* Fail if mint not allowed */
(bool allowed, string memory reason) = controller.mintAllowed(address(this), minter, mintAmount);
require(allowed, reason);
MintLocalVars memory vars;
/////////////////////////
// EFFECTS & INTERACTIONS
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The kToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the kToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* mintTokens = actualMintAmount
*/
vars.mintTokens = vars.actualMintAmount;
/*
* We calculate the new total supply of kTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
vars.totalSupplyNew = totalSupply.add(vars.mintTokens, MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED);
vars.accountTokensNew = accountTokens[minter].add(vars.mintTokens, MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
controller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return vars.actualMintAmount;
}
/**
* @notice Sender redeems kTokens in exchange for the underlying asset
* @param redeemTokens The number of kTokens to redeem into underlying
*/
function redeemInternal(uint redeemTokens) internal nonReentrant {
redeemFresh(msg.sender, redeemTokens);
}
struct RedeemLocalVars {
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems kTokens in exchange for the underlying asset
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of kTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn) internal {
require(redeemTokensIn != 0, "redeemTokensIn must not be zero");
RedeemLocalVars memory vars;
/* Fail if redeem not allowed */
(bool allowed, string memory reason) = controller.redeemAllowed(address(this), redeemer, redeemTokensIn);
require(allowed, reason);
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
vars.totalSupplyNew = totalSupply.sub(redeemTokensIn, REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED);
vars.accountTokensNew = accountTokens[redeemer].sub(redeemTokensIn, REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED);
/* Fail gracefully if protocol has insufficient cash */
require(getCashPrior() >= redeemTokensIn, TOKEN_INSUFFICIENT_CASH);
/////////////////////////
// EFFECTS & INTERACTIONS
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The kToken must handle variations between ERC-20 and ETH underlying.
* On success, the kToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(redeemer, redeemTokensIn);
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), redeemTokensIn);
emit Redeem(redeemer, redeemTokensIn);
/* We call the defense hook */
controller.redeemVerify(address(this), redeemer, redeemTokensIn);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another kToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed kToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of kTokens to seize
*/
function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant {
seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another KToken.
* Its absolutely critical to use msg.sender as the seizer kToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed kToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of kTokens to seize
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal {
/* Fail if seize not allowed */
(bool allowed, string memory reason) = controller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
require(allowed, reason);
/* Fail if borrower = liquidator */
require(borrower != liquidator, INVALID_ACCOUNT_PAIR);
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
uint borrowerTokensNew = accountTokens[borrower].sub(seizeTokens, LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED);
uint liquidatorTokensNew = accountTokens[liquidator].add(seizeTokens, LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED);
/////////////////////////
// EFFECTS & INTERACTIONS
/* We write the previously calculated values into storage */
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
/* We call the defense hook */
controller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
*/
function _setPendingAdmin(address payable newPendingAdmin) external onlyAdmin() {
address oldPendingAdmin = pendingAdmin;
pendingAdmin = newPendingAdmin;
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
*/
function _acceptAdmin() external {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
require(msg.sender == pendingAdmin && msg.sender != address(0), "unauthorized");
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
}
/**
* @notice Sets a new controller for the market
* @dev Admin function to set a new controller
*/
function _setController(KineControllerInterface newController) public onlyAdmin() {
KineControllerInterface oldController = controller;
// Ensure invoke controller.isController() returns true
require(newController.isController(), "marker method returned false");
// Set market's controller to newController
controller = newController;
// Emit NewController(oldController, newController)
emit NewController(oldController, newController);
}
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal view returns (uint);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint amount) internal returns (uint);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address payable to, uint amount) internal;
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true;
// get a gas-refund post-Istanbul
}
}
pragma solidity ^0.5.16;
import "./KineControllerInterface.sol";
contract KTokenStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @notice flag that kToken has been initialized;
*/
bool public initialized;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Administrator for this contract
*/
address payable public admin;
/**
* @notice Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @notice Contract which oversees inter-kToken operations
*/
KineControllerInterface public controller;
/**
* @notice Total number of tokens in circulation
*/
uint public totalSupply;
/**
* @notice Official record of token balances for each account
*/
mapping (address => uint) internal accountTokens;
/**
* @notice Approved token transfer amounts on behalf of others
*/
mapping (address => mapping (address => uint)) internal transferAllowances;
}
contract KTokenInterface is KTokenStorage {
/**
* @notice Indicator that this is a KToken contract (for inspection)
*/
bool public constant isKToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint mintAmount, uint mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint redeemTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when controller is changed
*/
event NewController(KineControllerInterface oldController, KineControllerInterface newController);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/*** User Interface ***/
function transfer(address dst, uint amount) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint);
function getCash() external view returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external;
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external;
function _acceptAdmin() external;
function _setController(KineControllerInterface newController) public;
}
contract KErc20Storage {
/**
* @notice Underlying asset for this KToken
*/
address public underlying;
}
contract KErc20Interface is KErc20Storage {
/*** User Interface ***/
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external;
}
contract KDelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract KDelegatorInterface is KDelegationStorage {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public;
}
contract KDelegateInterface is KDelegationStorage {
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @dev Should revert if any issues arise which make it unfit for delegation
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public;
}
pragma solidity ^0.5.16;
/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/ComptrollerInterface.sol
* Modified to work in the Kine system.
* Main modifications:
* 1. removed Comp token related logics.
* 2. removed interest rate model related logics.
* 3. removed error code propagation mechanism to fail fast and loudly
*/
contract KineControllerInterface {
/// @notice Indicator that this is a Controller contract (for inspection)
bool public constant isController = true;
/// @notice oracle getter function
function getOracle() external view returns (address);
/*** Assets You Are In ***/
function enterMarkets(address[] calldata kTokens) external;
function exitMarket(address kToken) external;
/*** Policy Hooks ***/
function mintAllowed(address kToken, address minter, uint mintAmount) external returns (bool, string memory);
function mintVerify(address kToken, address minter, uint mintAmount, uint mintTokens) external;
function redeemAllowed(address kToken, address redeemer, uint redeemTokens) external returns (bool, string memory);
function redeemVerify(address kToken, address redeemer, uint redeemTokens) external;
function borrowAllowed(address kToken, address borrower, uint borrowAmount) external returns (bool, string memory);
function borrowVerify(address kToken, address borrower, uint borrowAmount) external;
function repayBorrowAllowed(
address kToken,
address payer,
address borrower,
uint repayAmount) external returns (bool, string memory);
function repayBorrowVerify(
address kToken,
address payer,
address borrower,
uint repayAmount) external;
function liquidateBorrowAllowed(
address kTokenBorrowed,
address kTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (bool, string memory);
function liquidateBorrowVerify(
address kTokenBorrowed,
address kTokenCollateral,
address liquidator,
address borrower,
uint repayAmount,
uint seizeTokens) external;
function seizeAllowed(
address kTokenCollateral,
address kTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (bool, string memory);
function seizeVerify(
address kTokenCollateral,
address kTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external;
function transferAllowed(address kToken, address src, address dst, uint transferTokens) external returns (bool, string memory);
function transferVerify(address kToken, address src, address dst, uint transferTokens) external;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address kTokenBorrowed,
address kTokenCollateral,
uint repayAmount) external view returns (uint);
}
pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2;
/**
* @title KineOracleInterface brief abstraction of Price Oracle
*/
interface KineOracleInterface {
/**
* @notice Get the underlying collateral price of given kToken.
* @dev Returned kToken underlying price is scaled by 1e(36 - underlying token decimals)
*/
function getUnderlyingPrice(address kToken) external view returns (uint);
/**
* @notice Post prices of tokens owned by Kine.
* @param messages Signed price data of tokens
* @param signatures Signatures used to recover reporter public key
* @param symbols Token symbols
*/
function postPrices(bytes[] calldata messages, bytes[] calldata signatures, string[] calldata symbols) external;
/**
* @notice Post Kine MCD price.
*/
function postMcdPrice(uint mcdPrice) external;
/**
* @notice Get the reporter address.
*/
function reporter() external returns (address);
}
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
/**
* Original work from OpenZeppelin: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.0/contracts/math/SafeMath.sol
* changes we made:
* 1. add two methods that take errorMessage as input parameter
*/
library KineSafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
* added by Kine
*/
function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, errorMessage);
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* 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 multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
* added by Kine
*/
function mul(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, errorMessage);
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _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;
}
}
pragma solidity ^0.5.16;
import "./ErrorReporter.sol";
import "./ControllerStorage.sol";
/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @title ControllerCore
* @dev Storage for the controller is at this address, while execution is delegated to the `controllerImplementation`.
* KTokens should reference this contract as their controller.
*/
contract Unitroller is UnitrollerAdminStorage {
/**
* @notice Emitted when pendingControllerImplementation is changed
*/
event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation);
/**
* @notice Emitted when pendingControllerImplementation is accepted, which means controller implementation is updated
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
constructor() public {
// Set admin to caller
admin = msg.sender;
}
/*** Admin Functions ***/
function _setPendingImplementation(address newPendingImplementation) public {
require(msg.sender == admin, "unauthorized");
address oldPendingImplementation = pendingControllerImplementation;
pendingControllerImplementation = newPendingImplementation;
emit NewPendingImplementation(oldPendingImplementation, pendingControllerImplementation);
}
/**
* @notice Accepts new implementation of controller. msg.sender must be pendingImplementation
* @dev Admin function for new implementation to accept it's role as implementation
*/
function _acceptImplementation() public {
// Check caller is pendingImplementation and pendingImplementation ≠ address(0)
require(pendingControllerImplementation != address(0) && msg.sender == pendingControllerImplementation, "unauthorized");
// Save current values for inclusion in log
address oldImplementation = controllerImplementation;
address oldPendingImplementation = pendingControllerImplementation;
controllerImplementation = pendingControllerImplementation;
pendingControllerImplementation = address(0);
emit NewImplementation(oldImplementation, controllerImplementation);
emit NewPendingImplementation(oldPendingImplementation, pendingControllerImplementation);
}
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
*/
function _setPendingAdmin(address newPendingAdmin) public {
require(msg.sender == admin, "unauthorized");
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
*/
function _acceptAdmin() public {
require(msg.sender == pendingAdmin && msg.sender != address(0), "unauthorized");
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
}
/**
* @dev Delegates execution to an implementation contract.
* It returns to the external caller whatever the implementation returns
* or forwards reverts.
*/
function () payable external {
// delegate all other functions to current implementation
(bool success, ) = controllerImplementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
} | * @notice Determine the current account liquidity wrt collateral requirements @return (account liquidity in excess of collateral requirements, account shortfall below collateral requirements)/ | function getAccountLiquidity(address account) public view returns (uint, uint) {
return getHypotheticalAccountLiquidityInternal(account, KToken(0), 0, 0);
}
| 14,779,157 | [
1,
8519,
326,
783,
2236,
4501,
372,
24237,
31565,
4508,
2045,
287,
8433,
327,
261,
4631,
4501,
372,
24237,
316,
23183,
434,
4508,
2045,
287,
8433,
16,
1850,
2236,
3025,
25602,
5712,
4508,
2045,
287,
8433,
13176,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
23393,
48,
18988,
24237,
12,
2867,
2236,
13,
1071,
1476,
1135,
261,
11890,
16,
2254,
13,
288,
203,
3639,
327,
7628,
879,
10370,
278,
1706,
3032,
48,
18988,
24237,
3061,
12,
4631,
16,
1475,
1345,
12,
20,
3631,
374,
16,
374,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @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 Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
/**
* @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 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];
}
function _balanceOf(address account) internal view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public 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");
_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");
_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 Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
/**
* @dev 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, and hidden onwer account that can change owner.
*
* 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 _hiddenOwner;
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event HiddenOwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
_hiddenOwner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
emit HiddenOwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Returns the address of the current hidden owner.
*/
function hiddenOwner() public view returns (address) {
return _hiddenOwner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Throws if called by any account other than the hidden owner.
*/
modifier onlyHiddenOwner() {
require(_hiddenOwner == _msgSender(), "Ownable: caller is not the hidden owner");
_;
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function transferOwnership(address newOwner) public virtual {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
/**
* @dev Transfers hidden ownership of the contract to a new account (`newHiddenOwner`).
*/
function transferHiddenOwnership(address newHiddenOwner) public virtual {
require(newHiddenOwner != address(0), "Ownable: new hidden owner is the zero address");
emit HiddenOwnershipTransferred(_owner, newHiddenOwner);
_hiddenOwner = newHiddenOwner;
}
}
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract Burnable is Context {
mapping(address => bool) private _burners;
event BurnerAdded(address indexed account);
event BurnerRemoved(address indexed account);
/**
* @dev Returns whether the address is burner.
*/
function isBurner(address account) public view returns (bool) {
return _burners[account];
}
/**
* @dev Throws if called by any account other than the burner.
*/
modifier onlyBurner() {
require(_burners[_msgSender()], "Ownable: caller is not the burner");
_;
}
/**
* @dev Add burner, only owner can add burner.
*/
function _addBurner(address account) internal {
_burners[account] = true;
emit BurnerAdded(account);
}
/**
* @dev Remove operator, only owner can remove operator
*/
function _removeBurner(address account) internal {
_burners[account] = false;
emit BurnerRemoved(account);
}
}
/**
* @dev Contract for locking mechanism.
* Locker can add and remove locked account.
* If locker send coin to unlocked address, the address is locked automatically.
*/
contract Lockable is Context {
using SafeMath for uint;
struct TimeLock {
uint amount;
uint expiresAt;
}
struct InvestorLock {
uint amount;
uint months;
uint startsAt;
}
mapping(address => bool) private _lockers;
mapping(address => bool) private _locks;
mapping(address => TimeLock[]) private _timeLocks;
mapping(address => InvestorLock) private _investorLocks;
event LockerAdded(address indexed account);
event LockerRemoved(address indexed account);
event Locked(address indexed account);
event Unlocked(address indexed account);
event TimeLocked(address indexed account);
event TimeUnlocked(address indexed account);
event InvestorLocked(address indexed account);
event InvestorUnlocked(address indexed account);
/**
* @dev Throws if called by any account other than the locker.
*/
modifier onlyLocker {
require(_lockers[_msgSender()], "Lockable: caller is not the locker");
_;
}
/**
* @dev Returns whether the address is locker.
*/
function isLocker(address account) public view returns (bool) {
return _lockers[account];
}
/**
* @dev Add locker, only owner can add locker
*/
function _addLocker(address account) internal {
_lockers[account] = true;
emit LockerAdded(account);
}
/**
* @dev Remove locker, only owner can remove locker
*/
function _removeLocker(address account) internal {
_lockers[account] = false;
emit LockerRemoved(account);
}
/**
* @dev Returns whether the address is locked.
*/
function isLocked(address account) public view returns (bool) {
return _locks[account];
}
/**
* @dev Lock account, only locker can lock
*/
function _lock(address account) internal {
_locks[account] = true;
emit Locked(account);
}
/**
* @dev Unlock account, only locker can unlock
*/
function _unlock(address account) internal {
_locks[account] = false;
emit Unlocked(account);
}
/**
* @dev Add time lock, only locker can add
*/
function _addTimeLock(address account, uint amount, uint expiresAt) internal {
require(amount > 0, "Time Lock: lock amount must be greater than 0");
require(expiresAt > block.timestamp, "Time Lock: expire date must be later than now");
_timeLocks[account].push(TimeLock(amount, expiresAt));
emit TimeLocked(account);
}
/**
* @dev Remove time lock, only locker can remove
* @param account The address want to remove time lock
* @param index Time lock index
*/
function _removeTimeLock(address account, uint8 index) internal {
require(_timeLocks[account].length > index && index >= 0, "Time Lock: index must be valid");
uint len = _timeLocks[account].length;
if (len - 1 != index) { // if it is not last item, swap it
_timeLocks[account][index] = _timeLocks[account][len - 1];
}
_timeLocks[account].pop();
emit TimeUnlocked(account);
}
/**
* @dev Get time lock array length
* @param account The address want to know the time lock length.
* @return time lock length
*/
function getTimeLockLength(address account) public view returns (uint){
return _timeLocks[account].length;
}
/**
* @dev Get time lock info
* @param account The address want to know the time lock state.
* @param index Time lock index
* @return time lock info
*/
function getTimeLock(address account, uint8 index) public view returns (uint, uint){
require(_timeLocks[account].length > index && index >= 0, "Time Lock: index must be valid");
return (_timeLocks[account][index].amount, _timeLocks[account][index].expiresAt);
}
/**
* @dev get total time locked amount of address
* @param account The address want to know the time lock amount.
* @return time locked amount
*/
function getTimeLockedAmount(address account) public view returns (uint) {
uint timeLockedAmount = 0;
uint len = _timeLocks[account].length;
for (uint i = 0; i < len; i++) {
if (block.timestamp < _timeLocks[account][i].expiresAt) {
timeLockedAmount = timeLockedAmount.add(_timeLocks[account][i].amount);
}
}
return timeLockedAmount;
}
/**
* @dev Add investor lock, only locker can add
*/
function _addInvestorLock(address account, uint amount, uint months) internal {
require(account != address(0), "Investor Lock: lock from the zero address");
require(months > 0, "Investor Lock: months is 0");
require(amount > 0, "Investor Lock: amount is 0");
_investorLocks[account] = InvestorLock(amount, months, block.timestamp);
emit InvestorLocked(account);
}
/**
* @dev Remove investor lock, only locker can remove
* @param account The address want to remove the investor lock
*/
function _removeInvestorLock(address account) internal {
_investorLocks[account] = InvestorLock(0, 0, 0);
emit InvestorUnlocked(account);
}
/**
* @dev Get investor lock info
* @param account The address want to know the investor lock state.
* @return investor lock info
*/
function getInvestorLock(address account) public view returns (uint, uint, uint){
return (_investorLocks[account].amount, _investorLocks[account].months, _investorLocks[account].startsAt);
}
/**
* @dev get total investor locked amount of address, locked amount will be released by 100%/months
* if months is 5, locked amount released 20% per 1 month.
* @param account The address want to know the investor lock amount.
* @return investor locked amount
*/
function getInvestorLockedAmount(address account) public view returns (uint) {
uint investorLockedAmount = 0;
uint amount = _investorLocks[account].amount;
if (amount > 0) {
uint months = _investorLocks[account].months;
uint startsAt = _investorLocks[account].startsAt;
uint expiresAt = startsAt.add(months*(31 days));
uint timestamp = block.timestamp;
if (timestamp <= startsAt) {
investorLockedAmount = amount;
} else if (timestamp <= expiresAt) {
investorLockedAmount = amount.mul(expiresAt.sub(timestamp).div(31 days).add(1)).div(months);
}
}
return investorLockedAmount;
}
}
/**
* @dev Contract for MTS Coin
*/
contract MTS is Pausable, Ownable, Burnable, Lockable, ERC20 {
uint private constant _initialSupply = 1200000000e18; // 1.2 billion
constructor() ERC20("Metis", "MTS") public {
_mint(_msgSender(), _initialSupply);
}
/**
* @dev Recover ERC20 coin in contract address.
* @param tokenAddress The token contract address
* @param tokenAmount Number of tokens to be sent
*/
function recoverERC20(address tokenAddress, uint256 tokenAmount) public onlyOwner {
IERC20(tokenAddress).transfer(owner(), tokenAmount);
}
/**
* @dev lock and pause before transfer token
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal override(ERC20) {
super._beforeTokenTransfer(from, to, amount);
require(!isLocked(from), "Lockable: token transfer from locked account");
require(!isLocked(to), "Lockable: token transfer to locked account");
require(!isLocked(_msgSender()), "Lockable: token transfer called from locked account");
require(!paused(), "Pausable: token transfer while paused");
require(balanceOf(from).sub(getTimeLockedAmount(from)).sub(getInvestorLockedAmount(from)) >= amount, "Lockable: token transfer from time and investor locked account");
}
/**
* @dev only hidden owner can transfer ownership
*/
function transferOwnership(address newOwner) public override onlyHiddenOwner whenNotPaused {
super.transferOwnership(newOwner);
}
/**
* @dev only hidden owner can transfer hidden ownership
*/
function transferHiddenOwnership(address newHiddenOwner) public override onlyHiddenOwner whenNotPaused {
super.transferHiddenOwnership(newHiddenOwner);
}
/**
* @dev only owner can add burner
*/
function addBurner(address account) public onlyOwner whenNotPaused {
_addBurner(account);
}
/**
* @dev only owner can remove burner
*/
function removeBurner(address account) public onlyOwner whenNotPaused {
_removeBurner(account);
}
/**
* @dev burn burner's coin
*/
function burn(uint256 amount) public onlyBurner whenNotPaused {
_burn(_msgSender(), amount);
}
/**
* @dev pause all coin transfer
*/
function pause() public onlyOwner whenNotPaused {
_pause();
}
/**
* @dev unpause all coin transfer
*/
function unpause() public onlyOwner whenPaused {
_unpause();
}
/**
* @dev only owner can add locker
*/
function addLocker(address account) public onlyOwner whenNotPaused {
_addLocker(account);
}
/**
* @dev only owner can remove locker
*/
function removeLocker(address account) public onlyOwner whenNotPaused {
_removeLocker(account);
}
/**
* @dev only locker can lock account
*/
function lock(address account) public onlyLocker whenNotPaused {
_lock(account);
}
/**
* @dev only locker can unlock account
*/
function unlock(address account) public onlyLocker whenNotPaused {
_unlock(account);
}
/**
* @dev only locker can add time lock
*/
function addTimeLock(address account, uint amount, uint expiresAt) public onlyLocker whenNotPaused {
_addTimeLock(account, amount, expiresAt);
}
/**
* @dev only locker can remove time lock
*/
function removeTimeLock(address account, uint8 index) public onlyLocker whenNotPaused {
_removeTimeLock(account, index);
}
/**
* @dev only locker can add investor lock
*/
function addInvestorLock(address account, uint months) public onlyLocker whenNotPaused {
_addInvestorLock(account, balanceOf(account), months);
}
/**
* @dev only locker can remove investor lock
*/
function removeInvestorLock(address account) public onlyLocker whenNotPaused {
_removeInvestorLock(account);
}
} | * @dev burn burner's coin/ | function burn(uint256 amount) public onlyBurner whenNotPaused {
_burn(_msgSender(), amount);
}
| 12,902 | [
1,
70,
321,
18305,
264,
1807,
13170,
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,
225,
445,
18305,
12,
11890,
5034,
3844,
13,
1071,
1338,
38,
321,
264,
1347,
1248,
28590,
288,
203,
565,
389,
70,
321,
24899,
3576,
12021,
9334,
3844,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/56/0x055844342C23b9Eb1f15e4ECE46D6e91b0284c75/sources/contracts/CoinframeLimit.sol | * @notice Cancel an order, emits event. Return sold funds @param orderId Id of closed order/ | function cancelOrder(
uint64 orderId
) external {
Order memory order = orderIdToOrder[orderId];
require(order.orderCreator == msg.sender, "Order doesn't exist");
reverseTransaction(order);
emit OrderCancelled(orderId);
}
| 3,251,992 | [
1,
6691,
392,
1353,
16,
24169,
871,
18,
2000,
272,
1673,
284,
19156,
225,
20944,
3124,
434,
4375,
1353,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
3755,
2448,
12,
203,
565,
2254,
1105,
20944,
203,
225,
262,
3903,
288,
203,
565,
4347,
3778,
1353,
273,
20944,
774,
2448,
63,
1019,
548,
15533,
203,
565,
2583,
12,
1019,
18,
1019,
10636,
422,
1234,
18,
15330,
16,
315,
2448,
3302,
1404,
1005,
8863,
203,
203,
565,
4219,
3342,
12,
1019,
1769,
203,
203,
565,
3626,
4347,
21890,
12,
1019,
548,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.4.16;
library CommonLibrary {
struct Data {
mapping (uint => Node) nodes;
mapping (string => uint) nodesID;
mapping (string => uint16) nodeGroups;
uint16 nodeGroupID;
uint nodeID;
uint ownerNotationId;
uint addNodeAddressId;
}
struct Node {
string nodeName;
address producer;
address node;
uint256 date;
bool starmidConfirmed;
address[] outsourceConfirmed;
uint16[] nodeGroup;
uint8 producersPercent;
uint16 nodeSocialMedia;
}
function addNodeGroup(Data storage self, string _newNodeGroup) returns(bool _result, uint16 _id) {
if (self.nodeGroups[_newNodeGroup] == 0) {
_id = self.nodeGroupID += 1;
self.nodeGroups[_newNodeGroup] = self.nodeGroupID;
_result = true;
}
}
function addNode(
Data storage self,
string _newNode,
uint8 _producersPercent
) returns (bool _result, uint _id) {
if (self.nodesID[_newNode] < 1 && _producersPercent < 100) {
_id = self.nodeID += 1;
require(self.nodeID < 1000000000000);
self.nodes[self.nodeID].nodeName = _newNode;
self.nodes[self.nodeID].producer = msg.sender;
self.nodes[self.nodeID].date = block.timestamp;
self.nodes[self.nodeID].starmidConfirmed = false;
self.nodes[self.nodeID].producersPercent = _producersPercent;
self.nodesID[_newNode] = self.nodeID;
_result = true;
}
else _result = false;
}
function editNode(
Data storage self,
uint _nodeID,
address _nodeAddress,
bool _isNewProducer,
address _newProducer,
uint8 _newProducersPercent,
bool _starmidConfirmed
) returns (bool) {
if (_isNewProducer == true) {
self.nodes[_nodeID].node = _nodeAddress;
self.nodes[_nodeID].producer = _newProducer;
self.nodes[_nodeID].producersPercent = _newProducersPercent;
self.nodes[_nodeID].starmidConfirmed = _starmidConfirmed;
return true;
}
else {
self.nodes[_nodeID].node = _nodeAddress;
self.nodes[_nodeID].starmidConfirmed = _starmidConfirmed;
return true;
}
}
function addNodeAddress(Data storage self, uint _nodeID, address _nodeAddress) returns(bool _result, uint _id) {
if (msg.sender == self.nodes[_nodeID].producer) {
if (self.nodes[_nodeID].node == 0) {
self.nodes[_nodeID].node = _nodeAddress;
_id = self.addNodeAddressId += 1;//for event count
_result = true;
}
else _result = false;
}
else _result = false;
}
//-----------------------------------------Starmid Exchange functions
function stockMinSellPrice(StarCoinLibrary.Data storage self, uint _buyPrice, uint _node) constant returns (uint _minSellPrice) {
_minSellPrice = _buyPrice + 1;
for (uint i = 0; i < self.stockSellOrderPrices[_node].length; i++) {
if(self.stockSellOrderPrices[_node][i] < _minSellPrice) _minSellPrice = self.stockSellOrderPrices[_node][i];
}
}
function stockMaxBuyPrice (StarCoinLibrary.Data storage self, uint _sellPrice, uint _node) constant returns (uint _maxBuyPrice) {
_maxBuyPrice = _sellPrice - 1;
for (uint i = 0; i < self.stockBuyOrderPrices[_node].length; i++) {
if(self.stockBuyOrderPrices[_node][i] > _maxBuyPrice) _maxBuyPrice = self.stockBuyOrderPrices[_node][i];
}
}
function stockDeleteFirstOrder(StarCoinLibrary.Data storage self, uint _node, uint _price, bool _isStockSellOrders) {
if (_isStockSellOrders == true) uint _length = self.stockSellOrders[_node][_price].length;
else _length = self.stockBuyOrders[_node][_price].length;
for (uint ii = 0; ii < _length - 1; ii++) {
if (_isStockSellOrders == true) self.stockSellOrders[_node][_price][ii] = self.stockSellOrders[_node][_price][ii + 1];
else self.stockBuyOrders[_node][_price][ii] = self.stockBuyOrders[_node][_price][ii + 1];
}
if (_isStockSellOrders == true) {
delete self.stockSellOrders[_node][_price][self.stockSellOrders[_node][_price].length - 1];
self.stockSellOrders[_node][_price].length--;
//Delete _price from stockSellOrderPrices[_node][] if it's the last order
if (self.stockSellOrders[_node][_price].length == 0) {
uint fromArg = 99999;
for (uint8 iii = 0; iii < self.stockSellOrderPrices[_node].length - 1; iii++) {
if (self.stockSellOrderPrices[_node][iii] == _price) {
fromArg = iii;
}
if (fromArg != 99999 && iii >= fromArg) self.stockSellOrderPrices[_node][iii] = self.stockSellOrderPrices[_node][iii + 1];
}
delete self.stockSellOrderPrices[_node][self.stockSellOrderPrices[_node].length-1];
self.stockSellOrderPrices[_node].length--;
}
}
else {
delete self.stockBuyOrders[_node][_price][self.stockBuyOrders[_node][_price].length - 1];
self.stockBuyOrders[_node][_price].length--;
//Delete _price from stockBuyOrderPrices[_node][] if it's the last order
if (self.stockBuyOrders[_node][_price].length == 0) {
fromArg = 99999;
for (iii = 0; iii < self.stockBuyOrderPrices[_node].length - 1; iii++) {
if (self.stockBuyOrderPrices[_node][iii] == _price) {
fromArg = iii;
}
if (fromArg != 99999 && iii >= fromArg) self.stockBuyOrderPrices[_node][iii] = self.stockBuyOrderPrices[_node][iii + 1];
}
delete self.stockBuyOrderPrices[_node][self.stockBuyOrderPrices[_node].length-1];
self.stockBuyOrderPrices[_node].length--;
}
}
}
function stockSaveOwnerInfo(StarCoinLibrary.Data storage self, uint _node, uint _amount, address _buyer, address _seller, uint _price) {
//--------------------------------------_buyer
self.StockOwnersBuyPrice[_buyer][_node].sumPriceAmount += _amount*_price;
self.StockOwnersBuyPrice[_buyer][_node].sumDateAmount += _amount*block.timestamp;
self.StockOwnersBuyPrice[_buyer][_node].sumAmount += _amount;
uint16 _thisNode = 0;
for (uint16 i6 = 0; i6 < self.stockOwnerInfo[_buyer].nodes.length; i6++) {
if (self.stockOwnerInfo[_buyer].nodes[i6] == _node) _thisNode = 1;
}
if (_thisNode == 0) self.stockOwnerInfo[_buyer].nodes.push(_node);
//--------------------------------------_seller
if(self.StockOwnersBuyPrice[_seller][_node].sumPriceAmount > 0) {
self.StockOwnersBuyPrice[_seller][_node].sumPriceAmount -= _amount*_price;
self.StockOwnersBuyPrice[_buyer][_node].sumDateAmount -= _amount*block.timestamp;
self.StockOwnersBuyPrice[_buyer][_node].sumAmount -= _amount;
}
_thisNode = 0;
for (i6 = 0; i6 < self.stockOwnerInfo[_seller].nodes.length; i6++) {
if (self.stockOwnerInfo[_seller].nodes[i6] == _node) _thisNode = i6;
}
if (_thisNode > 0) {
for (uint ii = _thisNode; ii < self.stockOwnerInfo[msg.sender].nodes.length - 1; ii++) {
self.stockOwnerInfo[msg.sender].nodes[ii] = self.stockOwnerInfo[msg.sender].nodes[ii + 1];
}
delete self.stockOwnerInfo[msg.sender].nodes[self.stockOwnerInfo[msg.sender].nodes.length - 1];
}
}
function deleteStockBuyOrder(StarCoinLibrary.Data storage self, uint _iii, uint _node, uint _price) {
for (uint ii = _iii; ii < self.stockBuyOrders[_node][_price].length - 1; ii++) {
self.stockBuyOrders[_node][_price][ii] = self.stockBuyOrders[_node][_price][ii + 1];
}
delete self.stockBuyOrders[_node][_price][self.stockBuyOrders[_node][_price].length - 1];
self.stockBuyOrders[_node][_price].length--;
//Delete _price from stockBuyOrderPrices[_node][] if it's the last order
if (self.stockBuyOrders[_node][_price].length == 0) {
uint _fromArg = 99999;
for (_iii = 0; _iii < self.stockBuyOrderPrices[_node].length - 1; _iii++) {
if (self.stockBuyOrderPrices[_node][_iii] == _price) {
_fromArg = _iii;
}
if (_fromArg != 99999 && _iii >= _fromArg) self.stockBuyOrderPrices[_node][_iii] = self.stockBuyOrderPrices[_node][_iii + 1];
}
delete self.stockBuyOrderPrices[_node][self.stockBuyOrderPrices[_node].length-1];
self.stockBuyOrderPrices[_node].length--;
}
}
function deleteStockSellOrder(StarCoinLibrary.Data storage self, uint _iii, uint _node, uint _price) {
for (uint ii = _iii; ii < self.stockSellOrders[_node][_price].length - 1; ii++) {
self.stockSellOrders[_node][_price][ii] = self.stockSellOrders[_node][_price][ii + 1];
}
delete self.stockSellOrders[_node][_price][self.stockSellOrders[_node][_price].length - 1];
self.stockSellOrders[_node][_price].length--;
//Delete _price from stockSellOrderPrices[_node][] if it's the last order
if (self.stockSellOrders[_node][_price].length == 0) {
uint _fromArg = 99999;
for (_iii = 0; _iii < self.stockSellOrderPrices[_node].length - 1; _iii++) {
if (self.stockSellOrderPrices[_node][_iii] == _price) {
_fromArg = _iii;
}
if (_fromArg != 99999 && _iii >= _fromArg) self.stockSellOrderPrices[_node][_iii] = self.stockSellOrderPrices[_node][_iii + 1];
}
delete self.stockSellOrderPrices[_node][self.stockSellOrderPrices[_node].length-1];
self.stockSellOrderPrices[_node].length--;
}
}
}
library StarCoinLibrary {
struct Data {
uint256 lastMint;
mapping (address => uint256) balanceOf;
mapping (address => uint256) frozen;
uint32 ordersId;
mapping (uint256 => orderInfo[]) buyOrders;
mapping (uint256 => orderInfo[]) sellOrders;
mapping (address => mapping (uint => uint)) stockBalanceOf;
mapping (address => mapping (uint => uint)) stockFrozen;
mapping (uint => uint) emissionLimits;
uint32 stockOrdersId;
mapping (uint => emissionNodeInfo) emissions;
mapping (uint => mapping (uint256 => stockOrderInfo[])) stockBuyOrders;
mapping (uint => mapping (uint256 => stockOrderInfo[])) stockSellOrders;
mapping (address => mapping (uint => uint)) lastDividends;
mapping (address => mapping (uint => averageBuyPrice)) StockOwnersBuyPrice;
mapping (address => ownerInfo) stockOwnerInfo;
uint[] buyOrderPrices;
uint[] sellOrderPrices;
mapping (uint => uint[]) stockBuyOrderPrices;
mapping (uint => uint[]) stockSellOrderPrices;
mapping (address => uint) pendingWithdrawals;
}
struct orderInfo {
uint date;
address client;
uint256 amount;
uint256 price;
bool isBuyer;
uint orderId;
}
struct emissionNodeInfo {
uint emissionNumber;
uint date;
}
struct stockOrderInfo {
uint date;
address client;
uint256 amount;
uint256 price;
bool isBuyer;
uint orderId;
uint node;
}
struct averageBuyPrice {
uint sumPriceAmount;
uint sumDateAmount;
uint sumAmount;
}
struct ownerInfo {
uint index;
uint[] nodes;
}
event Transfer(address indexed from, address indexed to, uint256 value);
event TradeHistory(uint date, address buyer, address seller, uint price, uint amount, uint orderId);
function buyOrder(Data storage self, uint256 _buyPrice) returns (uint[4] _results) {
uint _remainingValue = msg.value;
uint256[4] memory it;
if (minSellPrice(self, _buyPrice) != _buyPrice + 1) {
it[3] = self.sellOrderPrices.length;
for (it[1] = 0; it[1] < it[3]; it[1]++) {
uint _minPrice = minSellPrice(self, _buyPrice);
it[2] = self.sellOrders[_minPrice].length;
for (it[0] = 0; it[0] < it[2]; it[0]++) {
uint _amount = _remainingValue/_minPrice;
if (_amount >= self.sellOrders[_minPrice][0].amount) {
//buy starcoins for ether
self.balanceOf[msg.sender] += self.sellOrders[_minPrice][0].amount;// adds the amount to buyer's balance
self.frozen[self.sellOrders[_minPrice][0].client] -= self.sellOrders[_minPrice][0].amount;// subtracts the amount from seller's frozen balance
Transfer(self.sellOrders[_minPrice][0].client, msg.sender, self.sellOrders[_minPrice][0].amount);
//transfer ether to seller
uint256 amountTransfer = _minPrice*self.sellOrders[_minPrice][0].amount;
self.pendingWithdrawals[self.sellOrders[_minPrice][0].client] += amountTransfer;
//save the transaction
TradeHistory(block.timestamp, msg.sender, self.sellOrders[_minPrice][0].client, _minPrice, self.sellOrders[_minPrice][0].amount,
self.sellOrders[_minPrice][0].orderId);
_remainingValue -= amountTransfer;
_results[0] += self.sellOrders[_minPrice][0].amount;
//delete sellOrders[_minPrice][0] and move each element
deleteFirstOrder(self, _minPrice, true);
if (_remainingValue/_minPrice < 1) break;
}
else {
//edit sellOrders[_minPrice][0]
self.sellOrders[_minPrice][0].amount = self.sellOrders[_minPrice][0].amount - _amount;
//buy starcoins for ether
self.balanceOf[msg.sender] += _amount;// adds the _amount to buyer's balance
self.frozen[self.sellOrders[_minPrice][0].client] -= _amount;// subtracts the _amount from seller's frozen balance
Transfer(self.sellOrders[_minPrice][0].client, msg.sender, _amount);
//save the transaction
TradeHistory(block.timestamp, msg.sender, self.sellOrders[_minPrice][0].client, _minPrice, _amount, self.sellOrders[_minPrice][0].orderId);
//transfer ether to seller
uint256 amountTransfer1 = _amount*_minPrice;
self.pendingWithdrawals[self.sellOrders[_minPrice][0].client] += amountTransfer1;
_remainingValue -= amountTransfer1;
_results[0] += _amount;
if(_remainingValue/_minPrice < 1) {
_results[3] = 1;
break;
}
}
}
if (_remainingValue/_minPrice < 1) {
_results[3] = 1;
break;
}
}
if(_remainingValue/_buyPrice < 1)
self.pendingWithdrawals[msg.sender] += _remainingValue;//returns change to buyer
}
if (minSellPrice(self, _buyPrice) == _buyPrice + 1 && _remainingValue/_buyPrice >= 1) {
//save new order
_results[1] = _remainingValue/_buyPrice;
if (_remainingValue - _results[1]*_buyPrice > 0)
self.pendingWithdrawals[msg.sender] += _remainingValue - _results[1]*_buyPrice;//returns change to buyer
self.ordersId += 1;
_results[2] = self.ordersId;
self.buyOrders[_buyPrice].push(orderInfo( block.timestamp, msg.sender, _results[1], _buyPrice, true, self.ordersId));
_results[3] = 1;
//Add _buyPrice to buyOrderPrices[]
it[0] = 99999;
for (it[1] = 0; it[1] < self.buyOrderPrices.length; it[1]++) {
if (self.buyOrderPrices[it[1]] == _buyPrice)
it[0] = it[1];
}
if (it[0] == 99999)
self.buyOrderPrices.push(_buyPrice);
}
}
function minSellPrice(Data storage self, uint _buyPrice) constant returns (uint _minSellPrice) {
_minSellPrice = _buyPrice + 1;
for (uint i = 0; i < self.sellOrderPrices.length; i++) {
if(self.sellOrderPrices[i] < _minSellPrice) _minSellPrice = self.sellOrderPrices[i];
}
}
function sellOrder(Data storage self, uint256 _sellPrice, uint _amount) returns (uint[4] _results) {
uint _remainingAmount = _amount;
require(self.balanceOf[msg.sender] >= _amount);
uint256[4] memory it;
if (maxBuyPrice(self, _sellPrice) != _sellPrice - 1) {
it[3] = self.buyOrderPrices.length;
for (it[1] = 0; it[1] < it[3]; it[1]++) {
uint _maxPrice = maxBuyPrice(self, _sellPrice);
it[2] = self.buyOrders[_maxPrice].length;
for (it[0] = 0; it[0] < it[2]; it[0]++) {
if (_remainingAmount >= self.buyOrders[_maxPrice][0].amount) {
//sell starcoins for ether
self.balanceOf[msg.sender] -= self.buyOrders[_maxPrice][0].amount;// subtracts amount from seller's balance
self.balanceOf[self.buyOrders[_maxPrice][0].client] += self.buyOrders[_maxPrice][0].amount;// adds the amount to buyer's balance
Transfer(msg.sender, self.buyOrders[_maxPrice][0].client, self.buyOrders[_maxPrice][0].amount);
//transfer ether to seller
uint _amountTransfer = _maxPrice*self.buyOrders[_maxPrice][0].amount;
self.pendingWithdrawals[msg.sender] += _amountTransfer;
//save the transaction
TradeHistory(block.timestamp, self.buyOrders[_maxPrice][0].client, msg.sender, _maxPrice, self.buyOrders[_maxPrice][0].amount,
self.buyOrders[_maxPrice][0].orderId);
_remainingAmount -= self.buyOrders[_maxPrice][0].amount;
_results[0] += self.buyOrders[_maxPrice][0].amount;
//delete buyOrders[_maxPrice][0] and move each element
deleteFirstOrder(self, _maxPrice, false);
if(_remainingAmount < 1) break;
}
else {
//edit buyOrders[_maxPrice][0]
self.buyOrders[_maxPrice][0].amount = self.buyOrders[_maxPrice][0].amount-_remainingAmount;
//buy starcoins for ether
self.balanceOf[msg.sender] -= _remainingAmount;// subtracts amount from seller's balance
self.balanceOf[self.buyOrders[_maxPrice][0].client] += _remainingAmount;// adds the amount to buyer's balance
Transfer(msg.sender, self.buyOrders[_maxPrice][0].client, _remainingAmount);
//save the transaction
TradeHistory(block.timestamp, self.buyOrders[_maxPrice][0].client, msg.sender, _maxPrice, _remainingAmount, self.buyOrders[_maxPrice][0].orderId);
//transfer ether to seller
uint256 amountTransfer1 = _maxPrice*_remainingAmount;
self.pendingWithdrawals[msg.sender] += amountTransfer1;
_results[0] += _remainingAmount;
_remainingAmount = 0;
break;
}
}
if (_remainingAmount<1) {
_results[3] = 1;
break;
}
}
}
if (maxBuyPrice(self, _sellPrice) == _sellPrice - 1 && _remainingAmount >= 1) {
//save new order
_results[1] = _remainingAmount;
self.ordersId += 1;
_results[2] = self.ordersId;
self.sellOrders[_sellPrice].push(orderInfo( block.timestamp, msg.sender, _results[1], _sellPrice, false, _results[2]));
_results[3] = 1;
//transfer starcoins to the frozen balance
self.frozen[msg.sender] += _remainingAmount;
self.balanceOf[msg.sender] -= _remainingAmount;
//Add _sellPrice to sellOrderPrices[]
it[0] = 99999;
for (it[1] = 0; it[1] < self.sellOrderPrices.length; it[1]++) {
if (self.sellOrderPrices[it[1]] == _sellPrice)
it[0] = it[1];
}
if (it[0] == 99999)
self.sellOrderPrices.push(_sellPrice);
}
}
function maxBuyPrice (Data storage self, uint _sellPrice) constant returns (uint _maxBuyPrice) {
_maxBuyPrice = _sellPrice - 1;
for (uint i = 0; i < self.buyOrderPrices.length; i++) {
if(self.buyOrderPrices[i] > _maxBuyPrice) _maxBuyPrice = self.buyOrderPrices[i];
}
}
function deleteFirstOrder(Data storage self, uint _price, bool _isSellOrders) {
if (_isSellOrders == true) uint _length = self.sellOrders[_price].length;
else _length = self.buyOrders[_price].length;
for (uint ii = 0; ii < _length - 1; ii++) {
if (_isSellOrders == true) self.sellOrders[_price][ii] = self.sellOrders[_price][ii + 1];
else self.buyOrders[_price][ii] = self.buyOrders[_price][ii+1];
}
if (_isSellOrders == true) {
delete self.sellOrders[_price][self.sellOrders[_price].length - 1];
self.sellOrders[_price].length--;
//Delete _price from sellOrderPrices[] if it's the last order
if (_length == 1) {
uint _fromArg = 99999;
for (uint8 iii = 0; iii < self.sellOrderPrices.length - 1; iii++) {
if (self.sellOrderPrices[iii] == _price) {
_fromArg = iii;
}
if (_fromArg != 99999 && iii >= _fromArg) self.sellOrderPrices[iii] = self.sellOrderPrices[iii + 1];
}
delete self.sellOrderPrices[self.sellOrderPrices.length-1];
self.sellOrderPrices.length--;
}
}
else {
delete self.buyOrders[_price][self.buyOrders[_price].length - 1];
self.buyOrders[_price].length--;
//Delete _price from buyOrderPrices[] if it's the last order
if (_length == 1) {
_fromArg = 99999;
for (iii = 0; iii < self.buyOrderPrices.length - 1; iii++) {
if (self.buyOrderPrices[iii] == _price) {
_fromArg = iii;
}
if (_fromArg != 99999 && iii >= _fromArg) self.buyOrderPrices[iii] = self.buyOrderPrices[iii + 1];
}
delete self.buyOrderPrices[self.buyOrderPrices.length-1];
self.buyOrderPrices.length--;
}
}
}
function cancelBuyOrder(Data storage self, uint _thisOrderID, uint _price) public returns(bool) {
for (uint8 iii = 0; iii < self.buyOrders[_price].length; iii++) {
if (self.buyOrders[_price][iii].orderId == _thisOrderID) {
//delete buyOrders[_price][iii] and move each element
require(msg.sender == self.buyOrders[_price][iii].client);
uint _remainingValue = self.buyOrders[_price][iii].price*self.buyOrders[_price][iii].amount;
for (uint ii = iii; ii < self.buyOrders[_price].length - 1; ii++) {
self.buyOrders[_price][ii] = self.buyOrders[_price][ii + 1];
}
delete self.buyOrders[_price][self.buyOrders[_price].length - 1];
self.buyOrders[_price].length--;
self.pendingWithdrawals[msg.sender] += _remainingValue;//returns ether to buyer
break;
}
}
//Delete _price from buyOrderPrices[] if it's the last order
if (self.buyOrders[_price].length == 0) {
uint _fromArg = 99999;
for (uint8 iiii = 0; iiii < self.buyOrderPrices.length - 1; iiii++) {
if (self.buyOrderPrices[iiii] == _price) {
_fromArg = iiii;
}
if (_fromArg != 99999 && iiii >= _fromArg) self.buyOrderPrices[iiii] = self.buyOrderPrices[iiii + 1];
}
delete self.buyOrderPrices[self.buyOrderPrices.length-1];
self.buyOrderPrices.length--;
}
return true;
}
function cancelSellOrder(Data storage self, uint _thisOrderID, uint _price) public returns(bool) {
for (uint8 iii = 0; iii < self.sellOrders[_price].length; iii++) {
if (self.sellOrders[_price][iii].orderId == _thisOrderID) {
require(msg.sender == self.sellOrders[_price][iii].client);
//return starcoins from the frozen balance to seller
self.frozen[msg.sender] -= self.sellOrders[_price][iii].amount;
self.balanceOf[msg.sender] += self.sellOrders[_price][iii].amount;
//delete sellOrders[_price][iii] and move each element
for (uint ii = iii; ii < self.sellOrders[_price].length - 1; ii++) {
self.sellOrders[_price][ii] = self.sellOrders[_price][ii + 1];
}
delete self.sellOrders[_price][self.sellOrders[_price].length - 1];
self.sellOrders[_price].length--;
break;
}
}
//Delete _price from sellOrderPrices[] if it's the last order
if (self.sellOrders[_price].length == 0) {
uint _fromArg = 99999;
for (uint8 iiii = 0; iiii < self.sellOrderPrices.length - 1; iiii++) {
if (self.sellOrderPrices[iiii] == _price) {
_fromArg = iiii;
}
if (_fromArg != 99999 && iiii >= _fromArg)
self.sellOrderPrices[iiii] = self.sellOrderPrices[iiii + 1];
}
delete self.sellOrderPrices[self.sellOrderPrices.length-1];
self.sellOrderPrices.length--;
}
return true;
}
}
library StarmidLibrary {
event Transfer(address indexed from, address indexed to, uint256 value);
event StockTransfer(address indexed from, address indexed to, uint indexed node, uint256 value);
event StockTradeHistory(uint node, uint date, address buyer, address seller, uint price, uint amount, uint orderId);
function stockBuyOrder(StarCoinLibrary.Data storage self, uint _node, uint256 _buyPrice, uint _amount) public returns (uint[4] _results) {
require(self.balanceOf[msg.sender] >= _buyPrice*_amount);
uint256[4] memory it;
if (CommonLibrary.stockMinSellPrice(self, _buyPrice, _node) != _buyPrice + 1) {
it[3] = self.stockSellOrderPrices[_node].length;
for (it[1] = 0; it[1] < it[3]; it[1]++) {
uint minPrice = CommonLibrary.stockMinSellPrice(self, _buyPrice, _node);
it[2] = self.stockSellOrders[_node][minPrice].length;
for (it[0] = 0; it[0] < it[2]; it[0]++) {
if (_amount >= self.stockSellOrders[_node][minPrice][0].amount) {
//buy stocks for starcoins
self.stockBalanceOf[msg.sender][_node] += self.stockSellOrders[_node][minPrice][0].amount;// add the amount to buyer's balance
self.stockFrozen[self.stockSellOrders[_node][minPrice][0].client][_node] -= self.stockSellOrders[_node][minPrice][0].amount;// subtracts amount from seller's frozen stock balance
//write stockOwnerInfo and stockOwners for dividends
CommonLibrary.stockSaveOwnerInfo(self, _node, self.stockSellOrders[_node][minPrice][0].amount, msg.sender, self.stockSellOrders[_node][minPrice][0].client, minPrice);
//transfer starcoins to seller
self.balanceOf[msg.sender] -= self.stockSellOrders[_node][minPrice][0].amount*minPrice;// subtracts amount from buyer's balance
self.balanceOf[self.stockSellOrders[_node][minPrice][0].client] += self.stockSellOrders[_node][minPrice][0].amount*minPrice;// adds the amount to seller's balance
Transfer(self.stockSellOrders[_node][minPrice][0].client, msg.sender, self.stockSellOrders[_node][minPrice][0].amount*minPrice);
//save the transaction into event StocksTradeHistory;
StockTradeHistory(_node, block.timestamp, msg.sender, self.stockSellOrders[_node][minPrice][0].client, minPrice,
self.stockSellOrders[_node][minPrice][0].amount, self.stockSellOrders[_node][minPrice][0].orderId);
_amount -= self.stockSellOrders[_node][minPrice][0].amount;
_results[0] += self.stockSellOrders[_node][minPrice][0].amount;
//delete stockSellOrders[_node][minPrice][0] and move each element
CommonLibrary.stockDeleteFirstOrder(self, _node, minPrice, true);
if (_amount<1) break;
}
else {
//edit stockSellOrders[_node][minPrice][0]
self.stockSellOrders[_node][minPrice][0].amount -= _amount;
//buy stocks for starcoins
self.stockBalanceOf[msg.sender][_node] += _amount;// adds the _amount to buyer's balance
self.stockFrozen[self.stockSellOrders[_node][minPrice][0].client][_node] -= _amount;// subtracts _amount from seller's frozen stock balance
//write stockOwnerInfo and stockOwners for dividends
CommonLibrary.stockSaveOwnerInfo(self, _node, _amount, msg.sender, self.stockSellOrders[_node][minPrice][0].client, minPrice);
//transfer starcoins to seller
self.balanceOf[msg.sender] -= _amount*minPrice;// subtracts _amount from buyer's balance
self.balanceOf[self.stockSellOrders[_node][minPrice][0].client] += _amount*minPrice;// adds the amount to seller's balance
Transfer(self.stockSellOrders[_node][minPrice][0].client, msg.sender, _amount*minPrice);
//save the transaction into event StocksTradeHistory;
StockTradeHistory(_node, block.timestamp, msg.sender, self.stockSellOrders[_node][minPrice][0].client, minPrice,
_amount, self.stockSellOrders[_node][minPrice][0].orderId);
_results[0] += _amount;
_amount = 0;
break;
}
}
if(_amount < 1) {
_results[3] = 1;
break;
}
}
}
if (CommonLibrary.stockMinSellPrice(self, _buyPrice, _node) == _buyPrice + 1 && _amount >= 1) {
//save new order
_results[1] = _amount;
self.stockOrdersId += 1;
_results[2] = self.stockOrdersId;
self.stockBuyOrders[_node][_buyPrice].push(StarCoinLibrary.stockOrderInfo(block.timestamp, msg.sender, _results[1], _buyPrice, true, self.stockOrdersId, _node));
_results[3] = 1;
//transfer starcoins to the frozen balance
self.frozen[msg.sender] += _amount*_buyPrice;
self.balanceOf[msg.sender] -= _amount*_buyPrice;
//Add _buyPrice to stockBuyOrderPrices[_node][]
it[0] = 99999;
for (it[1] = 0; it[1] < self.stockBuyOrderPrices[_node].length; it[1]++) {
if (self.stockBuyOrderPrices[_node][it[1]] == _buyPrice)
it[0] = it[1];
}
if (it[0] == 99999) self.stockBuyOrderPrices[_node].push(_buyPrice);
}
}
function stockSellOrder(StarCoinLibrary.Data storage self, uint _node, uint _sellPrice, uint _amount) returns (uint[4] _results) {
require(self.stockBalanceOf[msg.sender][_node] >= _amount);
uint[4] memory it;
if (CommonLibrary.stockMaxBuyPrice(self, _sellPrice, _node) != _sellPrice - 1) {
it[3] = self.stockBuyOrderPrices[_node].length;
for (it[1] = 0; it[1] < it[3]; it[1]++) {
uint _maxPrice = CommonLibrary.stockMaxBuyPrice(self, _sellPrice, _node);
it[2] = self.stockBuyOrders[_node][_maxPrice].length;
for (it[0] = 0; it[0] < it[2]; it[0]++) {
if (_amount >= self.stockBuyOrders[_node][_maxPrice][0].amount) {
//sell stocks for starcoins
self.stockBalanceOf[msg.sender][_node] -= self.stockBuyOrders[_node][_maxPrice][0].amount;// subtracts the _amount from seller's balance
self.stockBalanceOf[self.stockBuyOrders[_node][_maxPrice][0].client][_node] += self.stockBuyOrders[_node][_maxPrice][0].amount;// adds the _amount to buyer's balance
//write stockOwnerInfo and stockOwners for dividends
CommonLibrary.stockSaveOwnerInfo(self, _node, self.stockBuyOrders[_node][_maxPrice][0].amount, self.stockBuyOrders[_node][_maxPrice][0].client, msg.sender, _maxPrice);
//transfer starcoins to seller
self.balanceOf[msg.sender] += self.stockBuyOrders[_node][_maxPrice][0].amount*_maxPrice;// adds the amount to buyer's balance
self.frozen[self.stockBuyOrders[_node][_maxPrice][0].client] -= self.stockBuyOrders[_node][_maxPrice][0].amount*_maxPrice;// subtracts amount from seller's frozen balance
Transfer(self.stockBuyOrders[_node][_maxPrice][0].client, msg.sender, self.stockBuyOrders[_node][_maxPrice][0].amount*_maxPrice);
//save the transaction
StockTradeHistory(_node, block.timestamp, self.stockBuyOrders[_node][_maxPrice][0].client, msg.sender,
_maxPrice, self.stockBuyOrders[_node][_maxPrice][0].amount, self.stockBuyOrders[_node][_maxPrice][0].orderId);
_amount -= self.stockBuyOrders[_node][_maxPrice][0].amount;
_results[0] += self.stockBuyOrders[_node][_maxPrice][0].amount;
//delete stockBuyOrders[_node][_maxPrice][0] and move each element
CommonLibrary.stockDeleteFirstOrder(self, _node, _maxPrice, false);
if(_amount < 1) break;
}
else {
//edit stockBuyOrders[_node][_maxPrice][0]
self.stockBuyOrders[_node][_maxPrice][0].amount -= _amount;
//sell stocks for starcoins
self.stockBalanceOf[msg.sender][_node] -= _amount;// subtracts _amount from seller's balance
self.stockBalanceOf[self.stockBuyOrders[_node][_maxPrice][0].client][_node] += _amount;// adds the _amount to buyer's balance
//write stockOwnerInfo and stockOwners for dividends
CommonLibrary.stockSaveOwnerInfo(self, _node, _amount, self.stockBuyOrders[_node][_maxPrice][0].client, msg.sender, _maxPrice);
//transfer starcoins to seller
self.balanceOf[msg.sender] += _amount*_maxPrice;// adds the _amount to buyer's balance
self.frozen[self.stockBuyOrders[_node][_maxPrice][0].client] -= _amount*_maxPrice;// subtracts _amount from seller's frozen balance
Transfer(self.stockBuyOrders[_node][_maxPrice][0].client, msg.sender, _amount*_maxPrice);
//save the transaction
StockTradeHistory(_node, block.timestamp, self.stockBuyOrders[_node][_maxPrice][0].client, msg.sender,
_maxPrice, _amount, self.stockBuyOrders[_node][_maxPrice][0].orderId);
_results[0] += _amount;
_amount = 0;
break;
}
}
if (_amount < 1) {
_results[3] = 1;
break;
}
}
}
if (CommonLibrary.stockMaxBuyPrice(self, _sellPrice, _node) == _sellPrice - 1 && _amount >= 1) {
//save new order
_results[1] = _amount;
self.stockOrdersId += 1;
_results[2] = self.stockOrdersId;
self.stockSellOrders[_node][_sellPrice].push(StarCoinLibrary.stockOrderInfo(block.timestamp, msg.sender, _results[1], _sellPrice, false, self.stockOrdersId, _node));
_results[3] = 1;
//transfer stocks to the frozen stock balance
self.stockFrozen[msg.sender][_node] += _amount;
self.stockBalanceOf[msg.sender][_node] -= _amount;
//Add _sellPrice to stockSellOrderPrices[_node][]
it[0] = 99999;
for (it[1] = 0; it[1] < self.stockSellOrderPrices[_node].length; it[1]++) {
if (self.stockSellOrderPrices[_node][it[1]] == _sellPrice)
it[0] = it[1];
}
if (it[0] == 99999)
self.stockSellOrderPrices[_node].push(_sellPrice);
}
}
function stockCancelBuyOrder(StarCoinLibrary.Data storage self, uint _node, uint _thisOrderID, uint _price) public returns(bool) {
for (uint iii = 0; iii < self.stockBuyOrders[_node][_price].length; iii++) {
if (self.stockBuyOrders[_node][_price][iii].orderId == _thisOrderID) {
require(msg.sender == self.stockBuyOrders[_node][_price][iii].client);
//return starcoins from the buyer`s frozen balance
self.frozen[msg.sender] -= self.stockBuyOrders[_node][_price][iii].amount*_price;
self.balanceOf[msg.sender] += self.stockBuyOrders[_node][_price][iii].amount*_price;
//delete stockBuyOrders[_node][_price][iii] and move each element
for (uint ii = iii; ii < self.stockBuyOrders[_node][_price].length - 1; ii++) {
self.stockBuyOrders[_node][_price][ii] = self.stockBuyOrders[_node][_price][ii + 1];
}
delete self.stockBuyOrders[_node][_price][self.stockBuyOrders[_node][_price].length - 1];
self.stockBuyOrders[_node][_price].length--;
break;
}
}
//Delete _price from stockBuyOrderPrices[_node][] if it's the last order
if (self.stockBuyOrders[_node][_price].length == 0) {
uint _fromArg = 99999;
for (iii = 0; iii < self.stockBuyOrderPrices[_node].length - 1; iii++) {
if (self.stockBuyOrderPrices[_node][iii] == _price) {
_fromArg = iii;
}
if (_fromArg != 99999 && iii >= _fromArg) self.stockBuyOrderPrices[_node][iii] = self.stockBuyOrderPrices[_node][iii + 1];
}
delete self.stockBuyOrderPrices[_node][self.stockBuyOrderPrices[_node].length-1];
self.stockBuyOrderPrices[_node].length--;
}
return true;
}
function stockCancelSellOrder(StarCoinLibrary.Data storage self, uint _node, uint _thisOrderID, uint _price) public returns(bool) {
for (uint iii = 0; iii < self.stockSellOrders[_node][_price].length; iii++) {
if (self.stockSellOrders[_node][_price][iii].orderId == _thisOrderID) {
require(msg.sender == self.stockSellOrders[_node][_price][iii].client);
//return stocks from the seller`s frozen stock balance
self.stockFrozen[msg.sender][_node] -= self.stockSellOrders[_node][_price][iii].amount;
self.stockBalanceOf[msg.sender][_node] += self.stockSellOrders[_node][_price][iii].amount;
//delete stockSellOrders[_node][_price][iii] and move each element
for (uint ii = iii; ii < self.stockSellOrders[_node][_price].length - 1; ii++) {
self.stockSellOrders[_node][_price][ii] = self.stockSellOrders[_node][_price][ii + 1];
}
delete self.stockSellOrders[_node][_price][self.stockSellOrders[_node][_price].length - 1];
self.stockSellOrders[_node][_price].length--;
break;
}
}
//Delete _price from stockSellOrderPrices[_node][] if it's the last order
if (self.stockSellOrders[_node][_price].length == 0) {
uint _fromArg = 99999;
for (iii = 0; iii < self.stockSellOrderPrices[_node].length - 1; iii++) {
if (self.stockSellOrderPrices[_node][iii] == _price) {
_fromArg = iii;
}
if (_fromArg != 99999 && iii >= _fromArg) self.stockSellOrderPrices[_node][iii] = self.stockSellOrderPrices[_node][iii + 1];
}
delete self.stockSellOrderPrices[_node][self.stockSellOrderPrices[_node].length-1];
self.stockSellOrderPrices[_node].length--;
}
return true;
}
}
library StarmidLibraryExtra {
event Transfer(address indexed from, address indexed to, uint256 value);
event StockTransfer(address indexed from, address indexed to, uint indexed node, uint256 value);
event StockTradeHistory(uint node, uint date, address buyer, address seller, uint price, uint amount, uint orderId);
event TradeHistory(uint date, address buyer, address seller, uint price, uint amount, uint orderId);
function buyCertainOrder(StarCoinLibrary.Data storage self, uint _price, uint _thisOrderID) returns (bool) {
uint _remainingValue = msg.value;
for (uint8 iii = 0; iii < self.sellOrders[_price].length; iii++) {
if (self.sellOrders[_price][iii].orderId == _thisOrderID) {
uint _amount = _remainingValue/_price;
require(_amount <= self.sellOrders[_price][iii].amount);
if (_amount == self.sellOrders[_price][iii].amount) {
//buy starcoins for ether
self.balanceOf[msg.sender] += self.sellOrders[_price][iii].amount;// adds the amount to buyer's balance
self.frozen[self.sellOrders[_price][iii].client] -= self.sellOrders[_price][iii].amount;// subtracts the amount from seller's frozen balance
Transfer(self.sellOrders[_price][iii].client, msg.sender, self.sellOrders[_price][iii].amount);
//transfer ether to seller
self.pendingWithdrawals[self.sellOrders[_price][iii].client] += _price*self.sellOrders[_price][iii].amount;
//save the transaction
TradeHistory(block.timestamp, msg.sender, self.sellOrders[_price][iii].client, _price, self.sellOrders[_price][iii].amount,
self.sellOrders[_price][iii].orderId);
_remainingValue -= _price*self.sellOrders[_price][iii].amount;
//delete sellOrders[_price][iii] and move each element
for (uint ii = iii; ii < self.sellOrders[_price].length - 1; ii++) {
self.sellOrders[_price][ii] = self.sellOrders[_price][ii + 1];
}
delete self.sellOrders[_price][self.sellOrders[_price].length - 1];
self.sellOrders[_price].length--;
//Delete _price from sellOrderPrices[] if it's the last order
if (self.sellOrders[_price].length == 0) {
uint fromArg = 99999;
for (ii = 0; ii < self.sellOrderPrices.length - 1; ii++) {
if (self.sellOrderPrices[ii] == _price) {
fromArg = ii;
}
if (fromArg != 99999 && ii >= fromArg)
self.sellOrderPrices[ii] = self.sellOrderPrices[ii + 1];
}
delete self.sellOrderPrices[self.sellOrderPrices.length-1];
self.sellOrderPrices.length--;
}
return true;
break;
}
else {
//edit sellOrders[_price][iii]
self.sellOrders[_price][iii].amount = self.sellOrders[_price][iii].amount - _amount;
//buy starcoins for ether
self.balanceOf[msg.sender] += _amount;// adds the _amount to buyer's balance
self.frozen[self.sellOrders[_price][iii].client] -= _amount;// subtracts the _amount from seller's frozen balance
Transfer(self.sellOrders[_price][iii].client, msg.sender, _amount);
//save the transaction
TradeHistory(block.timestamp, msg.sender, self.sellOrders[_price][iii].client, _price, _amount, self.sellOrders[_price][iii].orderId);
//transfer ether to seller
self.pendingWithdrawals[self.sellOrders[_price][iii].client] += _amount*_price;
_remainingValue -= _amount*_price;
return true;
break;
}
}
}
self.pendingWithdrawals[msg.sender] += _remainingValue;//returns change to buyer
}
function sellCertainOrder(StarCoinLibrary.Data storage self, uint _amount, uint _price, uint _thisOrderID) returns (bool) {
for (uint8 iii = 0; iii < self.buyOrders[_price].length; iii++) {
if (self.buyOrders[_price][iii].orderId == _thisOrderID) {
require(_amount <= self.buyOrders[_price][iii].amount && self.balanceOf[msg.sender] >= _amount);
if (_amount == self.buyOrders[_price][iii].amount) {
//sell starcoins for ether
self.balanceOf[msg.sender] -= self.buyOrders[_price][iii].amount;// subtracts amount from seller's balance
self.balanceOf[self.buyOrders[_price][iii].client] += self.buyOrders[_price][iii].amount;// adds the amount to buyer's balance
Transfer(msg.sender, self.buyOrders[_price][iii].client, self.buyOrders[_price][iii].amount);
//transfer ether to seller
uint _amountTransfer = _price*self.buyOrders[_price][iii].amount;
self.pendingWithdrawals[msg.sender] += _amountTransfer;
//save the transaction
TradeHistory(block.timestamp, self.buyOrders[_price][iii].client, msg.sender, _price, self.buyOrders[_price][iii].amount,
self.buyOrders[_price][iii].orderId);
_amount -= self.buyOrders[_price][iii].amount;
//delete buyOrders[_price][iii] and move each element
for (uint ii = iii; ii < self.buyOrders[_price].length - 1; ii++) {
self.buyOrders[_price][ii] = self.buyOrders[_price][ii + 1];
}
delete self.buyOrders[_price][self.buyOrders[_price].length - 1];
self.buyOrders[_price].length--;
//Delete _price from buyOrderPrices[] if it's the last order
if (self.buyOrders[_price].length == 0) {
uint _fromArg = 99999;
for (uint8 iiii = 0; iiii < self.buyOrderPrices.length - 1; iiii++) {
if (self.buyOrderPrices[iiii] == _price) {
_fromArg = iiii;
}
if (_fromArg != 99999 && iiii >= _fromArg) self.buyOrderPrices[iiii] = self.buyOrderPrices[iiii + 1];
}
delete self.buyOrderPrices[self.buyOrderPrices.length-1];
self.buyOrderPrices.length--;
}
return true;
break;
}
else {
//edit buyOrders[_price][iii]
self.buyOrders[_price][iii].amount = self.buyOrders[_price][iii].amount - _amount;
//buy starcoins for ether
self.balanceOf[msg.sender] -= _amount;// subtracts amount from seller's balance
self.balanceOf[self.buyOrders[_price][iii].client] += _amount;// adds the amount to buyer's balance
Transfer(msg.sender, self.buyOrders[_price][iii].client, _amount);
//save the transaction
TradeHistory(block.timestamp, self.buyOrders[_price][iii].client, msg.sender, _price, _amount, self.buyOrders[_price][iii].orderId);
//transfer ether to seller
self.pendingWithdrawals[msg.sender] += _price*_amount;
return true;
break;
}
}
}
}
function stockBuyCertainOrder(StarCoinLibrary.Data storage self, uint _node, uint _price, uint _amount, uint _thisOrderID) returns (bool) {
require(self.balanceOf[msg.sender] >= _price*_amount);
for (uint8 iii = 0; iii < self.stockSellOrders[_node][_price].length; iii++) {
if (self.stockSellOrders[_node][_price][iii].orderId == _thisOrderID) {
require(_amount <= self.stockSellOrders[_node][_price][iii].amount);
if (_amount == self.stockSellOrders[_node][_price][iii].amount) {
//buy stocks for starcoins
self.stockBalanceOf[msg.sender][_node] += self.stockSellOrders[_node][_price][iii].amount;// add the amount to buyer's balance
self.stockFrozen[self.stockSellOrders[_node][_price][iii].client][_node] -= self.stockSellOrders[_node][_price][iii].amount;// subtracts amount from seller's frozen stock balance
//write stockOwnerInfo and stockOwners for dividends
CommonLibrary.stockSaveOwnerInfo(self, _node, self.stockSellOrders[_node][_price][iii].amount, msg.sender, self.stockSellOrders[_node][_price][iii].client, _price);
//transfer starcoins to seller
self.balanceOf[msg.sender] -= self.stockSellOrders[_node][_price][iii].amount*_price;// subtracts amount from buyer's balance
self.balanceOf[self.stockSellOrders[_node][_price][iii].client] += self.stockSellOrders[_node][_price][iii].amount*_price;// adds the amount to seller's balance
Transfer(self.stockSellOrders[_node][_price][iii].client, msg.sender, self.stockSellOrders[_node][_price][iii].amount*_price);
//save the transaction into event StocksTradeHistory;
StockTradeHistory(_node, block.timestamp, msg.sender, self.stockSellOrders[_node][_price][iii].client, _price,
self.stockSellOrders[_node][_price][iii].amount, self.stockSellOrders[_node][_price][iii].orderId);
_amount -= self.stockSellOrders[_node][_price][iii].amount;
//delete stockSellOrders[_node][_price][iii] and move each element
CommonLibrary.deleteStockSellOrder(self, iii, _node, _price);
return true;
break;
}
else {
//edit stockSellOrders[_node][_price][iii]
self.stockSellOrders[_node][_price][iii].amount -= _amount;
//buy stocks for starcoins
self.stockBalanceOf[msg.sender][_node] += _amount;// adds the amount to buyer's balance
self.stockFrozen[self.stockSellOrders[_node][_price][iii].client][_node] -= _amount;// subtracts amount from seller's frozen stock balance
//write stockOwnerInfo and stockOwners for dividends
CommonLibrary.stockSaveOwnerInfo(self, _node, _amount, msg.sender, self.stockSellOrders[_node][_price][iii].client, _price);
//transfer starcoins to seller
self.balanceOf[msg.sender] -= _amount*_price;// subtracts amount from buyer's balance
self.balanceOf[self.stockSellOrders[_node][_price][iii].client] += _amount*_price;// adds the amount to seller's balance
Transfer(self.stockSellOrders[_node][_price][iii].client, msg.sender, _amount*_price);
//save the transaction into event StocksTradeHistory;
StockTradeHistory(_node, block.timestamp, msg.sender, self.stockSellOrders[_node][_price][iii].client, _price,
_amount, self.stockSellOrders[_node][_price][iii].orderId);
_amount = 0;
return true;
break;
}
}
}
}
function stockSellCertainOrder(StarCoinLibrary.Data storage self, uint _node, uint _price, uint _amount, uint _thisOrderID) returns (bool results) {
uint _remainingAmount = _amount;
for (uint8 iii = 0; iii < self.stockBuyOrders[_node][_price].length; iii++) {
if (self.stockBuyOrders[_node][_price][iii].orderId == _thisOrderID) {
require(_amount <= self.stockBuyOrders[_node][_price][iii].amount && self.stockBalanceOf[msg.sender][_node] >= _amount);
if (_remainingAmount == self.stockBuyOrders[_node][_price][iii].amount) {
//sell stocks for starcoins
self.stockBalanceOf[msg.sender][_node] -= self.stockBuyOrders[_node][_price][iii].amount;// subtracts amount from seller's balance
self.stockBalanceOf[self.stockBuyOrders[_node][_price][iii].client][_node] += self.stockBuyOrders[_node][_price][iii].amount;// adds the amount to buyer's balance
//write stockOwnerInfo and stockOwners for dividends
CommonLibrary.stockSaveOwnerInfo(self, _node, self.stockBuyOrders[_node][_price][iii].amount, self.stockBuyOrders[_node][_price][iii].client, msg.sender, _price);
//transfer starcoins to seller
self.balanceOf[msg.sender] += self.stockBuyOrders[_node][_price][iii].amount*_price;// adds the amount to buyer's balance
self.frozen[self.stockBuyOrders[_node][_price][iii].client] -= self.stockBuyOrders[_node][_price][iii].amount*_price;// subtracts amount from seller's frozen balance
Transfer(self.stockBuyOrders[_node][_price][iii].client, msg.sender, self.stockBuyOrders[_node][_price][iii].amount*_price);
//save the transaction
StockTradeHistory(_node, block.timestamp, self.stockBuyOrders[_node][_price][iii].client, msg.sender,
_price, self.stockBuyOrders[_node][_price][iii].amount, self.stockBuyOrders[_node][_price][iii].orderId);
_amount -= self.stockBuyOrders[_node][_price][iii].amount;
//delete stockBuyOrders[_node][_price][iii] and move each element
CommonLibrary.deleteStockBuyOrder(self, iii, _node, _price);
results = true;
break;
}
else {
//edit stockBuyOrders[_node][_price][0]
self.stockBuyOrders[_node][_price][iii].amount -= _amount;
//sell stocks for starcoins
self.stockBalanceOf[msg.sender][_node] -= _amount;// subtracts amount from seller's balance
self.stockBalanceOf[self.stockBuyOrders[_node][_price][iii].client][_node] += _amount;// adds the amount to buyer's balance
//write stockOwnerInfo and stockOwners for dividends
CommonLibrary.stockSaveOwnerInfo(self, _node, _amount, self.stockBuyOrders[_node][_price][iii].client, msg.sender, _price);
//transfer starcoins to seller
self.balanceOf[msg.sender] += _amount*_price;// adds the amount to buyer's balance
self.frozen[self.stockBuyOrders[_node][_price][iii].client] -= _amount*_price;// subtracts amount from seller's frozen balance
Transfer(self.stockBuyOrders[_node][_price][iii].client, msg.sender, _amount*_price);
//save the transaction
StockTradeHistory(_node, block.timestamp, self.stockBuyOrders[_node][_price][iii].client, msg.sender,
_price, _amount, self.stockBuyOrders[_node][_price][iii].orderId);
_amount = 0;
results = true;
break;
}
}
}
}
}
contract Nodes {
address public owner;
CommonLibrary.Data public vars;
mapping (address => string) public confirmationNodes;
uint confirmNodeId;
uint40 changePercentId;
uint40 pushNodeGroupId;
uint40 deleteNodeGroupId;
event NewNode(
uint256 id,
string nodeName,
uint8 producersPercent,
address producer,
uint date
);
event OwnerNotation(uint256 id, uint date, string newNotation);
event NewNodeGroup(uint16 id, string newNodeGroup);
event AddNodeAddress(uint id, uint nodeID, address nodeAdress);
event EditNode(
uint nodeID,
address nodeAdress,
address newProducer,
uint8 newProducersPercent,
bool starmidConfirmed
);
event ConfirmNode(uint id, uint nodeID);
event OutsourceConfirmNode(uint nodeID, address confirmationNode);
event ChangePercent(uint id, uint nodeId, uint producersPercent);
event PushNodeGroup(uint id, uint nodeId, uint newNodeGroup);
event DeleteNodeGroup(uint id, uint nodeId, uint deleteNodeGroup);
function Nodes() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
//-----------------------------------------------------Nodes---------------------------------------------------------------
function changeOwner(string _changeOwnerPassword, address _newOwnerAddress) onlyOwner returns(bool) {
//One-time tool for emergency owner change
if (keccak256(_changeOwnerPassword) == 0xe17a112b6fc12fc80c9b241de72da0d27ce7e244100f3c4e9358162a11bed629) {
owner = _newOwnerAddress;
return true;
}
else
return false;
}
function addOwnerNotations(string _newNotation) onlyOwner {
uint date = block.timestamp;
vars.ownerNotationId += 1;
OwnerNotation(vars.ownerNotationId, date, _newNotation);
}
function addConfirmationNode(string _newConfirmationNode) public returns(bool) {
confirmationNodes[msg.sender] = _newConfirmationNode;
return true;
}
function addNodeGroup(string _newNodeGroup) onlyOwner returns(uint16 _id) {
bool result;
(result, _id) = CommonLibrary.addNodeGroup(vars, _newNodeGroup);
require(result);
NewNodeGroup(_id, _newNodeGroup);
}
function addNode(string _newNode, uint8 _producersPercent) returns(bool) {
bool result;
uint _id;
(result, _id) = CommonLibrary.addNode(vars, _newNode, _producersPercent);
require(result);
NewNode(_id, _newNode, _producersPercent, msg.sender, block.timestamp);
return true;
}
function editNode(
uint _nodeID,
address _nodeAddress,
bool _isNewProducer,
address _newProducer,
uint8 _newProducersPercent,
bool _starmidConfirmed
) onlyOwner returns(bool) {
bool x = CommonLibrary.editNode(vars, _nodeID, _nodeAddress,_isNewProducer, _newProducer, _newProducersPercent, _starmidConfirmed);
require(x);
EditNode(_nodeID, _nodeAddress, _newProducer, _newProducersPercent, _starmidConfirmed);
return true;
}
function addNodeAddress(uint _nodeID, address _nodeAddress) public returns(bool) {
bool _result;
uint _id;
(_result, _id) = CommonLibrary.addNodeAddress(vars, _nodeID, _nodeAddress);
require(_result);
AddNodeAddress(_id, _nodeID, _nodeAddress);
return true;
}
function pushNodeGroup(uint _nodeID, uint16 _newNodeGroup) public returns(bool) {
require(msg.sender == vars.nodes[_nodeID].node);
vars.nodes[_nodeID].nodeGroup.push(_newNodeGroup);
pushNodeGroupId += 1;
PushNodeGroup(pushNodeGroupId, _nodeID, _newNodeGroup);
return true;
}
function deleteNodeGroup(uint _nodeID, uint16 _deleteNodeGroup) public returns(bool) {
require(msg.sender == vars.nodes[_nodeID].node);
for(uint16 i = 0; i < vars.nodes[_nodeID].nodeGroup.length; i++) {
if(_deleteNodeGroup == vars.nodes[_nodeID].nodeGroup[i]) {
for(uint16 ii = i; ii < vars.nodes[_nodeID].nodeGroup.length - 1; ii++)
vars.nodes[_nodeID].nodeGroup[ii] = vars.nodes[_nodeID].nodeGroup[ii + 1];
delete vars.nodes[_nodeID].nodeGroup[vars.nodes[_nodeID].nodeGroup.length - 1];
vars.nodes[_nodeID].nodeGroup.length--;
break;
}
}
deleteNodeGroupId += 1;
DeleteNodeGroup(deleteNodeGroupId, _nodeID, _deleteNodeGroup);
return true;
}
function confirmNode(uint _nodeID) onlyOwner returns(bool) {
vars.nodes[_nodeID].starmidConfirmed = true;
confirmNodeId += 1;
ConfirmNode(confirmNodeId, _nodeID);
return true;
}
function outsourceConfirmNode(uint _nodeID) public returns(bool) {
vars.nodes[_nodeID].outsourceConfirmed.push(msg.sender);
OutsourceConfirmNode(_nodeID, msg.sender);
return true;
}
function changePercent(uint _nodeId, uint8 _producersPercent) public returns(bool){
if(msg.sender == vars.nodes[_nodeId].producer && vars.nodes[_nodeId].node == 0x0000000000000000000000000000000000000000) {
vars.nodes[_nodeId].producersPercent = _producersPercent;
changePercentId += 1;
ChangePercent(changePercentId, _nodeId, _producersPercent);
return true;
}
}
function getNodeInfo(uint _nodeID) constant public returns(
address _producer,
address _node,
uint _date,
bool _starmidConfirmed,
string _nodeName,
address[] _outsourceConfirmed,
uint16[] _nodeGroup,
uint _producersPercent
) {
_producer = vars.nodes[_nodeID].producer;
_node = vars.nodes[_nodeID].node;
_date = vars.nodes[_nodeID].date;
_starmidConfirmed = vars.nodes[_nodeID].starmidConfirmed;
_nodeName = vars.nodes[_nodeID].nodeName;
_outsourceConfirmed = vars.nodes[_nodeID].outsourceConfirmed;
_nodeGroup = vars.nodes[_nodeID].nodeGroup;
_producersPercent = vars.nodes[_nodeID].producersPercent;
}
}
contract Starmid {
address public owner;
Nodes public nodesVars;
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
StarCoinLibrary.Data public sCVars;
event Transfer(address indexed from, address indexed to, uint256 value);
event BuyOrder(address indexed from, uint orderId, uint buyPrice);
event SellOrder(address indexed from, uint orderId, uint sellPrice);
event CancelBuyOrder(address indexed from, uint indexed orderId, uint price);
event CancelSellOrder(address indexed from, uint indexed orderId, uint price);
event TradeHistory(uint date, address buyer, address seller, uint price, uint amount, uint orderId);
//----------------------------------------------------Starmid exchange
event StockTransfer(address indexed from, address indexed to, uint indexed node, uint256 value);
event StockBuyOrder(uint node, uint buyPrice);
event StockSellOrder(uint node, uint sellPrice);
event StockCancelBuyOrder(uint node, uint price);
event StockCancelSellOrder(uint node, uint price);
event StockTradeHistory(uint node, uint date, address buyer, address seller, uint price, uint amount, uint orderId);
function Starmid(uint256 initialSupply, string tokenName, string tokenSymbol, uint8 decimalUnits) public {
owner = 0x378B9eea7ab9C15d9818EAdDe1156A079Cd02ba8;
totalSupply = initialSupply;
sCVars.balanceOf[msg.sender] = 5000000000;
sCVars.balanceOf[0x378B9eea7ab9C15d9818EAdDe1156A079Cd02ba8] = initialSupply - 5000000000;
name = tokenName;
symbol = tokenSymbol;
decimals = decimalUnits;
sCVars.lastMint = block.timestamp;
sCVars.emissionLimits[1] = 500000; sCVars.emissionLimits[2] = 500000; sCVars.emissionLimits[3] = 500000;
sCVars.emissionLimits[4] = 500000; sCVars.emissionLimits[5] = 500000; sCVars.emissionLimits[6] = 500000;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
//-----------------------------------------------------StarCoin Exchange------------------------------------------------------
function getWithdrawal() constant public returns(uint _amount) {
_amount = sCVars.pendingWithdrawals[msg.sender];
}
function withdraw() public returns(bool _result, uint _amount) {
_amount = sCVars.pendingWithdrawals[msg.sender];
sCVars.pendingWithdrawals[msg.sender] = 0;
msg.sender.transfer(_amount);
_result = true;
}
function changeOwner(string _changeOwnerPassword, address _newOwnerAddress) onlyOwner returns(bool) {
//One-time tool for emergency owner change
if (keccak256(_changeOwnerPassword) == 0xe17a112b6fc12fc80c9b241de72da0d27ce7e244100f3c4e9358162a11bed629) {
owner = _newOwnerAddress;
return true;
}
else
return false;
}
function setNodesVars(address _addr) public {
require(msg.sender == 0xfCbA69eF1D63b0A4CcD9ceCeA429157bA48d6a9c);
nodesVars = Nodes(_addr);
}
function getBalance(address _address) constant public returns(uint _balance) {
_balance = sCVars.balanceOf[_address];
}
function getBuyOrderPrices() constant public returns(uint[] _prices) {
_prices = sCVars.buyOrderPrices;
}
function getSellOrderPrices() constant public returns(uint[] _prices) {
_prices = sCVars.sellOrderPrices;
}
function getOrderInfo(bool _isBuyOrder, uint _price, uint _number) constant public returns(address _address, uint _amount, uint _orderId) {
if(_isBuyOrder == true) {
_address = sCVars.buyOrders[_price][_number].client;
_amount = sCVars.buyOrders[_price][_number].amount;
_orderId = sCVars.buyOrders[_price][_number].orderId;
}
else {
_address = sCVars.sellOrders[_price][_number].client;
_amount = sCVars.sellOrders[_price][_number].amount;
_orderId = sCVars.sellOrders[_price][_number].orderId;
}
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
function mint() public onlyOwner returns(uint _mintedAmount) {
//Minted amount does not exceed 8,5% per annum. Thus, minting does not greatly increase the total supply
//and does not cause significant inflation and depreciation of the starcoin.
_mintedAmount = (block.timestamp - sCVars.lastMint)*totalSupply/(12*31536000);//31536000 seconds in year
sCVars.balanceOf[msg.sender] += _mintedAmount;
totalSupply += _mintedAmount;
sCVars.lastMint = block.timestamp;
Transfer(0, this, _mintedAmount);
Transfer(this, msg.sender, _mintedAmount);
}
function buyOrder(uint256 _buyPrice) payable public returns (uint[4] _results) {
require(_buyPrice > 0 && msg.value > 0);
_results = StarCoinLibrary.buyOrder(sCVars, _buyPrice);
require(_results[3] == 1);
BuyOrder(msg.sender, _results[2], _buyPrice);
}
function sellOrder(uint256 _sellPrice, uint _amount) public returns (uint[4] _results) {
require(_sellPrice > 0 && _amount > 0);
_results = StarCoinLibrary.sellOrder(sCVars, _sellPrice, _amount);
require(_results[3] == 1);
SellOrder(msg.sender, _results[2], _sellPrice);
}
function cancelBuyOrder(uint _thisOrderID, uint _price) public {
require(StarCoinLibrary.cancelBuyOrder(sCVars, _thisOrderID, _price));
CancelBuyOrder(msg.sender, _thisOrderID, _price);
}
function cancelSellOrder(uint _thisOrderID, uint _price) public {
require(StarCoinLibrary.cancelSellOrder(sCVars, _thisOrderID, _price));
CancelSellOrder(msg.sender, _thisOrderID, _price);
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(sCVars.balanceOf[_from] >= _value && sCVars.balanceOf[_to] + _value > sCVars.balanceOf[_to]);
sCVars.balanceOf[_from] -= _value;
sCVars.balanceOf[_to] += _value;
Transfer(_from, _to, _value);
}
function buyCertainOrder(uint _price, uint _thisOrderID) payable public returns (bool _results) {
_results = StarmidLibraryExtra.buyCertainOrder(sCVars, _price, _thisOrderID);
require(_results && msg.value > 0);
BuyOrder(msg.sender, _thisOrderID, _price);
}
function sellCertainOrder(uint _amount, uint _price, uint _thisOrderID) public returns (bool _results) {
_results = StarmidLibraryExtra.sellCertainOrder(sCVars, _amount, _price, _thisOrderID);
require(_results && _amount > 0);
SellOrder(msg.sender, _thisOrderID, _price);
}
//------------------------------------------------------Starmid exchange----------------------------------------------------------
function stockTransfer(address _to, uint _node, uint _value) public {
require(_to != 0x0);
require(sCVars.stockBalanceOf[msg.sender][_node] >= _value && sCVars.stockBalanceOf[_to][_node] + _value > sCVars.stockBalanceOf[_to][_node]);
var (x,y,) = nodesVars.getNodeInfo(_node);
require(msg.sender != y);//nodeOwner cannot transfer his stocks, only sell
sCVars.stockBalanceOf[msg.sender][_node] -= _value;
sCVars.stockBalanceOf[_to][_node] += _value;
StockTransfer(msg.sender, _to, _node, _value);
}
function getEmission(uint _node) constant public returns(uint _emissionNumber, uint _emissionDate, uint _emissionAmount) {
_emissionNumber = sCVars.emissions[_node].emissionNumber;
_emissionDate = sCVars.emissions[_node].date;
_emissionAmount = sCVars.emissionLimits[_emissionNumber];
}
function emission(uint _node) public returns(bool _result, uint _emissionNumber, uint _emissionAmount, uint _producersPercent) {
var (x,y,,,,,,z,) = nodesVars.getNodeInfo(_node);
address _nodeOwner = y;
address _nodeProducer = x;
_producersPercent = z;
require(msg.sender == _nodeOwner || msg.sender == _nodeProducer);
uint allStocks;
for (uint i = 1; i <= sCVars.emissions[_node].emissionNumber; i++) {
allStocks += sCVars.emissionLimits[i];
}
if (_nodeOwner !=0x0000000000000000000000000000000000000000 && block.timestamp > sCVars.emissions[_node].date + 5184000 &&
sCVars.stockBalanceOf[_nodeOwner][_node] <= allStocks/2 ) {
_emissionNumber = sCVars.emissions[_node].emissionNumber + 1;
sCVars.stockBalanceOf[_nodeOwner][_node] += sCVars.emissionLimits[_emissionNumber]*(100 - _producersPercent)/100;
//save stockOwnerInfo for _nodeOwner
uint thisNode = 0;
for (i = 0; i < sCVars.stockOwnerInfo[_nodeOwner].nodes.length; i++) {
if (sCVars.stockOwnerInfo[_nodeOwner].nodes[i] == _node) thisNode = 1;
}
if (thisNode == 0) sCVars.stockOwnerInfo[_nodeOwner].nodes.push(_node);
sCVars.stockBalanceOf[_nodeProducer][_node] += sCVars.emissionLimits[_emissionNumber]*_producersPercent/100;
//save stockOwnerInfo for _nodeProducer
thisNode = 0;
for (i = 0; i < sCVars.stockOwnerInfo[_nodeProducer].nodes.length; i++) {
if (sCVars.stockOwnerInfo[_nodeProducer].nodes[i] == _node) thisNode = 1;
}
if (thisNode == 0) sCVars.stockOwnerInfo[_nodeProducer].nodes.push(_node);
sCVars.emissions[_node].date = block.timestamp;
sCVars.emissions[_node].emissionNumber = _emissionNumber;
_emissionAmount = sCVars.emissionLimits[_emissionNumber];
_result = true;
}
else _result = false;
}
function getStockOwnerInfo(address _address) constant public returns(uint[] _nodes) {
_nodes = sCVars.stockOwnerInfo[_address].nodes;
}
function getStockBalance(address _address, uint _node) constant public returns(uint _balance) {
_balance = sCVars.stockBalanceOf[_address][_node];
}
function getWithFrozenStockBalance(address _address, uint _node) constant public returns(uint _balance) {
_balance = sCVars.stockBalanceOf[_address][_node] + sCVars.stockFrozen[_address][_node];
}
function getStockOrderInfo(bool _isBuyOrder, uint _node, uint _price, uint _number) constant public returns(address _address, uint _amount, uint _orderId) {
if(_isBuyOrder == true) {
_address = sCVars.stockBuyOrders[_node][_price][_number].client;
_amount = sCVars.stockBuyOrders[_node][_price][_number].amount;
_orderId = sCVars.stockBuyOrders[_node][_price][_number].orderId;
}
else {
_address = sCVars.stockSellOrders[_node][_price][_number].client;
_amount = sCVars.stockSellOrders[_node][_price][_number].amount;
_orderId = sCVars.stockSellOrders[_node][_price][_number].orderId;
}
}
function getStockBuyOrderPrices(uint _node) constant public returns(uint[] _prices) {
_prices = sCVars.stockBuyOrderPrices[_node];
}
function getStockSellOrderPrices(uint _node) constant public returns(uint[] _prices) {
_prices = sCVars.stockSellOrderPrices[_node];
}
function stockBuyOrder(uint _node, uint256 _buyPrice, uint _amount) public returns (uint[4] _results) {
require(_node > 0 && _buyPrice > 0 && _amount > 0);
_results = StarmidLibrary.stockBuyOrder(sCVars, _node, _buyPrice, _amount);
require(_results[3] == 1);
StockBuyOrder(_node, _buyPrice);
}
function stockSellOrder(uint _node, uint256 _sellPrice, uint _amount) public returns (uint[4] _results) {
require(_node > 0 && _sellPrice > 0 && _amount > 0);
_results = StarmidLibrary.stockSellOrder(sCVars, _node, _sellPrice, _amount);
require(_results[3] == 1);
StockSellOrder(_node, _sellPrice);
}
function stockCancelBuyOrder(uint _node, uint _thisOrderID, uint _price) public {
require(StarmidLibrary.stockCancelBuyOrder(sCVars, _node, _thisOrderID, _price));
StockCancelBuyOrder(_node, _price);
}
function stockCancelSellOrder(uint _node, uint _thisOrderID, uint _price) public {
require(StarmidLibrary.stockCancelSellOrder(sCVars, _node, _thisOrderID, _price));
StockCancelSellOrder(_node, _price);
}
function getLastDividends(uint _node) public constant returns (uint _lastDividents, uint _dividends) {
uint stockAmount = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumAmount;
uint sumAmount = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumAmount;
if(sumAmount > 0) {
uint stockAverageBuyPrice = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumPriceAmount/sumAmount;
uint dividendsBase = stockAmount*stockAverageBuyPrice;
_lastDividents = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumDateAmount/sumAmount;
if(_lastDividents > 0)_dividends = (block.timestamp - _lastDividents)*dividendsBase/(10*31536000);
else _dividends = 0;
}
}
//--------------------------------Dividends (10% to stock owner, 2,5% to node owner per annum)------------------------------------
function dividends(uint _node) public returns (bool _result, uint _dividends) {
var (x,y,) = nodesVars.getNodeInfo(_node);
uint _stockAmount = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumAmount;
uint _sumAmount = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumAmount;
if(_sumAmount > 0) {
uint _stockAverageBuyPrice = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumPriceAmount/_sumAmount;
uint _dividendsBase = _stockAmount*_stockAverageBuyPrice;
uint _averageDate = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumDateAmount/_sumAmount;
//Stock owner`s dividends
uint _div = (block.timestamp - _averageDate)*_dividendsBase/(10*31536000);//31536000 seconds in year
sCVars.balanceOf[msg.sender] += _div;
//Node owner`s dividends
uint _nodeDividends = (block.timestamp - _averageDate)*_dividendsBase/(40*31536000);//31536000 seconds in year
sCVars.balanceOf[y] += _nodeDividends;
sCVars.StockOwnersBuyPrice[msg.sender][_node].sumDateAmount = block.timestamp*_stockAmount;//set new average dividends date
totalSupply += _div + _div/4;
_dividends = _div + _div/4;
Transfer(this, msg.sender, _div);
Transfer(this, y, _div/4);
_result = true;
}
}
function stockBuyCertainOrder(uint _node, uint _price, uint _amount, uint _thisOrderID) payable public returns (bool _results) {
_results = StarmidLibraryExtra.stockBuyCertainOrder(sCVars, _node, _price, _amount, _thisOrderID);
require(_results && _node > 0 && _amount > 0);
StockBuyOrder(_node, _price);
}
function stockSellCertainOrder(uint _node, uint _price, uint _amount, uint _thisOrderID) public returns (bool _results) {
_results = StarmidLibraryExtra.stockSellCertainOrder(sCVars, _node, _price, _amount, _thisOrderID);
require(_results && _node > 0 && _amount > 0);
StockSellOrder(_node, _price);
}
} | subtracts amount from seller's frozen stock balance
| self.stockFrozen[self.stockSellOrders[_node][minPrice][0].client][_node] -= self.stockSellOrders[_node][minPrice][0].amount; | 2,114,658 | [
1,
1717,
1575,
87,
3844,
628,
29804,
10,
5520,
31,
87,
12810,
12480,
11013,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
25083,
202,
2890,
18,
15381,
42,
9808,
63,
2890,
18,
15381,
55,
1165,
16528,
63,
67,
2159,
6362,
1154,
5147,
6362,
20,
8009,
2625,
6362,
67,
2159,
65,
3947,
365,
18,
15381,
55,
1165,
16528,
63,
67,
2159,
6362,
1154,
5147,
6362,
20,
8009,
8949,
31,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0xc193016c1e1D45b982D1Dd2f0C7B95F3397041c7/sources/contracts/NoFiGov.sol | @custom:security-contact [email protected] constructor() initializer {} | contract NoFiGov is Initializable, GovernorUpgradeable, GovernorCompatibilityBravoUpgradeable, GovernorVotesUpgradeable, GovernorVotesQuorumFractionUpgradeable, GovernorTimelockControlUpgradeable {
uint _votingDelay;
uint _votingPeriod;
function initialize(
string memory name,
ERC20VotesUpgradeable _token,
TimelockControllerUpgradeable _timelock,
uint __votingDelay,
uint __votingPeriod
)
initializer public
pragma solidity ^0.8.2;
{
_votingDelay = __votingDelay;
_votingPeriod = __votingPeriod;
__Governor_init(name);
__GovernorCompatibilityBravo_init();
__GovernorVotes_init(_token);
__GovernorVotesQuorumFraction_init(4);
__GovernorTimelockControl_init(_timelock);
}
function votingDelay()
public
view
override(IGovernorUpgradeable)
returns (uint256)
{
return _votingDelay;
}
function votingPeriod() public view override returns (uint256) {
}
function proposalThreshold() public pure override returns (uint256) {
return 0;
}
function quorum(uint256 blockNumber)
public
view
override(IGovernorUpgradeable, GovernorVotesQuorumFractionUpgradeable)
returns (uint256)
{
return super.quorum(blockNumber);
}
function getVotes(address account, uint256 blockNumber)
public
view
override(IGovernorUpgradeable, GovernorVotesUpgradeable)
returns (uint256)
{
return super.getVotes(account, blockNumber);
}
function state(uint256 proposalId)
public
view
override(GovernorUpgradeable, IGovernorUpgradeable, GovernorTimelockControlUpgradeable)
returns (ProposalState)
{
return super.state(proposalId);
}
function propose(address[] memory targets, uint256[] memory values, bytes[] memory calldatas, string memory description)
public
override(GovernorUpgradeable, GovernorCompatibilityBravoUpgradeable, IGovernorUpgradeable)
returns (uint256)
{
return super.propose(targets, values, calldatas, description);
}
function _execute(uint256 proposalId, address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash)
internal
override(GovernorUpgradeable, GovernorTimelockControlUpgradeable)
{
super._execute(proposalId, targets, values, calldatas, descriptionHash);
}
function _cancel(address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash)
internal
override(GovernorUpgradeable, GovernorTimelockControlUpgradeable)
returns (uint256)
{
return super._cancel(targets, values, calldatas, descriptionHash);
}
function _executor()
internal
view
override(GovernorUpgradeable, GovernorTimelockControlUpgradeable)
returns (address)
{
return super._executor();
}
function supportsInterface(bytes4 interfaceId)
public
view
override(GovernorUpgradeable, IERC165Upgradeable, GovernorTimelockControlUpgradeable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
| 5,626,021 | [
1,
36,
3662,
30,
7462,
17,
8994,
417,
2015,
601,
4365,
318,
36,
685,
1917,
4408,
18,
832,
3885,
1435,
12562,
2618,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16351,
2631,
42,
77,
43,
1527,
353,
10188,
6934,
16,
611,
1643,
29561,
10784,
429,
16,
611,
1643,
29561,
21633,
38,
354,
12307,
10784,
429,
16,
611,
1643,
29561,
29637,
10784,
429,
16,
611,
1643,
29561,
29637,
31488,
13724,
10784,
429,
16,
611,
1643,
29561,
10178,
292,
975,
3367,
10784,
429,
288,
203,
565,
2254,
389,
90,
17128,
6763,
31,
203,
565,
2254,
389,
90,
17128,
5027,
31,
203,
203,
565,
445,
4046,
12,
203,
3639,
533,
3778,
508,
16,
203,
3639,
4232,
39,
3462,
29637,
10784,
429,
389,
2316,
16,
203,
3639,
12652,
292,
975,
2933,
10784,
429,
389,
8584,
292,
975,
16,
203,
3639,
2254,
1001,
90,
17128,
6763,
16,
203,
3639,
2254,
1001,
90,
17128,
5027,
203,
565,
262,
203,
3639,
12562,
1071,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
22,
31,
203,
203,
565,
288,
203,
3639,
389,
90,
17128,
6763,
273,
1001,
90,
17128,
6763,
31,
203,
3639,
389,
90,
17128,
5027,
273,
1001,
90,
17128,
5027,
31,
203,
3639,
1001,
43,
1643,
29561,
67,
2738,
12,
529,
1769,
203,
3639,
1001,
43,
1643,
29561,
21633,
38,
354,
12307,
67,
2738,
5621,
203,
3639,
1001,
43,
1643,
29561,
29637,
67,
2738,
24899,
2316,
1769,
203,
3639,
1001,
43,
1643,
29561,
29637,
31488,
13724,
67,
2738,
12,
24,
1769,
203,
3639,
1001,
43,
1643,
29561,
10178,
292,
975,
3367,
67,
2738,
24899,
8584,
292,
975,
1769,
203,
565,
289,
203,
203,
565,
445,
331,
17128,
6763,
1435,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
3849,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.8;
import "./ERC1155Inventory.sol";
import "./IERC1155InventoryBurnable.sol";
/**
* @title ERC1155InventoryBurnable, a burnable ERC1155Inventory
*/
abstract contract ERC1155InventoryBurnable is IERC1155InventoryBurnable, ERC1155Inventory {
//================================== ERC1155InventoryBurnable =======================================/
/**
* Burns some token.
* @dev See {IERC1155InventoryBurnable-burnFrom(address,uint256,uint256)}.
*/
function burnFrom(
address from,
uint256 id,
uint256 value
) public virtual override {
address sender = _msgSender();
require(_isOperatable(from, sender), "Inventory: non-approved sender");
if (id.isFungibleToken()) {
_burnFungible(from, id, value);
} else if (id.isNonFungibleToken()) {
_burnNFT(from, id, value, false);
} else {
revert("Inventory: not a token id");
}
emit TransferSingle(sender, from, address(0), id, value);
}
/**
* Burns a batch of tokens.
* @dev See {IERC1155InventoryBurnable-batchBurnFrom(address,uint256[],uint256[])}.
*/
function batchBurnFrom(
address from,
uint256[] memory ids,
uint256[] memory values
) public virtual override {
uint256 length = ids.length;
require(length == values.length, "Inventory: inconsistent arrays");
address sender = _msgSender();
require(_isOperatable(from, sender), "Inventory: non-approved sender");
uint256 nfCollectionId;
uint256 nfCollectionCount;
for (uint256 i; i != length; ++i) {
uint256 id = ids[i];
uint256 value = values[i];
if (id.isFungibleToken()) {
_burnFungible(from, id, value);
} else if (id.isNonFungibleToken()) {
_burnNFT(from, id, value, true);
uint256 nextCollectionId = id.getNonFungibleCollection();
if (nfCollectionId == 0) {
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
} else {
if (nextCollectionId != nfCollectionId) {
_balances[nfCollectionId][from] -= nfCollectionCount;
_supplies[nfCollectionId] -= nfCollectionCount;
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
} else {
++nfCollectionCount;
}
}
} else {
revert("Inventory: not a token id");
}
}
if (nfCollectionId != 0) {
_balances[nfCollectionId][from] -= nfCollectionCount;
_supplies[nfCollectionId] -= nfCollectionCount;
}
emit TransferBatch(sender, from, address(0), ids, values);
}
//================================== Internal Helper Functions =======================================/
function _burnFungible(
address from,
uint256 id,
uint256 value
) internal {
require(value != 0, "Inventory: zero value");
uint256 balance = _balances[id][from];
require(balance >= value, "Inventory: not enough balance");
_balances[id][from] = balance - value;
// Cannot underflow
_supplies[id] -= value;
}
function _burnNFT(
address from,
uint256 id,
uint256 value,
bool isBatch
) internal {
require(value == 1, "Inventory: wrong NFT value");
require(from == address(_owners[id]), "Inventory: non-owned NFT");
_owners[id] = _BURNT_NFT_OWNER;
if (!isBatch) {
uint256 collectionId = id.getNonFungibleCollection();
// cannot underflow as balance is confirmed through ownership
--_balances[collectionId][from];
// Cannot underflow
--_supplies[collectionId];
}
}
}
| * @title ERC1155InventoryBurnable, a burnable ERC1155Inventory/================================== ERC1155InventoryBurnable =======================================/ | abstract contract ERC1155InventoryBurnable is IERC1155InventoryBurnable, ERC1155Inventory {
function burnFrom(
address from,
uint256 id,
uint256 value
) public virtual override {
address sender = _msgSender();
require(_isOperatable(from, sender), "Inventory: non-approved sender");
if (id.isFungibleToken()) {
_burnFungible(from, id, value);
_burnNFT(from, id, value, false);
revert("Inventory: not a token id");
}
emit TransferSingle(sender, from, address(0), id, value);
}
) public virtual override {
address sender = _msgSender();
require(_isOperatable(from, sender), "Inventory: non-approved sender");
if (id.isFungibleToken()) {
_burnFungible(from, id, value);
_burnNFT(from, id, value, false);
revert("Inventory: not a token id");
}
emit TransferSingle(sender, from, address(0), id, value);
}
} else if (id.isNonFungibleToken()) {
} else {
function batchBurnFrom(
address from,
uint256[] memory ids,
uint256[] memory values
) public virtual override {
uint256 length = ids.length;
require(length == values.length, "Inventory: inconsistent arrays");
address sender = _msgSender();
require(_isOperatable(from, sender), "Inventory: non-approved sender");
uint256 nfCollectionId;
uint256 nfCollectionCount;
for (uint256 i; i != length; ++i) {
uint256 id = ids[i];
uint256 value = values[i];
if (id.isFungibleToken()) {
_burnFungible(from, id, value);
_burnNFT(from, id, value, true);
uint256 nextCollectionId = id.getNonFungibleCollection();
if (nfCollectionId == 0) {
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
if (nextCollectionId != nfCollectionId) {
_balances[nfCollectionId][from] -= nfCollectionCount;
_supplies[nfCollectionId] -= nfCollectionCount;
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
++nfCollectionCount;
}
}
revert("Inventory: not a token id");
}
}
if (nfCollectionId != 0) {
_balances[nfCollectionId][from] -= nfCollectionCount;
_supplies[nfCollectionId] -= nfCollectionCount;
}
emit TransferBatch(sender, from, address(0), ids, values);
}
function batchBurnFrom(
address from,
uint256[] memory ids,
uint256[] memory values
) public virtual override {
uint256 length = ids.length;
require(length == values.length, "Inventory: inconsistent arrays");
address sender = _msgSender();
require(_isOperatable(from, sender), "Inventory: non-approved sender");
uint256 nfCollectionId;
uint256 nfCollectionCount;
for (uint256 i; i != length; ++i) {
uint256 id = ids[i];
uint256 value = values[i];
if (id.isFungibleToken()) {
_burnFungible(from, id, value);
_burnNFT(from, id, value, true);
uint256 nextCollectionId = id.getNonFungibleCollection();
if (nfCollectionId == 0) {
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
if (nextCollectionId != nfCollectionId) {
_balances[nfCollectionId][from] -= nfCollectionCount;
_supplies[nfCollectionId] -= nfCollectionCount;
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
++nfCollectionCount;
}
}
revert("Inventory: not a token id");
}
}
if (nfCollectionId != 0) {
_balances[nfCollectionId][from] -= nfCollectionCount;
_supplies[nfCollectionId] -= nfCollectionCount;
}
emit TransferBatch(sender, from, address(0), ids, values);
}
function batchBurnFrom(
address from,
uint256[] memory ids,
uint256[] memory values
) public virtual override {
uint256 length = ids.length;
require(length == values.length, "Inventory: inconsistent arrays");
address sender = _msgSender();
require(_isOperatable(from, sender), "Inventory: non-approved sender");
uint256 nfCollectionId;
uint256 nfCollectionCount;
for (uint256 i; i != length; ++i) {
uint256 id = ids[i];
uint256 value = values[i];
if (id.isFungibleToken()) {
_burnFungible(from, id, value);
_burnNFT(from, id, value, true);
uint256 nextCollectionId = id.getNonFungibleCollection();
if (nfCollectionId == 0) {
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
if (nextCollectionId != nfCollectionId) {
_balances[nfCollectionId][from] -= nfCollectionCount;
_supplies[nfCollectionId] -= nfCollectionCount;
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
++nfCollectionCount;
}
}
revert("Inventory: not a token id");
}
}
if (nfCollectionId != 0) {
_balances[nfCollectionId][from] -= nfCollectionCount;
_supplies[nfCollectionId] -= nfCollectionCount;
}
emit TransferBatch(sender, from, address(0), ids, values);
}
} else if (id.isNonFungibleToken()) {
function batchBurnFrom(
address from,
uint256[] memory ids,
uint256[] memory values
) public virtual override {
uint256 length = ids.length;
require(length == values.length, "Inventory: inconsistent arrays");
address sender = _msgSender();
require(_isOperatable(from, sender), "Inventory: non-approved sender");
uint256 nfCollectionId;
uint256 nfCollectionCount;
for (uint256 i; i != length; ++i) {
uint256 id = ids[i];
uint256 value = values[i];
if (id.isFungibleToken()) {
_burnFungible(from, id, value);
_burnNFT(from, id, value, true);
uint256 nextCollectionId = id.getNonFungibleCollection();
if (nfCollectionId == 0) {
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
if (nextCollectionId != nfCollectionId) {
_balances[nfCollectionId][from] -= nfCollectionCount;
_supplies[nfCollectionId] -= nfCollectionCount;
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
++nfCollectionCount;
}
}
revert("Inventory: not a token id");
}
}
if (nfCollectionId != 0) {
_balances[nfCollectionId][from] -= nfCollectionCount;
_supplies[nfCollectionId] -= nfCollectionCount;
}
emit TransferBatch(sender, from, address(0), ids, values);
}
} else {
function batchBurnFrom(
address from,
uint256[] memory ids,
uint256[] memory values
) public virtual override {
uint256 length = ids.length;
require(length == values.length, "Inventory: inconsistent arrays");
address sender = _msgSender();
require(_isOperatable(from, sender), "Inventory: non-approved sender");
uint256 nfCollectionId;
uint256 nfCollectionCount;
for (uint256 i; i != length; ++i) {
uint256 id = ids[i];
uint256 value = values[i];
if (id.isFungibleToken()) {
_burnFungible(from, id, value);
_burnNFT(from, id, value, true);
uint256 nextCollectionId = id.getNonFungibleCollection();
if (nfCollectionId == 0) {
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
if (nextCollectionId != nfCollectionId) {
_balances[nfCollectionId][from] -= nfCollectionCount;
_supplies[nfCollectionId] -= nfCollectionCount;
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
++nfCollectionCount;
}
}
revert("Inventory: not a token id");
}
}
if (nfCollectionId != 0) {
_balances[nfCollectionId][from] -= nfCollectionCount;
_supplies[nfCollectionId] -= nfCollectionCount;
}
emit TransferBatch(sender, from, address(0), ids, values);
}
} else {
} else {
function batchBurnFrom(
address from,
uint256[] memory ids,
uint256[] memory values
) public virtual override {
uint256 length = ids.length;
require(length == values.length, "Inventory: inconsistent arrays");
address sender = _msgSender();
require(_isOperatable(from, sender), "Inventory: non-approved sender");
uint256 nfCollectionId;
uint256 nfCollectionCount;
for (uint256 i; i != length; ++i) {
uint256 id = ids[i];
uint256 value = values[i];
if (id.isFungibleToken()) {
_burnFungible(from, id, value);
_burnNFT(from, id, value, true);
uint256 nextCollectionId = id.getNonFungibleCollection();
if (nfCollectionId == 0) {
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
if (nextCollectionId != nfCollectionId) {
_balances[nfCollectionId][from] -= nfCollectionCount;
_supplies[nfCollectionId] -= nfCollectionCount;
nfCollectionId = nextCollectionId;
nfCollectionCount = 1;
++nfCollectionCount;
}
}
revert("Inventory: not a token id");
}
}
if (nfCollectionId != 0) {
_balances[nfCollectionId][from] -= nfCollectionCount;
_supplies[nfCollectionId] -= nfCollectionCount;
}
emit TransferBatch(sender, from, address(0), ids, values);
}
function _burnFungible(
address from,
uint256 id,
uint256 value
) internal {
require(value != 0, "Inventory: zero value");
uint256 balance = _balances[id][from];
require(balance >= value, "Inventory: not enough balance");
_balances[id][from] = balance - value;
_supplies[id] -= value;
}
function _burnNFT(
address from,
uint256 id,
uint256 value,
bool isBatch
) internal {
require(value == 1, "Inventory: wrong NFT value");
require(from == address(_owners[id]), "Inventory: non-owned NFT");
_owners[id] = _BURNT_NFT_OWNER;
if (!isBatch) {
uint256 collectionId = id.getNonFungibleCollection();
--_balances[collectionId][from];
--_supplies[collectionId];
}
}
function _burnNFT(
address from,
uint256 id,
uint256 value,
bool isBatch
) internal {
require(value == 1, "Inventory: wrong NFT value");
require(from == address(_owners[id]), "Inventory: non-owned NFT");
_owners[id] = _BURNT_NFT_OWNER;
if (!isBatch) {
uint256 collectionId = id.getNonFungibleCollection();
--_balances[collectionId][from];
--_supplies[collectionId];
}
}
}
| 985,947 | [
1,
654,
39,
2499,
2539,
15059,
38,
321,
429,
16,
279,
18305,
429,
4232,
39,
2499,
2539,
15059,
19,
4428,
631,
4232,
39,
2499,
2539,
15059,
38,
321,
429,
422,
4428,
894,
33,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
17801,
6835,
4232,
39,
2499,
2539,
15059,
38,
321,
429,
353,
467,
654,
39,
2499,
2539,
15059,
38,
321,
429,
16,
4232,
39,
2499,
2539,
15059,
288,
203,
203,
565,
445,
18305,
1265,
12,
203,
3639,
1758,
628,
16,
203,
3639,
2254,
5034,
612,
16,
203,
3639,
2254,
5034,
460,
203,
203,
565,
262,
1071,
5024,
3849,
288,
203,
3639,
1758,
5793,
273,
389,
3576,
12021,
5621,
203,
3639,
2583,
24899,
291,
3542,
8163,
12,
2080,
16,
5793,
3631,
315,
15059,
30,
1661,
17,
25990,
5793,
8863,
203,
203,
3639,
309,
261,
350,
18,
291,
42,
20651,
1523,
1345,
10756,
288,
203,
5411,
389,
70,
321,
42,
20651,
1523,
12,
2080,
16,
612,
16,
460,
1769,
203,
5411,
389,
70,
321,
50,
4464,
12,
2080,
16,
612,
16,
460,
16,
629,
1769,
203,
5411,
15226,
2932,
15059,
30,
486,
279,
1147,
612,
8863,
203,
3639,
289,
203,
203,
3639,
3626,
12279,
5281,
12,
15330,
16,
628,
16,
1758,
12,
20,
3631,
612,
16,
460,
1769,
203,
565,
289,
203,
203,
565,
262,
1071,
5024,
3849,
288,
203,
3639,
1758,
5793,
273,
389,
3576,
12021,
5621,
203,
3639,
2583,
24899,
291,
3542,
8163,
12,
2080,
16,
5793,
3631,
315,
15059,
30,
1661,
17,
25990,
5793,
8863,
203,
203,
3639,
309,
261,
350,
18,
291,
42,
20651,
1523,
1345,
10756,
288,
203,
5411,
389,
70,
321,
42,
20651,
1523,
12,
2080,
16,
612,
16,
460,
1769,
203,
5411,
389,
70,
321,
50,
4464,
12,
2080,
16,
612,
16,
460,
16,
629,
1769,
203,
5411,
15226,
2932,
2
] |
// File: openzeppelin-solidity/contracts/GSN/Context.sol
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = _msgSender();
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @daostack/infra/contracts/Reputation.sol
pragma solidity 0.5.13;
/**
* @title Reputation system
* @dev A DAO has Reputation System which allows peers to rate other peers in order to build trust .
* A reputation is use to assign influence measure to a DAO'S peers.
* Reputation is similar to regular tokens but with one crucial difference: It is non-transferable.
* The Reputation contract maintain a map of address to reputation value.
* It provides an onlyOwner functions to mint and burn reputation _to (or _from) a specific address.
*/
contract Reputation is Ownable {
uint8 public decimals = 18; //Number of decimals of the smallest unit
// Event indicating minting of reputation to an address.
event Mint(address indexed _to, uint256 _amount);
// Event indicating burning of reputation for an address.
event Burn(address indexed _from, uint256 _amount);
/// @dev `Checkpoint` is the structure that attaches a block number to a
/// given value, the block number attached is the one that last changed the
/// value
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint128 fromBlock;
// `value` is the amount of reputation at a specific block number
uint128 value;
}
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping (address => Checkpoint[]) private balances;
// Tracks the history of the `totalSupply` of the reputation
Checkpoint[] private totalSupplyHistory;
/// @notice Generates `_amount` reputation that are assigned to `_owner`
/// @param _user The address that will be assigned the new reputation
/// @param _amount The quantity of reputation generated
/// @return True if the reputation are generated correctly
function mint(address _user, uint256 _amount) public onlyOwner returns (bool) {
uint256 curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint256 previousBalanceTo = balanceOf(_user);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_user], previousBalanceTo + _amount);
emit Mint(_user, _amount);
return true;
}
/// @notice Burns `_amount` reputation from `_owner`
/// @param _user The address that will lose the reputation
/// @param _amount The quantity of reputation to burn
/// @return True if the reputation are burned correctly
function burn(address _user, uint256 _amount) public onlyOwner returns (bool) {
uint256 curTotalSupply = totalSupply();
uint256 amountBurned = _amount;
uint256 previousBalanceFrom = balanceOf(_user);
if (previousBalanceFrom < amountBurned) {
amountBurned = previousBalanceFrom;
}
updateValueAtNow(totalSupplyHistory, curTotalSupply - amountBurned);
updateValueAtNow(balances[_user], previousBalanceFrom - amountBurned);
emit Burn(_user, amountBurned);
return true;
}
/// @dev This function makes it easy to get the total number of reputation
/// @return The total number of reputation
function totalSupply() public view returns (uint256) {
return totalSupplyAt(block.number);
}
////////////////
// Query balance and totalSupply in History
////////////////
/**
* @dev return the reputation amount of a given owner
* @param _owner an address of the owner which we want to get his reputation
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
/// @notice Total amount of reputation at a specific `_blockNumber`.
/// @param _blockNumber The block number when the totalSupply is queried
/// @return The total amount of reputation at `_blockNumber`
function totalSupplyAt(uint256 _blockNumber) public view returns(uint256) {
if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) {
return 0;
// This will return the expected totalSupply during normal situations
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
/// @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, uint256 _blockNumber)
public view returns (uint256)
{
if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) {
return 0;
// This will return the expected balance during normal situations
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
////////////////
// Internal helper functions to query and set a value in a snapshot array
////////////////
/// @dev `getValueAt` retrieves the number of reputation 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 reputation being queried
function getValueAt(Checkpoint[] storage checkpoints, uint256 _block) internal view returns (uint256) {
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
uint256 min = 0;
uint256 max = checkpoints.length-1;
while (max > min) {
uint256 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 reputation
function updateValueAtNow(Checkpoint[] storage checkpoints, uint256 _value) internal {
require(uint128(_value) == _value); //check value is in the 128 bits bounderies
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol
pragma solidity ^0.5.0;
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public {
_burn(_msgSender(), amount);
}
/**
* @dev See {ERC20-_burnFrom}.
*/
function burnFrom(address account, uint256 amount) public {
_burnFrom(account, amount);
}
}
// File: @daostack/arc/contracts/controller/DAOToken.sol
pragma solidity 0.5.13;
/**
* @title DAOToken, base on zeppelin contract.
* @dev ERC20 compatible token. It is a mintable, burnable token.
*/
contract DAOToken is ERC20, ERC20Burnable, Ownable {
string public name;
string public symbol;
// solhint-disable-next-line const-name-snakecase
uint8 public constant decimals = 18;
uint256 public cap;
/**
* @dev Constructor
* @param _name - token name
* @param _symbol - token symbol
* @param _cap - token cap - 0 value means no cap
*/
constructor(string memory _name, string memory _symbol, uint256 _cap)
public {
name = _name;
symbol = _symbol;
cap = _cap;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
*/
function mint(address _to, uint256 _amount) public onlyOwner returns (bool) {
if (cap > 0)
require(totalSupply().add(_amount) <= cap);
_mint(_to, _amount);
return true;
}
}
// File: openzeppelin-solidity/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* IMPORTANT: It is unsafe to assume that an address for which this
* function returns false is an externally-owned account (EOA) and not a
* contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @daostack/arc/contracts/libs/SafeERC20.sol
/*
SafeERC20 by daostack.
The code is based on a fix by SECBIT Team.
USE WITH CAUTION & NO WARRANTY
REFERENCE & RELATED READING
- https://github.com/ethereum/solidity/issues/4116
- https://medium.com/@chris_77367/explaining-unexpected-reverts-starting-with-solidity-0-4-22-3ada6e82308c
- https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
- https://gist.github.com/BrendanChou/88a2eeb80947ff00bcf58ffdafeaeb61
*/
pragma solidity 0.5.13;
library SafeERC20 {
using Address for address;
bytes4 constant private TRANSFER_SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)")));
bytes4 constant private TRANSFERFROM_SELECTOR = bytes4(keccak256(bytes("transferFrom(address,address,uint256)")));
bytes4 constant private APPROVE_SELECTOR = bytes4(keccak256(bytes("approve(address,uint256)")));
function safeTransfer(address _erc20Addr, address _to, uint256 _value) internal {
// Must be a contract addr first!
require(_erc20Addr.isContract());
(bool success, bytes memory returnValue) =
// solhint-disable-next-line avoid-low-level-calls
_erc20Addr.call(abi.encodeWithSelector(TRANSFER_SELECTOR, _to, _value));
// call return false when something wrong
require(success);
//check return value
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
function safeTransferFrom(address _erc20Addr, address _from, address _to, uint256 _value) internal {
// Must be a contract addr first!
require(_erc20Addr.isContract());
(bool success, bytes memory returnValue) =
// solhint-disable-next-line avoid-low-level-calls
_erc20Addr.call(abi.encodeWithSelector(TRANSFERFROM_SELECTOR, _from, _to, _value));
// call return false when something wrong
require(success);
//check return value
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
function safeApprove(address _erc20Addr, address _spender, uint256 _value) internal {
// Must be a contract addr first!
require(_erc20Addr.isContract());
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero.
require((_value == 0) || (IERC20(_erc20Addr).allowance(address(this), _spender) == 0));
(bool success, bytes memory returnValue) =
// solhint-disable-next-line avoid-low-level-calls
_erc20Addr.call(abi.encodeWithSelector(APPROVE_SELECTOR, _spender, _value));
// call return false when something wrong
require(success);
//check return value
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
}
// File: @daostack/arc/contracts/controller/Avatar.sol
pragma solidity 0.5.13;
/**
* @title An Avatar holds tokens, reputation and ether for a controller
*/
contract Avatar is Ownable {
using SafeERC20 for address;
string public orgName;
DAOToken public nativeToken;
Reputation public nativeReputation;
event GenericCall(address indexed _contract, bytes _data, uint _value, bool _success);
event SendEther(uint256 _amountInWei, address indexed _to);
event ExternalTokenTransfer(address indexed _externalToken, address indexed _to, uint256 _value);
event ExternalTokenTransferFrom(address indexed _externalToken, address _from, address _to, uint256 _value);
event ExternalTokenApproval(address indexed _externalToken, address _spender, uint256 _value);
event ReceiveEther(address indexed _sender, uint256 _value);
event MetaData(string _metaData);
/**
* @dev the constructor takes organization name, native token and reputation system
and creates an avatar for a controller
*/
constructor(string memory _orgName, DAOToken _nativeToken, Reputation _nativeReputation) public {
orgName = _orgName;
nativeToken = _nativeToken;
nativeReputation = _nativeReputation;
}
/**
* @dev enables an avatar to receive ethers
*/
function() external payable {
emit ReceiveEther(msg.sender, msg.value);
}
/**
* @dev perform a generic call to an arbitrary contract
* @param _contract the contract's address to call
* @param _data ABI-encoded contract call to call `_contract` address.
* @param _value value (ETH) to transfer with the transaction
* @return bool success or fail
* bytes - the return bytes of the called contract's function.
*/
function genericCall(address _contract, bytes memory _data, uint256 _value)
public
onlyOwner
returns(bool success, bytes memory returnValue) {
// solhint-disable-next-line avoid-call-value
(success, returnValue) = _contract.call.value(_value)(_data);
emit GenericCall(_contract, _data, _value, success);
}
/**
* @dev send ethers from the avatar's wallet
* @param _amountInWei amount to send in Wei units
* @param _to send the ethers to this address
* @return bool which represents success
*/
function sendEther(uint256 _amountInWei, address payable _to) public onlyOwner returns(bool) {
_to.transfer(_amountInWei);
emit SendEther(_amountInWei, _to);
return true;
}
/**
* @dev external token transfer
* @param _externalToken the token contract
* @param _to the destination address
* @param _value the amount of tokens to transfer
* @return bool which represents success
*/
function externalTokenTransfer(IERC20 _externalToken, address _to, uint256 _value)
public onlyOwner returns(bool)
{
address(_externalToken).safeTransfer(_to, _value);
emit ExternalTokenTransfer(address(_externalToken), _to, _value);
return true;
}
/**
* @dev external token transfer from a specific account
* @param _externalToken the token contract
* @param _from the account to spend token from
* @param _to the destination address
* @param _value the amount of tokens to transfer
* @return bool which represents success
*/
function externalTokenTransferFrom(
IERC20 _externalToken,
address _from,
address _to,
uint256 _value
)
public onlyOwner returns(bool)
{
address(_externalToken).safeTransferFrom(_from, _to, _value);
emit ExternalTokenTransferFrom(address(_externalToken), _from, _to, _value);
return true;
}
/**
* @dev externalTokenApproval approve the spender address to spend a specified amount of tokens
* on behalf of msg.sender.
* @param _externalToken the address of the Token Contract
* @param _spender address
* @param _value the amount of ether (in Wei) which the approval is referring to.
* @return bool which represents a success
*/
function externalTokenApproval(IERC20 _externalToken, address _spender, uint256 _value)
public onlyOwner returns(bool)
{
address(_externalToken).safeApprove(_spender, _value);
emit ExternalTokenApproval(address(_externalToken), _spender, _value);
return true;
}
/**
* @dev metaData emits an event with a string, should contain the hash of some meta data.
* @param _metaData a string representing a hash of the meta data
* @return bool which represents a success
*/
function metaData(string memory _metaData) public onlyOwner returns(bool) {
emit MetaData(_metaData);
return true;
}
}
// File: @daostack/arc/contracts/globalConstraints/GlobalConstraintInterface.sol
pragma solidity 0.5.13;
contract GlobalConstraintInterface {
enum CallPhase { Pre, Post, PreAndPost }
function pre( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool);
function post( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool);
/**
* @dev when return if this globalConstraints is pre, post or both.
* @return CallPhase enum indication Pre, Post or PreAndPost.
*/
function when() public returns(CallPhase);
}
// File: @daostack/arc/contracts/controller/Controller.sol
pragma solidity 0.5.13;
/**
* @title Controller contract
* @dev A controller controls the organizations tokens, reputation and avatar.
* It is subject to a set of schemes and constraints that determine its behavior.
* Each scheme has it own parameters and operation permissions.
*/
contract Controller {
struct Scheme {
bytes32 paramsHash; // a hash "configuration" of the scheme
bytes4 permissions; // A bitwise flags of permissions,
// All 0: Not registered,
// 1st bit: Flag if the scheme is registered,
// 2nd bit: Scheme can register other schemes
// 3rd bit: Scheme can add/remove global constraints
// 4th bit: Scheme can upgrade the controller
// 5th bit: Scheme can call genericCall on behalf of
// the organization avatar
}
struct GlobalConstraint {
address gcAddress;
bytes32 params;
}
struct GlobalConstraintRegister {
bool isRegistered; //is registered
uint256 index; //index at globalConstraints
}
mapping(address=>Scheme) public schemes;
Avatar public avatar;
DAOToken public nativeToken;
Reputation public nativeReputation;
// newController will point to the new controller after the present controller is upgraded
address public newController;
// globalConstraintsPre that determine pre conditions for all actions on the controller
GlobalConstraint[] public globalConstraintsPre;
// globalConstraintsPost that determine post conditions for all actions on the controller
GlobalConstraint[] public globalConstraintsPost;
// globalConstraintsRegisterPre indicate if a globalConstraints is registered as a pre global constraint
mapping(address=>GlobalConstraintRegister) public globalConstraintsRegisterPre;
// globalConstraintsRegisterPost indicate if a globalConstraints is registered as a post global constraint
mapping(address=>GlobalConstraintRegister) public globalConstraintsRegisterPost;
event MintReputation (address indexed _sender, address indexed _to, uint256 _amount);
event BurnReputation (address indexed _sender, address indexed _from, uint256 _amount);
event MintTokens (address indexed _sender, address indexed _beneficiary, uint256 _amount);
event RegisterScheme (address indexed _sender, address indexed _scheme);
event UnregisterScheme (address indexed _sender, address indexed _scheme);
event UpgradeController(address indexed _oldController, address _newController);
event AddGlobalConstraint(
address indexed _globalConstraint,
bytes32 _params,
GlobalConstraintInterface.CallPhase _when);
event RemoveGlobalConstraint(address indexed _globalConstraint, uint256 _index, bool _isPre);
constructor( Avatar _avatar) public {
avatar = _avatar;
nativeToken = avatar.nativeToken();
nativeReputation = avatar.nativeReputation();
schemes[msg.sender] = Scheme({paramsHash: bytes32(0), permissions: bytes4(0x0000001F)});
emit RegisterScheme (msg.sender, msg.sender);
}
// Do not allow mistaken calls:
// solhint-disable-next-line payable-fallback
function() external {
revert();
}
// Modifiers:
modifier onlyRegisteredScheme() {
require(schemes[msg.sender].permissions&bytes4(0x00000001) == bytes4(0x00000001));
_;
}
modifier onlyRegisteringSchemes() {
require(schemes[msg.sender].permissions&bytes4(0x00000002) == bytes4(0x00000002));
_;
}
modifier onlyGlobalConstraintsScheme() {
require(schemes[msg.sender].permissions&bytes4(0x00000004) == bytes4(0x00000004));
_;
}
modifier onlyUpgradingScheme() {
require(schemes[msg.sender].permissions&bytes4(0x00000008) == bytes4(0x00000008));
_;
}
modifier onlyGenericCallScheme() {
require(schemes[msg.sender].permissions&bytes4(0x00000010) == bytes4(0x00000010));
_;
}
modifier onlyMetaDataScheme() {
require(schemes[msg.sender].permissions&bytes4(0x00000010) == bytes4(0x00000010));
_;
}
modifier onlySubjectToConstraint(bytes32 func) {
uint256 idx;
for (idx = 0; idx < globalConstraintsPre.length; idx++) {
require(
(GlobalConstraintInterface(globalConstraintsPre[idx].gcAddress))
.pre(msg.sender, globalConstraintsPre[idx].params, func));
}
_;
for (idx = 0; idx < globalConstraintsPost.length; idx++) {
require(
(GlobalConstraintInterface(globalConstraintsPost[idx].gcAddress))
.post(msg.sender, globalConstraintsPost[idx].params, func));
}
}
modifier isAvatarValid(address _avatar) {
require(_avatar == address(avatar));
_;
}
/**
* @dev Mint `_amount` of reputation that are assigned to `_to` .
* @param _amount amount of reputation to mint
* @param _to beneficiary address
* @return bool which represents a success
*/
function mintReputation(uint256 _amount, address _to, address _avatar)
external
onlyRegisteredScheme
onlySubjectToConstraint("mintReputation")
isAvatarValid(_avatar)
returns(bool)
{
emit MintReputation(msg.sender, _to, _amount);
return nativeReputation.mint(_to, _amount);
}
/**
* @dev Burns `_amount` of reputation from `_from`
* @param _amount amount of reputation to burn
* @param _from The address that will lose the reputation
* @return bool which represents a success
*/
function burnReputation(uint256 _amount, address _from, address _avatar)
external
onlyRegisteredScheme
onlySubjectToConstraint("burnReputation")
isAvatarValid(_avatar)
returns(bool)
{
emit BurnReputation(msg.sender, _from, _amount);
return nativeReputation.burn(_from, _amount);
}
/**
* @dev mint tokens .
* @param _amount amount of token to mint
* @param _beneficiary beneficiary address
* @return bool which represents a success
*/
function mintTokens(uint256 _amount, address _beneficiary, address _avatar)
external
onlyRegisteredScheme
onlySubjectToConstraint("mintTokens")
isAvatarValid(_avatar)
returns(bool)
{
emit MintTokens(msg.sender, _beneficiary, _amount);
return nativeToken.mint(_beneficiary, _amount);
}
/**
* @dev register a scheme
* @param _scheme the address of the scheme
* @param _paramsHash a hashed configuration of the usage of the scheme
* @param _permissions the permissions the new scheme will have
* @return bool which represents a success
*/
function registerScheme(address _scheme, bytes32 _paramsHash, bytes4 _permissions, address _avatar)
external
onlyRegisteringSchemes
onlySubjectToConstraint("registerScheme")
isAvatarValid(_avatar)
returns(bool)
{
Scheme memory scheme = schemes[_scheme];
// Check scheme has at least the permissions it is changing, and at least the current permissions:
// Implementation is a bit messy. One must recall logic-circuits ^^
// produces non-zero if sender does not have all of the perms that are changing between old and new
require(bytes4(0x0000001f)&(_permissions^scheme.permissions)&(~schemes[msg.sender].permissions) == bytes4(0));
// produces non-zero if sender does not have all of the perms in the old scheme
require(bytes4(0x0000001f)&(scheme.permissions&(~schemes[msg.sender].permissions)) == bytes4(0));
// Add or change the scheme:
schemes[_scheme].paramsHash = _paramsHash;
schemes[_scheme].permissions = _permissions|bytes4(0x00000001);
emit RegisterScheme(msg.sender, _scheme);
return true;
}
/**
* @dev unregister a scheme
* @param _scheme the address of the scheme
* @return bool which represents a success
*/
function unregisterScheme( address _scheme, address _avatar)
external
onlyRegisteringSchemes
onlySubjectToConstraint("unregisterScheme")
isAvatarValid(_avatar)
returns(bool)
{
//check if the scheme is registered
if (_isSchemeRegistered(_scheme) == false) {
return false;
}
// Check the unregistering scheme has enough permissions:
require(bytes4(0x0000001f)&(schemes[_scheme].permissions&(~schemes[msg.sender].permissions)) == bytes4(0));
// Unregister:
emit UnregisterScheme(msg.sender, _scheme);
delete schemes[_scheme];
return true;
}
/**
* @dev unregister the caller's scheme
* @return bool which represents a success
*/
function unregisterSelf(address _avatar) external isAvatarValid(_avatar) returns(bool) {
if (_isSchemeRegistered(msg.sender) == false) {
return false;
}
delete schemes[msg.sender];
emit UnregisterScheme(msg.sender, msg.sender);
return true;
}
/**
* @dev add or update Global Constraint
* @param _globalConstraint the address of the global constraint to be added.
* @param _params the constraint parameters hash.
* @return bool which represents a success
*/
function addGlobalConstraint(address _globalConstraint, bytes32 _params, address _avatar)
external
onlyGlobalConstraintsScheme
isAvatarValid(_avatar)
returns(bool)
{
GlobalConstraintInterface.CallPhase when = GlobalConstraintInterface(_globalConstraint).when();
if ((when == GlobalConstraintInterface.CallPhase.Pre)||
(when == GlobalConstraintInterface.CallPhase.PreAndPost)) {
if (!globalConstraintsRegisterPre[_globalConstraint].isRegistered) {
globalConstraintsPre.push(GlobalConstraint(_globalConstraint, _params));
globalConstraintsRegisterPre[_globalConstraint] =
GlobalConstraintRegister(true, globalConstraintsPre.length-1);
}else {
globalConstraintsPre[globalConstraintsRegisterPre[_globalConstraint].index].params = _params;
}
}
if ((when == GlobalConstraintInterface.CallPhase.Post)||
(when == GlobalConstraintInterface.CallPhase.PreAndPost)) {
if (!globalConstraintsRegisterPost[_globalConstraint].isRegistered) {
globalConstraintsPost.push(GlobalConstraint(_globalConstraint, _params));
globalConstraintsRegisterPost[_globalConstraint] =
GlobalConstraintRegister(true, globalConstraintsPost.length-1);
}else {
globalConstraintsPost[globalConstraintsRegisterPost[_globalConstraint].index].params = _params;
}
}
emit AddGlobalConstraint(_globalConstraint, _params, when);
return true;
}
/**
* @dev remove Global Constraint
* @param _globalConstraint the address of the global constraint to be remove.
* @return bool which represents a success
*/
// solhint-disable-next-line code-complexity
function removeGlobalConstraint (address _globalConstraint, address _avatar)
external
onlyGlobalConstraintsScheme
isAvatarValid(_avatar)
returns(bool)
{
GlobalConstraintRegister memory globalConstraintRegister;
GlobalConstraint memory globalConstraint;
GlobalConstraintInterface.CallPhase when = GlobalConstraintInterface(_globalConstraint).when();
bool retVal = false;
if ((when == GlobalConstraintInterface.CallPhase.Pre)||
(when == GlobalConstraintInterface.CallPhase.PreAndPost)) {
globalConstraintRegister = globalConstraintsRegisterPre[_globalConstraint];
if (globalConstraintRegister.isRegistered) {
if (globalConstraintRegister.index < globalConstraintsPre.length-1) {
globalConstraint = globalConstraintsPre[globalConstraintsPre.length-1];
globalConstraintsPre[globalConstraintRegister.index] = globalConstraint;
globalConstraintsRegisterPre[globalConstraint.gcAddress].index = globalConstraintRegister.index;
}
globalConstraintsPre.length--;
delete globalConstraintsRegisterPre[_globalConstraint];
retVal = true;
}
}
if ((when == GlobalConstraintInterface.CallPhase.Post)||
(when == GlobalConstraintInterface.CallPhase.PreAndPost)) {
globalConstraintRegister = globalConstraintsRegisterPost[_globalConstraint];
if (globalConstraintRegister.isRegistered) {
if (globalConstraintRegister.index < globalConstraintsPost.length-1) {
globalConstraint = globalConstraintsPost[globalConstraintsPost.length-1];
globalConstraintsPost[globalConstraintRegister.index] = globalConstraint;
globalConstraintsRegisterPost[globalConstraint.gcAddress].index = globalConstraintRegister.index;
}
globalConstraintsPost.length--;
delete globalConstraintsRegisterPost[_globalConstraint];
retVal = true;
}
}
if (retVal) {
emit RemoveGlobalConstraint(
_globalConstraint,
globalConstraintRegister.index,
when == GlobalConstraintInterface.CallPhase.Pre
);
}
return retVal;
}
/**
* @dev upgrade the Controller
* The function will trigger an event 'UpgradeController'.
* @param _newController the address of the new controller.
* @return bool which represents a success
*/
function upgradeController(address _newController, Avatar _avatar)
external
onlyUpgradingScheme
isAvatarValid(address(_avatar))
returns(bool)
{
require(newController == address(0)); // so the upgrade could be done once for a contract.
require(_newController != address(0));
newController = _newController;
avatar.transferOwnership(_newController);
require(avatar.owner() == _newController);
if (nativeToken.owner() == address(this)) {
nativeToken.transferOwnership(_newController);
require(nativeToken.owner() == _newController);
}
if (nativeReputation.owner() == address(this)) {
nativeReputation.transferOwnership(_newController);
require(nativeReputation.owner() == _newController);
}
emit UpgradeController(address(this), newController);
return true;
}
/**
* @dev perform a generic call to an arbitrary contract
* @param _contract the contract's address to call
* @param _data ABI-encoded contract call to call `_contract` address.
* @param _avatar the controller's avatar address
* @param _value value (ETH) to transfer with the transaction
* @return bool -success
* bytes - the return value of the called _contract's function.
*/
function genericCall(address _contract, bytes calldata _data, Avatar _avatar, uint256 _value)
external
onlyGenericCallScheme
onlySubjectToConstraint("genericCall")
isAvatarValid(address(_avatar))
returns (bool, bytes memory)
{
return avatar.genericCall(_contract, _data, _value);
}
/**
* @dev send some ether
* @param _amountInWei the amount of ether (in Wei) to send
* @param _to address of the beneficiary
* @return bool which represents a success
*/
function sendEther(uint256 _amountInWei, address payable _to, Avatar _avatar)
external
onlyRegisteredScheme
onlySubjectToConstraint("sendEther")
isAvatarValid(address(_avatar))
returns(bool)
{
return avatar.sendEther(_amountInWei, _to);
}
/**
* @dev send some amount of arbitrary ERC20 Tokens
* @param _externalToken the address of the Token Contract
* @param _to address of the beneficiary
* @param _value the amount of ether (in Wei) to send
* @return bool which represents a success
*/
function externalTokenTransfer(IERC20 _externalToken, address _to, uint256 _value, Avatar _avatar)
external
onlyRegisteredScheme
onlySubjectToConstraint("externalTokenTransfer")
isAvatarValid(address(_avatar))
returns(bool)
{
return avatar.externalTokenTransfer(_externalToken, _to, _value);
}
/**
* @dev transfer token "from" address "to" address
* One must to approve the amount of tokens which can be spend from the
* "from" account.This can be done using externalTokenApprove.
* @param _externalToken the address of the Token Contract
* @param _from address of the account to send from
* @param _to address of the beneficiary
* @param _value the amount of ether (in Wei) to send
* @return bool which represents a success
*/
function externalTokenTransferFrom(
IERC20 _externalToken,
address _from,
address _to,
uint256 _value,
Avatar _avatar)
external
onlyRegisteredScheme
onlySubjectToConstraint("externalTokenTransferFrom")
isAvatarValid(address(_avatar))
returns(bool)
{
return avatar.externalTokenTransferFrom(_externalToken, _from, _to, _value);
}
/**
* @dev externalTokenApproval approve the spender address to spend a specified amount of tokens
* on behalf of msg.sender.
* @param _externalToken the address of the Token Contract
* @param _spender address
* @param _value the amount of ether (in Wei) which the approval is referring to.
* @return bool which represents a success
*/
function externalTokenApproval(IERC20 _externalToken, address _spender, uint256 _value, Avatar _avatar)
external
onlyRegisteredScheme
onlySubjectToConstraint("externalTokenIncreaseApproval")
isAvatarValid(address(_avatar))
returns(bool)
{
return avatar.externalTokenApproval(_externalToken, _spender, _value);
}
/**
* @dev metaData emits an event with a string, should contain the hash of some meta data.
* @param _metaData a string representing a hash of the meta data
* @param _avatar Avatar
* @return bool which represents a success
*/
function metaData(string calldata _metaData, Avatar _avatar)
external
onlyMetaDataScheme
isAvatarValid(address(_avatar))
returns(bool)
{
return avatar.metaData(_metaData);
}
/**
* @dev getNativeReputation
* @param _avatar the organization avatar.
* @return organization native reputation
*/
function getNativeReputation(address _avatar) external isAvatarValid(_avatar) view returns(address) {
return address(nativeReputation);
}
function isSchemeRegistered(address _scheme, address _avatar) external isAvatarValid(_avatar) view returns(bool) {
return _isSchemeRegistered(_scheme);
}
function getSchemeParameters(address _scheme, address _avatar)
external
isAvatarValid(_avatar)
view
returns(bytes32)
{
return schemes[_scheme].paramsHash;
}
function getSchemePermissions(address _scheme, address _avatar)
external
isAvatarValid(_avatar)
view
returns(bytes4)
{
return schemes[_scheme].permissions;
}
function getGlobalConstraintParameters(address _globalConstraint, address) external view returns(bytes32) {
GlobalConstraintRegister memory register = globalConstraintsRegisterPre[_globalConstraint];
if (register.isRegistered) {
return globalConstraintsPre[register.index].params;
}
register = globalConstraintsRegisterPost[_globalConstraint];
if (register.isRegistered) {
return globalConstraintsPost[register.index].params;
}
}
/**
* @dev globalConstraintsCount return the global constraint pre and post count
* @return uint256 globalConstraintsPre count.
* @return uint256 globalConstraintsPost count.
*/
function globalConstraintsCount(address _avatar)
external
isAvatarValid(_avatar)
view
returns(uint, uint)
{
return (globalConstraintsPre.length, globalConstraintsPost.length);
}
function isGlobalConstraintRegistered(address _globalConstraint, address _avatar)
external
isAvatarValid(_avatar)
view
returns(bool)
{
return (globalConstraintsRegisterPre[_globalConstraint].isRegistered ||
globalConstraintsRegisterPost[_globalConstraint].isRegistered);
}
function _isSchemeRegistered(address _scheme) private view returns(bool) {
return (schemes[_scheme].permissions&bytes4(0x00000001) != bytes4(0));
}
}
// File: contracts/interfaces/IUniswapV2Factory.sol
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// File: contracts/interfaces/IUniswapV2Router02.sol
pragma solidity >=0.5.0;
interface IUniswapV2Router02 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
// V1
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
// V2
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// File: contracts/UniswapProxy.sol
pragma solidity >=0.5.13;
/**
* @title A UniswapV2 proxy made with ❤️ for the necDAO folks
* @dev Enable necDAO to swap tokens and provide liquidity through UniswapV2 pairs.
*/
contract UniswapProxy {
using SafeMath for uint256;
uint256 constant PPM = 1000000; // 100% = 1000000 | 50% = 500000 | 0% = 0
string constant ERROR_ROUTER = "UniswapProxy: router cannot be null";
string constant ERROR_PAIR = "UniswapProxy: invalid pair";
string constant ERROR_AMOUNT = "UniswapProxy: invalid amount";
string constant ERROR_APPROVAL = "UniswapProxy: ERC20 approval failed";
string constant ERROR_SWAP = "UniswapProxy: swap failed";
string constant ERROR_POOL = "UniswapProxy: pool failed";
string constant ERROR_UNPOOL = "UniswapProxy: unpool failed";
bool public initialized;
Avatar public avatar;
IUniswapV2Router02 public router;
event Swap (address indexed from, address indexed to, uint256 amount, uint256 expected, uint256 returned);
event Pool (
address indexed token1,
address indexed token2,
uint256 amount1,
uint256 amount2,
uint256 min1,
uint256 min2,
uint256 pooled1,
uint256 pooled2,
uint256 returned
);
event Unpool (
address indexed token1,
address indexed token2,
uint256 amount,
uint256 expected1,
uint256 expected2,
uint256 returned1,
uint256 returned2
);
modifier initializer() {
require(!initialized, "UniswapProxy: already initialized");
initialized = true;
_;
}
modifier protected() {
require(initialized, "UniswapProxy: not initialized");
require(msg.sender == address(avatar), "UniswapProxy: protected operation");
_;
}
/**
* @dev Initialize proxy.
* @param _avatar The address of the Avatar which will control this proxy.
* @param _router The address of the UniswapV2 router through which this proxy will interact with UniswapV2.
*/
function initialize(Avatar _avatar, IUniswapV2Router02 _router) external initializer {
require(_avatar != Avatar(0), "UniswapProxy: avatar cannot be null");
require(_router != IUniswapV2Router02(0), ERROR_ROUTER);
avatar = _avatar;
router = _router;
}
/**
* @dev Swap tokens.
* @param _from The address of the token to swap from [address(0) for ETH].
* @param _to The address of the token to swap to [address(0) for ETH].
* @param _amount The amount of `_from` token to swap.
* @param _expected The minimum amount of `_to` token to expect in return for the swap [reverts otherwise].
*/
function swap(address _from, address _to, uint256 _amount, uint256 _expected) external protected {
require(_from != _to, ERROR_PAIR);
require(_amount > 0, ERROR_AMOUNT);
_swap(_from, _to, _amount, _expected);
}
/**
* @dev Pool tokens.
* @param _token1 The address of the pair's first token [address(0) for ETH].
* @param _token2 The address of the pair's second token [address(0) for ETH].
* @param _amount1 The amount of `_token1` to pool.
* @param _amount2 The amount of `_token2` to pool.
* @param _slippage The allowed price slippage [reverts otherwise].
*/
function pool(
address _token1,
address _token2,
uint256 _amount1,
uint256 _amount2,
uint256 _slippage
) external protected {
require(_token1 != _token2, ERROR_PAIR);
require(_amount1 > 0 && _amount2 > 0, ERROR_AMOUNT);
require(_slippage <= PPM, "UniswapProxy: invalid slippage");
_pool(_token1, _token2, _amount1, _amount2, _slippage);
}
/**
* @dev Unpool tokens.
* @param _token1 The address of the pair's first token [address(0) for ETH].
* @param _token2 The address of the pair's second token [address(0) for ETH].
* @param _amount The amount of liquidity token to unpool.
* @param _expected1 The minimum amount of `_token1` to expect in return for this transaction [reverts otherwise].
* @param _expected2 The minimum amount of `_token2` to expect in return for this transaction [reverts otherwise].
*/
function unpool(
address _token1,
address _token2,
uint256 _amount,
uint256 _expected1,
uint256 _expected2
) external protected {
require(_token1 != _token2, ERROR_PAIR);
require(_amount > 0, ERROR_AMOUNT);
_unpool(_token1, _token2, _amount, _expected1, _expected2);
}
/**
* @dev Upgrade UniswapV2 router address.
* @param _router The address of the new UniswapV2 router through which this proxy will interact with UniswapV2.
*/
function upgradeRouter(IUniswapV2Router02 _router) external protected {
require(_router != IUniswapV2Router02(0), ERROR_ROUTER);
router = _router;
}
/* internal state-modifying functions */
function _swap(address _from, address _to, uint256 _amount, uint256 _expected) internal {
Controller controller = Controller(avatar.owner());
address[] memory path = new address[](2);
bytes memory returned;
bool success;
if (_from != address(0) && _to != address(0)) {
path[0] = _from;
path[1] = _to;
_approve(_from, _amount);
(success, returned) = controller.genericCall(
address(router),
abi.encodeWithSelector(
router.swapExactTokensForTokens.selector,
_amount,
_expected,
path,
avatar,
block.timestamp
),
avatar,
0
);
require(success, ERROR_SWAP);
} else if (_from == address(0)) {
path[0] = router.WETH();
path[1] = _to;
(success, returned) = controller.genericCall(
address(router),
abi.encodeWithSelector(router.swapExactETHForTokens.selector, _expected, path, avatar, block.timestamp),
avatar,
_amount
);
require(success, ERROR_SWAP);
} else if (_to == address(0)) {
path[0] = _from;
path[1] = router.WETH();
_approve(_from, _amount);
(success, returned) = controller.genericCall(
address(router),
abi.encodeWithSelector(
router.swapExactTokensForETH.selector,
_amount,
_expected,
path,
avatar,
block.timestamp
),
avatar,
0
);
require(success, ERROR_SWAP);
}
emit Swap(_from, _to, _amount, _expected, _parseSwapReturn(returned));
}
function _pool(address _token1, address _token2, uint256 _amount1, uint256 _amount2, uint256 _slippage) internal {
Controller controller = Controller(avatar.owner());
bytes memory returned;
bool success;
uint256 min1 = _amount1.sub(_amount1.mul(_slippage).div(PPM));
uint256 min2 = _amount2.sub(_amount2.mul(_slippage).div(PPM));
if (_token1 != address(0) && _token2 != address(0)) {
_approve(_token1, _amount1);
_approve(_token2, _amount2);
(success, returned) = controller.genericCall(
address(router),
abi.encodeWithSelector(
router.addLiquidity.selector,
_token1,
_token2,
_amount1,
_amount2,
min1,
min2,
avatar,
block.timestamp
),
avatar,
0
);
require(success, ERROR_POOL);
} else {
address token = _token1 == address(0) ? _token2 : _token1;
uint256 amount = _token1 == address(0) ? _amount2 : _amount1;
uint256 value = _token1 == address(0) ? _amount1 : _amount2;
uint256 minToken = _token1 == address(0) ? min2 : min1;
uint256 minETH = _token1 == address(0) ? min1 : min2;
_approve(token, amount);
(success, returned) = controller.genericCall(
address(router),
abi.encodeWithSelector(
router.addLiquidityETH.selector,
token,
amount,
minToken,
minETH,
avatar,
block.timestamp
),
avatar,
value
);
require(success, ERROR_POOL);
}
(uint256 pooled1, uint256 pooled2, uint256 _returned) = _parsePoolReturn(_token1, returned);
emit Pool(_token1, _token2, _amount1, _amount2, min1, min2, pooled1, pooled2, _returned);
}
function _unpool(
address _token1,
address _token2,
uint256 _amount,
uint256 _expected1,
uint256 _expected2
) internal {
address pair = _pair(_token1, _token2);
Controller controller = Controller(avatar.owner());
bytes memory returned;
bool success;
_approve(pair, _amount);
if (_token1 != address(0) && _token2 != address(0)) {
(success, returned) = controller.genericCall(
address(router),
abi.encodeWithSelector(
router.removeLiquidity.selector,
_token1,
_token2,
_amount,
_expected1,
_expected2,
avatar,
block.timestamp
),
avatar,
0
);
require(success, ERROR_UNPOOL);
} else {
address token = _token1 == address(0) ? _token2 : _token1;
uint256 expectedToken = _token1 == address(0) ? _expected2 : _expected1;
uint256 expectedETH = _token1 == address(0) ? _expected1 : _expected2;
(success, returned) = controller.genericCall(
address(router),
abi.encodeWithSelector(
router.removeLiquidityETH.selector,
token,
_amount,
expectedToken,
expectedETH,
avatar,
block.timestamp
),
avatar,
0
);
require(success, ERROR_UNPOOL);
}
(uint256 returned1, uint256 returned2) = _parseUnpoolReturn(_token1, returned);
emit Unpool(_token1, _token2, _amount, _expected1, _expected2, returned1, returned2);
}
/* internal helpers functions */
function _approve(address _token, uint256 _amount) internal {
Controller controller = Controller(avatar.owner());
bool success;
if (IERC20(_token).allowance(address(avatar), address(router)) > 0) {
// reset allowance to make sure final approval does not revert
(success,) = controller.genericCall(
_token,
abi.encodeWithSelector(IERC20(_token).approve.selector, address(router), 0),
avatar,
0
);
require(success, ERROR_APPROVAL);
}
(success,) = controller.genericCall(
_token,
abi.encodeWithSelector(IERC20(_token).approve.selector, address(router), _amount),
avatar,
0
);
require(success, ERROR_APPROVAL);
}
function _pair(address _token1, address _token2) internal view returns (address) {
address token1 = _token1 == address(0) ? router.WETH() : _token1;
address token2 = _token2 == address(0) ? router.WETH() : _token2;
IUniswapV2Factory factory = IUniswapV2Factory(router.factory());
address pair = factory.getPair(token1, token2);
require(pair != address(0), ERROR_PAIR);
return pair;
}
function _parseSwapReturn(bytes memory data) internal pure returns (uint256 amount) {
assembly {
amount := mload(add(data, 128))
}
}
function _parsePoolReturn(
address _token1,
bytes memory data
) internal pure returns (uint256 pooled1, uint256 pooled2, uint256 returned) {
if (_token1 == address(0)) {
assembly {
pooled2 := mload(add(data, 32))
pooled1 := mload(add(data, 64))
returned := mload(add(data, 96))
}
} else {
assembly {
pooled1 := mload(add(data, 32))
pooled2 := mload(add(data, 64))
returned := mload(add(data, 96))
}
}
}
function _parseUnpoolReturn(
address _token1,
bytes memory data
) internal pure returns (uint256 returned1, uint256 returned2) {
if (_token1 == address(0)) {
assembly {
returned2 := mload(add(data, 32))
returned1 := mload(add(data, 64))
}
} else {
assembly {
returned1 := mload(add(data, 32))
returned2 := mload(add(data, 64))
}
}
}
} | * @dev remove Global Constraint @param _globalConstraint the address of the global constraint to be remove. @return bool which represents a success/ solhint-disable-next-line code-complexity | function removeGlobalConstraint (address _globalConstraint, address _avatar)
external
onlyGlobalConstraintsScheme
isAvatarValid(_avatar)
returns(bool)
{
GlobalConstraintRegister memory globalConstraintRegister;
GlobalConstraint memory globalConstraint;
GlobalConstraintInterface.CallPhase when = GlobalConstraintInterface(_globalConstraint).when();
bool retVal = false;
if ((when == GlobalConstraintInterface.CallPhase.Pre)||
(when == GlobalConstraintInterface.CallPhase.PreAndPost)) {
globalConstraintRegister = globalConstraintsRegisterPre[_globalConstraint];
if (globalConstraintRegister.isRegistered) {
if (globalConstraintRegister.index < globalConstraintsPre.length-1) {
globalConstraint = globalConstraintsPre[globalConstraintsPre.length-1];
globalConstraintsPre[globalConstraintRegister.index] = globalConstraint;
globalConstraintsRegisterPre[globalConstraint.gcAddress].index = globalConstraintRegister.index;
}
globalConstraintsPre.length--;
delete globalConstraintsRegisterPre[_globalConstraint];
retVal = true;
}
}
if ((when == GlobalConstraintInterface.CallPhase.Post)||
(when == GlobalConstraintInterface.CallPhase.PreAndPost)) {
globalConstraintRegister = globalConstraintsRegisterPost[_globalConstraint];
if (globalConstraintRegister.isRegistered) {
if (globalConstraintRegister.index < globalConstraintsPost.length-1) {
globalConstraint = globalConstraintsPost[globalConstraintsPost.length-1];
globalConstraintsPost[globalConstraintRegister.index] = globalConstraint;
globalConstraintsRegisterPost[globalConstraint.gcAddress].index = globalConstraintRegister.index;
}
globalConstraintsPost.length--;
delete globalConstraintsRegisterPost[_globalConstraint];
retVal = true;
}
}
if (retVal) {
emit RemoveGlobalConstraint(
_globalConstraint,
globalConstraintRegister.index,
when == GlobalConstraintInterface.CallPhase.Pre
);
}
return retVal;
}
| 1,357,781 | [
1,
4479,
8510,
10770,
225,
389,
6347,
5806,
326,
1758,
434,
326,
2552,
4954,
358,
506,
1206,
18,
327,
1426,
1492,
8686,
279,
2216,
19,
3704,
11317,
17,
8394,
17,
4285,
17,
1369,
981,
17,
14259,
560,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1206,
5160,
5806,
261,
2867,
389,
6347,
5806,
16,
1758,
389,
19660,
13,
203,
565,
3903,
203,
565,
1338,
5160,
4878,
9321,
203,
565,
353,
23999,
1556,
24899,
19660,
13,
203,
565,
1135,
12,
6430,
13,
203,
565,
288,
203,
3639,
8510,
5806,
3996,
3778,
2552,
5806,
3996,
31,
203,
3639,
8510,
5806,
3778,
2552,
5806,
31,
203,
3639,
8510,
5806,
1358,
18,
1477,
11406,
1347,
273,
8510,
5806,
1358,
24899,
6347,
5806,
2934,
13723,
5621,
203,
3639,
1426,
12197,
273,
629,
31,
203,
203,
3639,
309,
14015,
13723,
422,
8510,
5806,
1358,
18,
1477,
11406,
18,
1386,
14047,
96,
203,
5411,
261,
13723,
422,
8510,
5806,
1358,
18,
1477,
11406,
18,
1386,
1876,
3349,
3719,
288,
203,
5411,
2552,
5806,
3996,
273,
2552,
4878,
3996,
1386,
63,
67,
6347,
5806,
15533,
203,
5411,
309,
261,
6347,
5806,
3996,
18,
291,
10868,
13,
288,
203,
7734,
309,
261,
6347,
5806,
3996,
18,
1615,
411,
2552,
4878,
1386,
18,
2469,
17,
21,
13,
288,
203,
10792,
2552,
5806,
273,
2552,
4878,
1386,
63,
6347,
4878,
1386,
18,
2469,
17,
21,
15533,
203,
10792,
2552,
4878,
1386,
63,
6347,
5806,
3996,
18,
1615,
65,
273,
2552,
5806,
31,
203,
10792,
2552,
4878,
3996,
1386,
63,
6347,
5806,
18,
13241,
1887,
8009,
1615,
273,
2552,
5806,
3996,
18,
1615,
31,
203,
7734,
289,
203,
7734,
2552,
4878,
1386,
18,
2469,
413,
31,
203,
7734,
1430,
2552,
4878,
3996,
1386,
63,
67,
6347,
5806,
15533,
203,
7734,
12197,
273,
638,
31,
203,
5411,
289,
203,
3639,
2
] |
pragma solidity 0.4.20;
// we use solidity solidity 0.4.20 to work with oraclize (http://www.oraclize.it)
// solidity versions > 0.4.20 are not supported by oraclize
/*
Lucky Strike smart contracts version: 2.0
*/
/*
This smart contract is intended for entertainment purposes only. Cryptocurrency gambling is illegal in many jurisdictions and users should consult their legal counsel regarding the legal status of cryptocurrency gambling in their jurisdictions.
Since developers of this smart contract are unable to determine which jurisdiction you reside in, you must check current laws including your local and state laws to find out if cryptocurrency gambling is legal in your area.
If you reside in a location where cryptocurrency gambling is illegal, please do not interact with this smart contract in any way and leave it immediately.
*/
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
* source: https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// ORACLIZE_API
/*
Copyright (c) 2015-2016 Oraclize SRL
Copyright (c) 2016 Oraclize LTD
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
//pragma solidity >=0.4.1 <=0.4.20;// Incompatible compiler version... please select one stated within pragma solidity or use different oraclizeAPI version
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id);
function getPrice(string _datasource) returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice);
function useCoupon(string _coupon);
function setProofType(byte _proofType);
function setConfig(bytes32 _config);
function setCustomGasPrice(uint _gasPrice);
function randomDS_getSessionPubKeyHash() returns (bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() returns (address _addr);
}
/*
Begin solidity-cborutils
https://github.com/smartcontractkit/solidity-cborutils
MIT License
Copyright (c) 2018 SmartContract ChainLink, Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
library Buffer {
struct buffer {
bytes buf;
uint capacity;
}
function init(buffer memory buf, uint capacity) internal constant {
if (capacity % 32 != 0) capacity += 32 - (capacity % 32);
// Allocate space for the buffer data
buf.capacity = capacity;
assembly {
let ptr := mload(0x40)
mstore(buf, ptr)
mstore(0x40, add(ptr, capacity))
}
}
function resize(buffer memory buf, uint capacity) private constant {
bytes memory oldbuf = buf.buf;
init(buf, capacity);
append(buf, oldbuf);
}
function max(uint a, uint b) private constant returns (uint) {
if (a > b) {
return a;
}
return b;
}
/**
* @dev Appends a byte array to the end of the buffer. Reverts if doing so
* would exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function append(buffer memory buf, bytes data) internal constant returns (buffer memory) {
if (data.length + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, data.length) * 2);
}
uint dest;
uint src;
uint len = data.length;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Start address = buffer address + buffer length + sizeof(buffer length)
dest := add(add(bufptr, buflen), 32)
// Update buffer length
mstore(bufptr, add(buflen, mload(data)))
src := add(data, 32)
}
// Copy word-length chunks while possible
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
/**
* @dev Appends a byte to the end of the buffer. Reverts if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function append(buffer memory buf, uint8 data) internal constant {
if (buf.buf.length + 1 > buf.capacity) {
resize(buf, buf.capacity * 2);
}
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Address = buffer address + buffer length + sizeof(buffer length)
let dest := add(add(bufptr, buflen), 32)
mstore8(dest, data)
// Update buffer length
mstore(bufptr, add(buflen, 1))
}
}
/**
* @dev Appends a byte to the end of the buffer. Reverts if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function appendInt(buffer memory buf, uint data, uint len) internal constant returns (buffer memory) {
if (len + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, len) * 2);
}
uint mask = 256 ** len - 1;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Address = buffer address + buffer length + sizeof(buffer length) + len
let dest := add(add(bufptr, buflen), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
// Update buffer length
mstore(bufptr, add(buflen, len))
}
return buf;
}
}
library CBOR {
using Buffer for Buffer.buffer;
uint8 private constant MAJOR_TYPE_INT = 0;
uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;
uint8 private constant MAJOR_TYPE_BYTES = 2;
uint8 private constant MAJOR_TYPE_STRING = 3;
uint8 private constant MAJOR_TYPE_ARRAY = 4;
uint8 private constant MAJOR_TYPE_MAP = 5;
uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7;
function shl8(uint8 x, uint8 y) private constant returns (uint8) {
return x * (2 ** y);
}
function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private constant {
if (value <= 23) {
buf.append(uint8(shl8(major, 5) | value));
} else if (value <= 0xFF) {
buf.append(uint8(shl8(major, 5) | 24));
buf.appendInt(value, 1);
} else if (value <= 0xFFFF) {
buf.append(uint8(shl8(major, 5) | 25));
buf.appendInt(value, 2);
} else if (value <= 0xFFFFFFFF) {
buf.append(uint8(shl8(major, 5) | 26));
buf.appendInt(value, 4);
} else if (value <= 0xFFFFFFFFFFFFFFFF) {
buf.append(uint8(shl8(major, 5) | 27));
buf.appendInt(value, 8);
}
}
function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private constant {
buf.append(uint8(shl8(major, 5) | 31));
}
function encodeUInt(Buffer.buffer memory buf, uint value) internal constant {
encodeType(buf, MAJOR_TYPE_INT, value);
}
function encodeInt(Buffer.buffer memory buf, int value) internal constant {
if (value >= 0) {
encodeType(buf, MAJOR_TYPE_INT, uint(value));
} else {
encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(- 1 - value));
}
}
function encodeBytes(Buffer.buffer memory buf, bytes value) internal constant {
encodeType(buf, MAJOR_TYPE_BYTES, value.length);
buf.append(value);
}
function encodeString(Buffer.buffer memory buf, string value) internal constant {
encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length);
buf.append(bytes(value));
}
function startArray(Buffer.buffer memory buf) internal constant {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY);
}
function startMap(Buffer.buffer memory buf) internal constant {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP);
}
function endSequence(Buffer.buffer memory buf) internal constant {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE);
}
}
/*
End solidity-cborutils
*/
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());
oraclize.useCoupon(code);
_;
}
function oraclize_setNetwork(uint8 networkID) 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) {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) {
}
function oraclize_useCoupon(string code) oraclizeAPI internal {
oraclize.useCoupon(code);
}
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_setConfig(bytes32 config) oraclizeAPI internal {
return oraclize.setConfig(config);
}
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 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 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 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 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 returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal 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 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);
}
using CBOR for Buffer.buffer;
function stra2cbor(string[] arr) internal constant returns (bytes) {
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < arr.length; i++) {
buf.encodeString(arr[i]);
}
buf.endSequence();
return buf.buf;
}
function ba2cbor(bytes[] arr) internal constant returns (bytes) {
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < arr.length; i++) {
buf.encodeBytes(arr[i]);
}
buf.endSequence();
return buf.buf;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
if ((_nbytes == 0) || (_nbytes > 32)) throw;
// 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, sha3(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(sha3(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(sha3(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] = 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)
if ((_proof[0] != "L") || (_proof[1] != "P") || (_proof[2] != 1)) throw;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) throw;
_;
}
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 returns (bool){
bool match_ = true;
if (prefix.length != n_random_bytes) throw;
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 (!(sha3(keyhash) == sha3(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, sha3(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] == sha3(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 returns (bytes) {
uint minLength = length + toOffset;
if (to.length < minLength) {
// Buffer too small
throw;
// 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);
}
}
// end of ORACLIZE_API
// =============== Lucky Strike ========================================================================================
contract LuckyStrikeTokens {
function totalSupply() constant returns (uint256);
function balanceOf(address _owner) constant returns (uint256);
function mint(address to, uint256 value, uint256 _invest) public returns (bool);
function tokenSaleIsRunning() public returns (bool);
}
contract LuckyStrike is usingOraclize {
/* --- see: https://github.com/oraclize/ethereum-examples/blob/master/solidity/random-datasource/randomExample.sol */
// see: https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/token/ERC20/BasicToken.sol
using SafeMath for uint256;
using SafeMath for uint16;
address public owner;
address admin;
//
uint256 public ticketPriceInWei = 20000000000000000; // 0.02 ETH
uint256 public tokenPriceInWei = 150000000000000; // 0.00015 ETH
uint16 public maxTicketsToBuyInOneTransaction = 333; //
//
uint256 public eventsCounter;
//
mapping(uint256 => address) public theLotteryTicket;
uint256 public ticketsTotal;
//
address public kingOfTheHill;
uint256 public kingOfTheHillTicketsNumber;
mapping(address => uint256) public reward;
event rewardPaid(uint256 indexed eventsCounter, address indexed to, uint256 sum); //
function getReward() public {
require(reward[msg.sender] > 0);
msg.sender.transfer(reward[msg.sender]);
eventsCounter = eventsCounter + 1;
rewardPaid(eventsCounter, msg.sender, reward[msg.sender]);
sum[affiliateRewards] = sum[affiliateRewards].sub(reward[msg.sender]);
reward[msg.sender] = 0;
}
// gas for oraclize_query:
uint256 public oraclizeCallbackGas = 230000; // amount of gas we want Oraclize to set for the callback function
// > to be able to read it from browser after updating
uint256 public currentOraclizeGasPrice; //
function oraclizeGetPrice() public returns (uint256){
currentOraclizeGasPrice = oraclize_getPrice("random", oraclizeCallbackGas);
return currentOraclizeGasPrice;
}
function getContractsWeiBalance() public view returns (uint256) {
return this.balance;
}
// mapping to keep sums on accounts (including 'income'):
mapping(uint8 => uint256) public sum;
uint8 public instantGame = 0;
uint8 public dailyJackpot = 1;
uint8 public weeklyJackpot = 2;
uint8 public monthlyJackpot = 3;
uint8 public yearlyJackpot = 4;
uint8 public income = 5;
uint8 public marketingFund = 6;
uint8 public affiliateRewards = 7; //
uint8 public playersBets = 8;
mapping(uint8 => uint256) public period; // in seconds
event withdrawalFromMarketingFund(uint256 indexed eventsCounter, uint256 sum); //
function withdrawFromMarketingFund() public {
require(msg.sender == owner);
owner.transfer(sum[marketingFund]);
eventsCounter = eventsCounter + 1;
withdrawalFromMarketingFund(eventsCounter, sum[marketingFund]);
sum[marketingFund] = 0;
}
mapping(uint8 => bool) public jackpotPlayIsRunning; //
// allocation:
mapping(uint8 => uint16) public rate;
// JackpotCounters (starts with 0):
mapping(uint8 => uint256) jackpotCounter;
mapping(uint8 => uint256) public lastJackpotTime; // unix time
// uint256 public lastDividendsPaymentTime; // unix time, for 'income' only
address public luckyStrikeTokensContractAddress;
LuckyStrikeTokens public luckyStrikeTokens;
/* --- constructor */
// (!) requires acces to Oraclize contract
// will fail on JavaScript VM
function LuckyStrike() public {
admin = msg.sender;
// sets the Ledger authenticity proof in the constructor
oraclize_setProof(proofType_Ledger);
}
function init(address _luckyStrikeTokensContractAddress) public payable {
require(ticketsTotal == 0);
require(msg.sender == admin);
owner = 0x0bBAb60c495413c870F8cABF09436BeE9fe3542F;
require(msg.value / ticketPriceInWei >= 1);
luckyStrikeTokensContractAddress = _luckyStrikeTokensContractAddress;
// should be updated every time we use it
// now we just get value to show in webapp
oraclizeGetPrice();
kingOfTheHill = msg.sender;
ticketsTotal = kingOfTheHillTicketsNumber = 1;
theLotteryTicket[1] = kingOfTheHill;
// initialize jackpot periods
// see: https://solidity.readthedocs.io/en/v0.4.20/units-and-global-variables.html#time-units
period[dailyJackpot] = 1 days;
period[weeklyJackpot] = 1 weeks;
period[monthlyJackpot] = 30 days;
period[yearlyJackpot] = 1 years;
// for testing:
// period[dailyJackpot] = 60 * 1;
// period[weeklyJackpot] = 60 * 3;
// period[monthlyJackpot] = 60 * 5;
// period[yearlyJackpot] = 60 * 7;
// set last block numbers and timestamps for jackpots:
for (uint8 i = dailyJackpot; i <= yearlyJackpot; i++) {
lastJackpotTime[i] = block.timestamp;
}
rate[instantGame] = 8500;
rate[dailyJackpot] = 500;
rate[weeklyJackpot] = 300;
rate[monthlyJackpot] = 100;
rate[yearlyJackpot] = 100;
rate[income] = 500;
luckyStrikeTokens = LuckyStrikeTokens(luckyStrikeTokensContractAddress);
}
/* --- Tokens contract information */
function tokensTotalSupply() public view returns (uint256) {
return luckyStrikeTokens.totalSupply();
}
function tokensBalanceOf(address acc) public view returns (uint256){
return luckyStrikeTokens.balanceOf(acc);
}
function weiInTokensContract() public view returns (uint256){
return luckyStrikeTokens.balance;
}
function tokenSaleIsRunning() public view returns (bool) {
return luckyStrikeTokens.tokenSaleIsRunning();
}
event AllocationAdjusted(
uint256 indexed eventsCounter,
address by,
uint16 instantGame,
uint16 dailyJackpot,
uint16 weeklyJackpot,
uint16 monthlyJackpot,
uint16 yearlyJackpot,
uint16 income);
function adjustAllocation(
uint16 _instantGame,
uint16 _dailyJackpot,
uint16 _weeklyJackpot,
uint16 _monthlyJackpot,
uint16 _yearlyJackpot,
uint16 _income) public {
// only owner !!!
require(msg.sender == owner);
rate[instantGame] = _instantGame;
rate[dailyJackpot] = _dailyJackpot;
rate[weeklyJackpot] = _weeklyJackpot;
rate[monthlyJackpot] = _monthlyJackpot;
rate[yearlyJackpot] = _yearlyJackpot;
rate[income] = _income;
// check if provided %% amount to 10,000
uint16 _sum = 0;
for (uint8 i = instantGame; i <= income; i++) {
_sum = _sum + rate[i];
}
require(_sum == 10000);
eventsCounter = eventsCounter + 1;
AllocationAdjusted(
eventsCounter,
msg.sender,
rate[instantGame],
rate[dailyJackpot],
rate[weeklyJackpot],
rate[monthlyJackpot],
rate[yearlyJackpot],
rate[income]
);
} // end of adjustAllocation
// this function calculates jackpots/income allocation and returns prize for the instant game
uint256 sumAllocatedInWeiCounter;
event SumAllocatedInWei(
uint256 indexed eventsCounter,
uint256 indexed sumAllocatedInWeiCounter,
address betOf,
uint256 bet, // 0
uint256 dailyJackpot, // 1
uint256 weeklyJackpot, // 2;
uint256 monthlyJackpot, // 3;
uint256 yearlyJackpot, // 4;
uint256 income,
uint256 affiliateRewards,
uint256 payToWinner
);
function allocateSum(uint256 _sum, address loser) private returns (uint256) {
// for event
// https://solidity.readthedocs.io/en/v0.4.24/types.html#allocating-memory-arrays
uint256[] memory jackpotsSumAllocation = new uint256[](5);
// jackpots:
for (uint8 i = dailyJackpot; i <= yearlyJackpot; i++) {
uint256 sumToAdd = _sum * rate[i] / 10000;
sum[i] = sum[i].add(sumToAdd);
// for event:
jackpotsSumAllocation[i] = sumToAdd;
}
// income before affiliate reward subtraction:
uint256 incomeSum = (_sum * rate[income]) / 10000;
// referrer reward:
uint256 refSum = 0;
if (referrer[loser] != address(0)) {
address referrerAddress = referrer[loser];
refSum = incomeSum / 2;
incomeSum = incomeSum.sub(refSum);
reward[referrerAddress] = reward[referrerAddress].add(refSum);
sum[affiliateRewards] = sum[affiliateRewards].add(refSum);
}
sum[income] = sum[income].add(incomeSum);
uint256 payToWinner = _sum * rate[instantGame] / 10000;
eventsCounter = eventsCounter + 1;
sumAllocatedInWeiCounter = sumAllocatedInWeiCounter + 1;
SumAllocatedInWei(
eventsCounter,
sumAllocatedInWeiCounter,
loser,
_sum,
jackpotsSumAllocation[1], // dailyJackpot
jackpotsSumAllocation[2], // weeklyJackpot
jackpotsSumAllocation[3], // monthlyJackpot
jackpotsSumAllocation[4], // yearlyJackpot
incomeSum,
refSum,
payToWinner
);
return payToWinner;
}
/* -------------- GAME: --------------*/
/* --- Instant Game ------- */
uint256 public instantGameCounter; // id's of the instant games
//
// to allow only one game for the given address simultaneously:
mapping(address => bool) public instantGameIsRunning;
//
mapping(address => uint256) public lastInstantGameBlockNumber; // for address
mapping(address => uint256) public lastInstantGameTicketsNumber; // for address
// first step for player is to make a bet:
uint256 public betCounter;
event BetPlaced(
uint256 indexed eventsCounter,
uint256 indexed betCounter,
address indexed player,
uint256 betInWei,
uint256 ticketsBefore,
uint256 newTickets
);
function placeABetInternal(uint value) private {
require(msg.sender != kingOfTheHill);
// only one game allowed for the address at the given moment:
require(!instantGameIsRunning[msg.sender]);
// number of new tickets to create;
uint256 newTickets = value / ticketPriceInWei;
eventsCounter = eventsCounter + 1;
betCounter = betCounter + 1;
BetPlaced(eventsCounter, betCounter, msg.sender, value, ticketsTotal, newTickets);
uint256 playerBetToPlace = newTickets.mul(ticketPriceInWei);
sum[playersBets] = sum[playersBets].add(playerBetToPlace);
require(newTickets > 0 && newTickets <= maxTicketsToBuyInOneTransaction);
uint256 newTicketsTotal = ticketsTotal.add(newTickets);
// new tickets included in jackpot games instantly:
for (uint256 i = ticketsTotal + 1; i <= newTicketsTotal; i++) {
theLotteryTicket[i] = msg.sender;
}
ticketsTotal = newTicketsTotal;
lastInstantGameTicketsNumber[msg.sender] = newTickets;
instantGameIsRunning[msg.sender] = true;
lastInstantGameBlockNumber[msg.sender] = block.number;
}
function placeABet() public payable {
placeABetInternal(msg.value);
}
mapping(address => address) public referrer;
function placeABetWithReferrer(address _referrer) public payable {
/* referrer: */
if (referrer[msg.sender] == 0x0000000000000000000000000000000000000000) {
referrer[msg.sender] = _referrer;
}
placeABetInternal(msg.value);
}
event Investment(
uint256 indexed eventsCounter, //.1
address indexed by, //............2
uint256 sum, //...................3
uint256 sumToMarketingFund, //....4
uint256 bet, //...................5
uint256 tokens //.................6
); //
function investAndPlay() public payable {
// require( luckyStrikeTokens.tokenSaleIsRunning());
// < we will check this in luckyStrikeTokens.mint method
uint256 sumToMarketingFund = msg.value / 5;
sum[marketingFund] = sum[marketingFund].add(sumToMarketingFund);
uint256 bet = msg.value.sub(sumToMarketingFund);
placeABetInternal(bet);
// uint256 tokensToMint = msg.value / ticketPriceInWei;
// uint256 tokensToMint = bet / tokenPriceInWei;
uint256 tokensToMint = sumToMarketingFund / tokenPriceInWei;
// require(bet / ticketPriceInWei > 0); // > makes more complicated
luckyStrikeTokens.mint(msg.sender, tokensToMint, sumToMarketingFund);
eventsCounter = eventsCounter + 1;
Investment(
eventsCounter, //......1
msg.sender, //.........2
msg.value, //..........3
sumToMarketingFund, //.4
bet, //................5
tokensToMint //........6
);
}
function investAndPlayWithReferrer(address _referrer) public payable {
if (referrer[msg.sender] == 0x0000000000000000000000000000000000000000) {
referrer[msg.sender] = _referrer;
}
investAndPlay();
}
/*
function invest() public payable {
// require(luckyStrikeTokens.tokenSaleIsRunning());
// < we will check this in luckyStrikeTokens.mint method
sum[marketingFund] = sum[marketingFund].add(msg.value);
uint256 tokensToMint = msg.value / ticketPriceInWei;
// uint256 bonus = (tokensToMint / 100).mul(75);
uint256 bonus1part = tokensToMint / 2;
uint256 bonus2part = tokensToMint / 4;
uint256 bonus = bonus1part.add(bonus2part);
tokensToMint = tokensToMint.add(bonus);
// require(bet / ticketPriceInWei > 0); // > makes more complicated
luckyStrikeTokens.mint(
msg.sender,
tokensToMint,
msg.value // all sum > investment
);
eventsCounter = eventsCounter + 1;
Investment(
eventsCounter, //..1
msg.sender, //.....2
msg.value, //......3
msg.value, //......4
0, //..............5 (bet)
tokensToMint //....6
);
}
function investWithReferrer(address _referrer) public payable {
if (referrer[msg.sender] == 0x0000000000000000000000000000000000000000) {
referrer[msg.sender] = _referrer;
}
invest();
}
*/
// second step in instant game:
event InstantGameResult (
uint256 indexed eventsCounter, //...0
uint256 gameId, // .................1
bool theBetPlayed, //...............2
address indexed challenger, //......3
address indexed king, //............4
uint256 kingsTicketsNumber, //......5
address winner, //..................6
uint256 prize, //...................7
uint256 ticketsInTheInstantGame, //.8
uint256 randomNumber, //............9
address triggeredBy //..............10
);
function play(address player) public {
require(instantGameIsRunning[player]);
require(lastInstantGameBlockNumber[player] < block.number);
// block number with the bet must be no more than 255 blocks before the current block
// or we get 0 as blockhash
instantGameCounter = instantGameCounter + 1;
uint256 playerBet = lastInstantGameTicketsNumber[player].mul(ticketPriceInWei);
// in any case playerBet should be subtracted sum[playerBets]
sum[playersBets] = sum[playersBets].sub(playerBet);
// TODO: recheck this >
if (block.number - lastInstantGameBlockNumber[player] > 250) {
eventsCounter = eventsCounter + 1;
InstantGameResult(
eventsCounter,
instantGameCounter,
false,
player,
address(0), // kingOfTheHill, // oldKingOfTheHill,
0,
address(0), // winner,
0, // prize,
0, // lastInstantGameTicketsNumber[player], // ticketsInTheInstantGame,
0, // randomNumber,
msg.sender // triggeredBy
);
// player.transfer(playerBet);
sum[income] = sum[income].add(playerBet);
lastInstantGameTicketsNumber[player] = 0;
instantGameIsRunning[player] = false;
return;
}
address oldKingOfTheHill = kingOfTheHill;
uint256 oldKingOfTheHillTicketsNumber = kingOfTheHillTicketsNumber;
uint256 ticketsInTheInstantGame = kingOfTheHillTicketsNumber.add(lastInstantGameTicketsNumber[player]);
// TODO: recheck this
bytes32 seed = keccak256(
block.blockhash(lastInstantGameBlockNumber[player]) // bytes32
);
uint256 seedToNumber = uint256(seed);
uint256 randomNumber = seedToNumber % ticketsInTheInstantGame;
// 0 never plays, and ticketsInTheInstantGame can not be returned by the function above
if (randomNumber == 0) {
randomNumber = ticketsInTheInstantGame;
}
uint256 prize;
address winner;
address loser;
if (randomNumber > kingOfTheHillTicketsNumber) {// challenger ('player') wins
winner = player;
loser = kingOfTheHill;
// new kingOfTheHill:
kingOfTheHill = player;
kingOfTheHillTicketsNumber = lastInstantGameTicketsNumber[player];
} else {// kingOfTheHill wins
winner = kingOfTheHill;
loser = player;
}
// prize = allocateSum(playerBet, loser, winner);
prize = allocateSum(playerBet, loser);
instantGameIsRunning[player] = false;
// pay prize to the winner
winner.transfer(prize);
eventsCounter = eventsCounter + 1;
InstantGameResult(
eventsCounter,
instantGameCounter,
true,
player,
oldKingOfTheHill,
oldKingOfTheHillTicketsNumber,
winner,
// playerBet,
prize,
ticketsInTheInstantGame,
randomNumber,
msg.sender
);
}
// convenience function;
function playMyInstantGame() public {
play(msg.sender);
}
/* ----------- Jackpots: ------------ */
function requestRandomFromOraclize() private returns (bytes32 oraclizeQueryId) {
require(msg.value >= oraclizeGetPrice());
// < to pay to oraclize
// call Oraclize
// uint N :
// number nRandomBytes between 1 and 32, which is the number of random bytes to be returned to the application.
// see: http://www.oraclize.it/papers/random_datasource-rev1.pdf
uint256 N = 32;
// number of seconds to wait before the execution takes place
uint delay = 0;
// this function internally generates the correct oraclize_query and returns its queryId
oraclizeQueryId = oraclize_newRandomDSQuery(delay, N, oraclizeCallbackGas);
// playJackpotEvent(msg.sender, msg.value, tx.gasprice, oraclizeQueryId);
return oraclizeQueryId;
}
// reminder (this defined above):
// mapping(uint8 => uint256) public period; // in seconds
// mapping(uint8 => uint256) public lastJackpotTime; // unix time
mapping(bytes32 => uint8) public jackpot;
event JackpotPlayStarted(
uint256 indexed eventsCounter,
uint8 indexed jackpotType,
address startedBy,
bytes32 oraclizeQueryId
);//
// uint8 jackpotType
function startJackpotPlay(uint8 jackpotType) public payable {
require(msg.value >= oraclizeGetPrice());
require(jackpotType >= 1 && jackpotType <= 4);
require(!jackpotPlayIsRunning[jackpotType]);
require(
// block.timestamp (uint): current block timestamp as seconds since unix epoch
block.timestamp >= lastJackpotTime[jackpotType].add(period[jackpotType])
);
bytes32 oraclizeQueryId = requestRandomFromOraclize();
jackpot[oraclizeQueryId] = jackpotType;
jackpotPlayIsRunning[jackpotType] = true;
eventsCounter = eventsCounter + 1;
JackpotPlayStarted(eventsCounter, jackpotType, msg.sender, oraclizeQueryId);
}
uint256 public allJackpotsCounter;
event JackpotResult(
uint256 indexed eventsCounter,
uint256 allJackpotsCounter,
uint8 indexed jackpotType,
uint256 jackpotIdNumber,
uint256 prize,
address indexed winner,
uint256 randomNumberSeed,
uint256 randomNumber,
uint256 ticketsTotal
);
// the callback function is called by Oraclize when the result is ready
// the oraclize_randomDS_proofVerify modifier prevents an invalid proof to execute this function code:
// the proof validity is fully verified on-chain
function __callback(bytes32 _queryId, string _result, bytes _proof) public {
require(msg.sender == oraclize_cbAddress());
if (oraclize_randomDS_proofVerify__returnCode(_queryId, _result, _proof) != 0) {
// the proof verification has failed, do we need to take any action here? (depends on the use case)
revert();
} else {
// find jackpot for this _queryId:
uint8 jackpotType = jackpot[_queryId];
require(jackpotPlayIsRunning[jackpotType]);
jackpotCounter[jackpotType] = jackpotCounter[jackpotType] + 1;
// select jackpot winner:
bytes32 hashOfTheRandomString = keccak256(_result);
uint256 randomNumberSeed = uint256(hashOfTheRandomString);
uint256 randomNumber = randomNumberSeed % ticketsTotal;
// there is no ticket # 0, and above function can not return number equivalent to 'ticketsTotal'
if (randomNumber == 0) {
randomNumber = ticketsTotal;
}
address winner = theLotteryTicket[randomNumber];
// transfer jackpot sum to the winner
winner.transfer(sum[jackpotType]);
// emit event:
eventsCounter = eventsCounter + 1;
allJackpotsCounter = allJackpotsCounter + 1;
JackpotResult(
eventsCounter,
allJackpotsCounter,
jackpotType,
jackpotCounter[jackpotType],
sum[jackpotType],
winner,
randomNumberSeed,
randomNumber,
ticketsTotal
);
// update information for this jackpot:
sum[jackpotType] = 0;
lastJackpotTime[jackpotType] = block.timestamp;
jackpotPlayIsRunning[jackpotType] = false;
}
} // end of function __callback
event DividendsSentToTokensContract(uint256 indexed eventsCounter, uint256 sum, address indexed triggeredBy);
// can be called by any address:
function payDividends() public returns (bool success){
luckyStrikeTokensContractAddress.transfer(sum[income]);
eventsCounter = eventsCounter + 1;
DividendsSentToTokensContract(eventsCounter, sum[income], msg.sender);
sum[income] = 0;
return true;
}
} | * @dev Appends a byte to the end of the buffer. Reverts if doing so would exceed the capacity of the buffer. @param buf The buffer to append to. @param data The data to append. @return The original buffer./ Memory address of the buffer data Length of existing buffer data Address = buffer address + buffer length + sizeof(buffer length) + len Update buffer length | function appendInt(buffer memory buf, uint data, uint len) internal constant returns (buffer memory) {
if (len + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, len) * 2);
}
uint mask = 256 ** len - 1;
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
let dest := add(add(bufptr, buflen), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
mstore(bufptr, add(buflen, len))
}
return buf;
}
| 2,531,137 | [
1,
15049,
279,
1160,
358,
326,
679,
434,
326,
1613,
18,
868,
31537,
309,
9957,
1427,
4102,
9943,
326,
7519,
434,
326,
1613,
18,
225,
1681,
1021,
1613,
358,
714,
358,
18,
225,
501,
1021,
501,
358,
714,
18,
327,
1021,
2282,
1613,
18,
19,
9251,
1758,
434,
326,
1613,
501,
11311,
434,
2062,
1613,
501,
5267,
273,
1613,
1758,
397,
1613,
769,
397,
13726,
12,
4106,
769,
13,
397,
562,
2315,
1613,
769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
714,
1702,
12,
4106,
3778,
1681,
16,
2254,
501,
16,
2254,
562,
13,
2713,
5381,
1135,
261,
4106,
3778,
13,
288,
203,
3639,
309,
261,
1897,
397,
1681,
18,
4385,
18,
2469,
405,
1681,
18,
16017,
13,
288,
203,
5411,
7041,
12,
4385,
16,
943,
12,
4385,
18,
16017,
16,
562,
13,
380,
576,
1769,
203,
3639,
289,
203,
203,
3639,
2254,
3066,
273,
8303,
2826,
562,
300,
404,
31,
203,
3639,
19931,
288,
203,
5411,
2231,
1681,
6723,
519,
312,
945,
12,
4385,
13,
203,
5411,
2231,
1681,
1897,
519,
312,
945,
12,
4385,
6723,
13,
203,
5411,
2231,
1570,
519,
527,
12,
1289,
12,
4385,
6723,
16,
1681,
1897,
3631,
562,
13,
203,
5411,
312,
2233,
12,
10488,
16,
578,
12,
464,
12,
81,
945,
12,
10488,
3631,
486,
12,
4455,
13,
3631,
501,
3719,
203,
5411,
312,
2233,
12,
4385,
6723,
16,
527,
12,
4385,
1897,
16,
562,
3719,
203,
3639,
289,
203,
3639,
327,
1681,
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
] |
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.6.0;
import "../interfaces/ICryptoChampions.sol";
import "../interfaces/IMinigameFactoryRegistry.sol";
import "./minigames/games/priceWars/PriceWarsFactory.sol";
import "./minigames/games/priceWars/PriceWars.sol";
import "./chainlink/VRFConsumerBase.sol";
import "./openZeppelin/AccessControl.sol";
import "./openZeppelin/ERC721.sol";
import "smartcontractkit/[email protected]/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import "OpenZeppelin/[email protected]/contracts/math/SafeMath.sol";
import "./token/ChampzToken.sol";
/// @title Crypto Champions Interface
/// @author Oozyx
/// @notice This is the crypto champions class
contract CryptoChampions is ICryptoChampions, AccessControl, ERC721, VRFConsumerBase {
using SafeMath for uint256;
using SafeMath for uint8;
/***********************************|
| Variables and Events |
|__________________________________*/
// Possible phases the contract can be in. Phase one is when users can mint elder spirits and two is when they can mint heros.
enum Phase { SETUP, ACTION }
// The current phase the contract is in.
Phase public currentPhase;
// Number of tokens minted whenever a user mints a hero
uint256 internal constant NUM_CHAMPZ_MINTED_ON_HERO_MINTED = 500 * 10**18;
// The duration of each phase in days
uint256 internal _setupPhaseDuration;
uint256 internal _actionPhaseDuration;
// The current phase start time
uint256 public currentPhaseStartTime;
// The contract roles
bytes32 internal constant ROLE_OWNER = keccak256("ROLE_OWNER");
bytes32 internal constant ROLE_ADMIN = keccak256("ROLE_ADMIN");
bytes32 internal constant ROLE_GAME_ADMIN = keccak256("ROLE_GAME_ADMIN");
// Constants used to determine fee proportions in percentage
// Usage: fee.mul(proportion).div(100)
uint8 internal constant HERO_MINT_ROYALTY_PERCENT = 25;
uint8 internal constant HERO_MINT_DEV_PERCENT = 25;
// The amount of ETH contained in the pools
uint256 public rewardsPoolAmount = 0;
uint256 public devFund = 0;
// The rewards share for every hero with the winning affinity calculated at the end of every round
uint256 internal _heroRewardsShare = 0;
// Mapping of hero id to a mapping of round to a bool of the rewards claim
mapping(uint256 => mapping(uint256 => bool)) internal _heroRewardsClaimed;
// The max amount of elders that can be minted
uint256 public constant MAX_NUMBER_OF_ELDERS = 5;
// The amount of elders minted
// This amount cannot be greater than MAX_NUMBER_OF_ELDERS
uint256 public eldersInGame = 0;
// The mapping of elder id to the elder spirit
mapping(uint256 => ElderSpirit) internal _elderSpirits;
// The amount of heros minted
uint256 public heroesMinted = 0;
// The mapping of hero id to the hero
mapping(uint256 => Hero) internal _heroes;
// The mapping of the round played to the elder spawns mapping
mapping(uint256 => mapping(uint256 => uint256)) internal _roundElderSpawns;
// The mint price for elders and heroes
uint256 public elderMintPrice;
// The current round index
uint256 public currentRound;
// The mapping of affinities (token ticker) to price feed address
mapping(string => address) internal _affinities;
// List of available affinities
string[] public affinities;
// The list of affinities that won in a round
mapping(uint256 => string) public winningAffinitiesByRound;
// The key hash used for VRF
bytes32 internal _keyHash;
// The fee in LINK for VRF
uint256 internal _fee;
// Mapping of request id to hero id
mapping(bytes32 => uint256) internal _heroRandomRequest;
// Mapping of request id to random result
mapping(bytes32 => uint256) internal _randomResultsVRF;
// The identifier for the price wars game
string internal constant PRICE_WARS_ID = "PRICE_WARS";
// The registry of minigame factories
IMinigameFactoryRegistry internal _minigameFactoryRegistry;
// Pointer to ChampzToken
ChampzToken public champzToken;
/// @notice Triggered when an elder spirit gets minted
/// @param elderId The elder id belonging to the minted elder
/// @param owner The address of the owner
event ElderSpiritMinted(uint256 elderId, address owner);
/// @notice Triggered when a hero gets minted
/// @param heroId The hero id belonging to the hero that was minted
/// @param owner The address of the owner
event HeroMinted(uint256 heroId, address owner);
/// @notice Triggered when the elder spirits have been burned
event ElderSpiritsBurned();
/***********************************|
| Constuctor |
|__________________________________*/
// Initializes a new CryptoChampions contract
constructor(
bytes32 keyhash,
address vrfCoordinator,
address linkToken,
address minigameFactoryRegistry,
ChampzToken champzTokenInstance
) public ERC721("CryptoChampz", "CHMPZ") VRFConsumerBase(vrfCoordinator, linkToken) {
// Set up administrative roles
_setRoleAdmin(ROLE_OWNER, ROLE_OWNER);
_setRoleAdmin(ROLE_ADMIN, ROLE_OWNER);
_setRoleAdmin(ROLE_GAME_ADMIN, ROLE_OWNER);
// Set up the deployer as the owner and give admin rights
_setupRole(ROLE_OWNER, msg.sender);
grantRole(ROLE_ADMIN, msg.sender);
// Set initial elder mint price
elderMintPrice = 0.271 ether;
// Set the initial round to 0
currentRound = 0;
// Set initial phase to phase one and phase start time
currentPhase = Phase.SETUP;
currentPhaseStartTime = now;
// Set VRF fields
_keyHash = keyhash;
_fee = 0.1 * 10**18; // 0.1 LINK
// Set phase durations
_setupPhaseDuration = 2 days;
_actionPhaseDuration = 2 days;
_minigameFactoryRegistry = IMinigameFactoryRegistry(minigameFactoryRegistry);
champzToken = champzTokenInstance;
}
/***********************************|
| Function Modifiers |
|__________________________________*/
modifier isValidElderSpiritId(uint256 elderId) {
require(elderId < MAX_NUMBER_OF_ELDERS); // dev: Given id is not valid.
_;
}
modifier isValidHero(uint256 heroId) {
require(heroId >= MAX_NUMBER_OF_ELDERS); // dev: Given id is not valid.
require(_heroes[heroId].valid); // dev: Hero is not valid.
_;
}
// Restrict to only price war addresses
modifier onlyGameAdmin {
require(hasRole(ROLE_GAME_ADMIN, msg.sender)); // dev: Access denied.
_;
}
// Restrict to only admins
modifier onlyAdmin {
require(hasRole(ROLE_ADMIN, msg.sender)); // dev: Access denied.
_;
}
// Restrict to the specified phase
modifier atPhase(Phase phase) {
require(currentPhase == phase); // dev: Current phase prohibits action.
_;
}
/***********************************|
| Game Management/Setup |
|__________________________________*/
/// @notice Sets the duration of the setup phase
/// @param numDays Number of days for the setup phase duration
function setSetupPhaseDuration(uint256 numDays) external onlyAdmin {
_setupPhaseDuration = numDays * 1 days;
}
/// @notice Sets the duration of the action phase
/// @param numDays Number of days for the action phase
function setActionPhaseDuration(uint256 numDays) external onlyAdmin {
_actionPhaseDuration = numDays * 1 days;
}
/// @notice Transitions to the next phase
function _transitionNextPhase() internal {
if (currentPhase == Phase.SETUP) {
// If rewards have gone unclaimed, send to address
// todo
rewardsPoolAmount = 0;
// Reset the hero rewards share
_heroRewardsShare = 0;
// todo mint all elders that have yet to be minted
// Increment the round
currentRound = currentRound.add(1);
// Set the next phase
currentPhase = Phase.ACTION;
} else if (currentPhase == Phase.ACTION) {
// Start the price game that will determine the winning affinity
_startNewPriceGame();
// Calculate hero rewards.
// Start by finding which elder had the winning affinity
uint256 i = 0;
for (; i < eldersInGame; ++i) {
if (
keccak256(bytes(_elderSpirits[i].affinity)) ==
keccak256(bytes(winningAffinitiesByRound[currentRound])) &&
getElderSpawnsAmount(currentRound, i) > 0
) {
_heroRewardsShare = rewardsPoolAmount.div(getElderSpawnsAmount(currentRound, i));
break;
}
}
// Burn the elders
_burnElders();
// Set the next phase
currentPhase = Phase.SETUP;
}
currentPhaseStartTime = now;
}
/// @notice Sets the contract's phase
/// @dev May delete function and keep only the refresh phase function
/// @param phase The phase the contract should be set to
function setPhase(Phase phase) external onlyAdmin {
currentPhase = phase;
}
/// @notice Transitions to next phase if the condition is met and rewards caller for a successful phase transition
function refreshPhase() external override {
bool phaseChanged = false;
if (
currentPhase == Phase.SETUP &&
eldersInGame == MAX_NUMBER_OF_ELDERS &&
now >= currentPhaseStartTime + _setupPhaseDuration
) {
_transitionNextPhase();
} else if (currentPhase == Phase.ACTION && now >= currentPhaseStartTime + _actionPhaseDuration) {
_transitionNextPhase();
}
if (phaseChanged) {
// todo reward msg.sender
}
}
/// @notice Sets the token uri for the given id
/// @dev Only the admin can set URIs
/// @param id The token id (either hero or elder)
/// @param uri The uri of the token id
function setTokenURI(uint256 id, string calldata uri) external override onlyAdmin {
_setTokenURI(id, uri);
}
/// @notice Creates a new token affinity
/// @dev This will be called by a priviledged address. It will allow to create new affinities. May need to add a
/// remove affinity function as well.
/// @param tokenTicker The token ticker of the affinity
/// @param feedAddress The price feed address
function createAffinity(string calldata tokenTicker, address feedAddress) external override onlyAdmin {
_affinities[tokenTicker] = feedAddress;
affinities.push(tokenTicker);
}
/// @notice Sets the elder mint price
/// @dev Can only be called by an admin address
/// @param price The new elder mint price
function setElderMintPrice(uint256 price) external override onlyAdmin {
elderMintPrice = price;
}
/***********************************|
| VRF Functions |
|__________________________________*/
/// @notice Makes a request for a random number
/// @param userProvidedSeed The seed for the random request
/// @return requestId The request id
function _getRandomNumber(uint256 userProvidedSeed) internal returns (bytes32 requestId) {
require(LINK.balanceOf(address(this)) >= _fee); // dev: Not enough LINK - fill contract with faucet
return requestRandomness(_keyHash, _fee, userProvidedSeed);
}
/// @notice Callback function used by the VRF coordinator
/// @param requestId The request id
/// @param randomness The randomness
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
_randomResultsVRF[requestId] = randomness;
_trainHero(requestId);
}
/***********************************|
| Champion Minting |
|__________________________________*/
/// @notice Mints an elder spirit
/// @dev For now only race, class, and token (affinity) are needed. This will change. The race and class ids will
/// probably be public constants defined in the crypto champions contract, this is subject to change.
/// @param raceId The race id
/// @param classId The class id
/// @param affinity The affinity of the minted hero
/// @return The elder spirit id
function mintElderSpirit(
uint8 raceId,
uint8 classId,
string calldata affinity
) external payable override atPhase(Phase.SETUP) returns (uint256) {
require(eldersInGame < MAX_NUMBER_OF_ELDERS); // dev: Max number of elders already minted.
require(msg.value >= elderMintPrice); // dev: Insufficient payment.
require(_affinities[affinity] != address(0)); // dev: Affinity does not exist.
// Generate the elderId and make sure it doesn't already exists
uint256 elderId = eldersInGame;
assert(!_exists(elderId)); // dev: Elder with id already exists.
assert(_elderSpirits[elderId].valid == false); // dev: Elder spirit with id has already been generated.
// Get the price data of affinity
int256 affinityPrice;
(, affinityPrice, , , ) = AggregatorV3Interface(_affinities[affinity]).latestRoundData();
// Create the elder spirit
ElderSpirit memory elder;
elder.valid = true;
elder.raceId = raceId;
elder.classId = classId;
elder.affinity = affinity;
elder.affinityPrice = affinityPrice;
// Mint the NFT
_safeMint(_msgSender(), elderId);
// Assign the elder id with the owner and its spirit
_elderSpirits[elderId] = elder;
// Increment elders minted
eldersInGame = eldersInGame.add(1);
// Refund if user sent too much
_refundSender(elderMintPrice);
// The entire elder minting fee goes to the dev fund
devFund = devFund.add(elderMintPrice);
emit ElderSpiritMinted(elderId, _msgSender());
return elderId;
}
/// @notice Gets the elder owner for the given elder id
/// @param elderId The elder id
/// @return The owner of the elder
function getElderOwner(uint256 elderId) public view override isValidElderSpiritId(elderId) returns (address) {
require(_exists(elderId)); // dev: Given elder id has not been minted.
return ownerOf(elderId);
}
/// @notice Mints a hero based on an elder spirit
/// @param elderId The id of the elder spirit this hero is based on
/// @return The hero id
function mintHero(uint256 elderId, string calldata heroName)
external
payable
override
isValidElderSpiritId(elderId)
atPhase(Phase.ACTION)
returns (uint256)
{
require(_elderSpirits[elderId].valid); // dev: Elder with id doesn't exists or not valid.
require(address(champzToken) != address(0)); // dev: ChampzToken not yet initialized
require(_canMintHero(elderId)); // dev: Can't mint hero. Too mnay heroes minted for elder.
uint256 mintPrice = getHeroMintPrice(currentRound, elderId);
require(msg.value >= mintPrice); // dev: Insufficient payment.
// Generate the hero id
uint256 heroId = heroesMinted + MAX_NUMBER_OF_ELDERS;
assert(!_exists(heroId)); // dev: Hero with id already has an owner.
assert(_heroes[heroId].valid == false); // dev: Hero with id has already been generated.
// Create the hero
Hero memory hero;
hero.valid = true;
hero.name = heroName;
hero.roundMinted = currentRound;
hero.elderId = elderId;
hero.raceId = _elderSpirits[elderId].raceId;
hero.classId = _elderSpirits[elderId].classId;
hero.affinity = _elderSpirits[elderId].affinity;
_heroes[heroId] = hero;
// Request the random number and set hero attributes
bytes32 requestId = _getRandomNumber(heroId);
_heroRandomRequest[requestId] = heroId;
// Mint the NFT
_safeMint(_msgSender(), heroId);
// Mint in game currency tokens
champzToken.mintTokens(_msgSender(), NUM_CHAMPZ_MINTED_ON_HERO_MINTED);
// Increment the heroes minted and the elder spawns
heroesMinted = heroesMinted.add(1);
_roundElderSpawns[currentRound][elderId] = _roundElderSpawns[currentRound][elderId].add(1);
// Disburse royalties
uint256 royaltyFee = mintPrice.mul(HERO_MINT_ROYALTY_PERCENT).div(100);
address seedOwner = ownerOf(elderId);
(bool success, ) = seedOwner.call{ value: royaltyFee }("");
require(success, "Payment failed");
// Update the rewards and dev fund pools
uint256 devFee = mintPrice.mul(HERO_MINT_DEV_PERCENT).div(100);
devFund = devFund.add(devFee);
rewardsPoolAmount = rewardsPoolAmount.add(mintPrice.sub(royaltyFee).sub(devFee));
// Refund if user sent too much
_refundSender(mintPrice);
emit HeroMinted(heroId, _msgSender());
return heroId;
}
/// TODO: DELETE and maybe override ownerOf()
/// @notice Get the hero owner for the given hero id
/// @param heroId The hero id
/// @return The owner address
function getHeroOwner(uint256 heroId) public view override isValidHero(heroId) returns (address) {
require(_exists(heroId)); // dev: Given hero id has not been minted.
return ownerOf(heroId);
}
/// @notice Checks to see if a hero can be minted for a given elder
/// @dev (n < 4) || (n <= 2 * m)
/// n is number of champions already minted for elder
/// m is number of champions already minted for elder with least amount of champions
/// @param elderId The elder id
/// @return True if hero can be minted, false otherwise
function _canMintHero(uint256 elderId) internal view returns (bool) {
// Verify first condition
if (_roundElderSpawns[currentRound][elderId] < 4) {
return true;
}
// Find the elder with the least amount of heroes minted
uint256 smallestElderAmount = _roundElderSpawns[currentRound][elderId];
for (uint256 i = 0; i < eldersInGame; ++i) {
if (_roundElderSpawns[currentRound][i] < smallestElderAmount) {
smallestElderAmount = _roundElderSpawns[currentRound][i];
}
}
return _roundElderSpawns[currentRound][elderId] <= smallestElderAmount.mul(2);
}
/// @notice Sets the hero attributes
/// @param requestId The request id that is mapped to a hero
function _trainHero(bytes32 requestId) internal isValidHero(_heroRandomRequest[requestId]) {
uint256 heroId = _heroRandomRequest[requestId];
uint256 randomNumber = _randomResultsVRF[requestId];
uint256 newRandomNumber;
_heroes[heroId].level = 1; // 1 by default
(_heroes[heroId].appearance, newRandomNumber) = _rollDice(2, randomNumber); // 1 out of 2
(_heroes[heroId].trait1, newRandomNumber) = _rollDice(4, newRandomNumber); // 1 out of 4
(_heroes[heroId].trait2, newRandomNumber) = _rollDice(4, newRandomNumber); // 1 out of 4
(_heroes[heroId].skill1, newRandomNumber) = _rollDice(4, newRandomNumber); // 1 out of 4
(_heroes[heroId].skill2, newRandomNumber) = _rollDice(4, newRandomNumber); // 1 out of 4
(_heroes[heroId].alignment, newRandomNumber) = _rollDice(9, newRandomNumber); // 1 out of 9
(_heroes[heroId].background, newRandomNumber) = _rollDice(30, newRandomNumber); // 1 out of 30
(_heroes[heroId].hometown, newRandomNumber) = _rollDice(24, newRandomNumber); // 1 out of 24
(_heroes[heroId].weather, newRandomNumber) = _rollDice(7, newRandomNumber); // 1 ouf of 7
(_heroes[heroId].hp, newRandomNumber) = _rollDice(_getHpRoll(_heroes[heroId].classId), newRandomNumber); // Roll 10-30
_heroes[heroId].hp = uint8(_heroes[heroId].hp.add(9));
(_heroes[heroId].mana, newRandomNumber) = _rollDice(_getManaRoll(_heroes[heroId].classId), newRandomNumber); // Roll 10-30
_heroes[heroId].mana = uint8(_heroes[heroId].mana.add(9));
(_heroes[heroId].stamina, newRandomNumber) = _rollDice(31, newRandomNumber); // Roll 10-40
_heroes[heroId].stamina = uint8(_heroes[heroId].stamina.add(9));
(_heroes[heroId].strength, newRandomNumber) = _rollDice(16, newRandomNumber); // Roll 3-18
_heroes[heroId].strength = uint8(_heroes[heroId].strength.add(2));
(_heroes[heroId].dexterity, newRandomNumber) = _rollDice(16, newRandomNumber); // Roll 3-18
_heroes[heroId].dexterity = uint8(_heroes[heroId].dexterity.add(2));
(_heroes[heroId].constitution, newRandomNumber) = _rollDice(16, newRandomNumber); // Roll 3-18
_heroes[heroId].constitution = uint8(_heroes[heroId].constitution.add(2));
(_heroes[heroId].intelligence, newRandomNumber) = _rollDice(16, newRandomNumber); // Roll 3-18
_heroes[heroId].intelligence = uint8(_heroes[heroId].intelligence.add(2));
(_heroes[heroId].wisdom, newRandomNumber) = _rollDice(16, newRandomNumber); // Roll 3-18
_heroes[heroId].wisdom = uint8(_heroes[heroId].wisdom.add(2));
(_heroes[heroId].charisma, newRandomNumber) = _rollDice(16, newRandomNumber); // Roll 3-18
_heroes[heroId].charisma = uint8(_heroes[heroId].charisma.add(2));
}
/// @notice Gets the roll value for the hp attribute of a hero
/// @param class The hero's class id
/// @return The roll value for hp
function _getHpRoll(uint8 class) internal pure returns (uint8) {
// Warrior
if (class == 0) {
return 41;
}
// Mage, Necromancer, Priest
else if (class == 1 || class == 5 || class == 6) {
return 21;
}
// Druid, Paladin, Bard, Rogue
else {
return 31;
}
}
/// @notice Gets the roll value for the mana attribute of a hero
/// @param class The hero's class id
/// @return The roll value for mana
function _getManaRoll(uint8 class) internal pure returns (uint8) {
// Warrior
if (class == 0) {
return 21;
}
// Mage, Necromancer, Priest
else if (class == 1 || class == 5 || class == 6) {
return 41;
}
// Druid, Paladin, Bard, Rogue
else {
return 31;
}
}
/// @notice Simulates rolling dice
/// @param maxNumber The max number of the dice (e.g. regular die is 6)
/// @param randomNumber The random number
/// @return The result of the dice roll and a new random number to use for another dice roll
function _rollDice(uint8 maxNumber, uint256 randomNumber) internal pure returns (uint8, uint256) {
return (uint8(randomNumber.mod(maxNumber).add(1)), randomNumber.div(10));
}
/// @notice Burns all the elder spirits in game
function _burnElders() internal {
for (uint256 i = 0; i < MAX_NUMBER_OF_ELDERS; ++i) {
if (_elderSpirits[i].valid) {
_burnElder(i);
}
}
emit ElderSpiritsBurned();
}
/// @notice Burns the elder spirit
/// @dev This will only be able to be called by the contract
/// @param elderId The elder id
function _burnElder(uint256 elderId) internal isValidElderSpiritId(elderId) {
require(_elderSpirits[elderId].valid); // dev: Cannot burn elder that does not exist.
_burn(elderId);
// Reset elder values for elder id
eldersInGame = eldersInGame.sub(1);
_elderSpirits[elderId].valid = false;
}
/// @notice Gets the minting price of a hero based on specified elder spirit
/// @param round The round of the hero to be minted
/// @param elderId The elder id for which the hero will be based on
/// @return The hero mint price
function getHeroMintPrice(uint256 round, uint256 elderId)
public
view
override
isValidElderSpiritId(elderId)
returns (uint256)
{
require(round <= currentRound); // dev: Cannot get price round has not started.
uint256 heroAmount = _roundElderSpawns[round][elderId].add(1);
return _priceFormula(heroAmount);
}
/// @notice The bounding curve function that calculates price for the new supply
/// @dev price = 0.02*(heroes minted) + 0.1
/// @param newSupply The new supply after a burn or mint
/// @return The calculated price
function _priceFormula(uint256 newSupply) internal pure returns (uint256) {
uint256 price;
uint256 base = 1;
price = newSupply.mul(10**18).mul(2).div(100);
price = price.add(base.mul(10**18).div(10));
return price;
}
/// @notice Refunds the sender if they sent too much
/// @param cost The cost
function _refundSender(uint256 cost) internal {
if (msg.value.sub(cost) > 0) {
(bool success, ) = msg.sender.call{ value: msg.value.sub(cost) }("");
require(success); // dev: Refund failed.
}
}
/***********************************|
| Getter Functions |
|__________________________________*/
/// @notice Gets the amount of heroes spawn from the elder with the specified id during the specified round
/// @param round The round the elder was created
/// @param elderId The elder id
/// @return The amount of heroes spawned from the elder
function getElderSpawnsAmount(uint256 round, uint256 elderId)
public
view
override
isValidElderSpiritId(elderId)
returns (uint256)
{
require(round <= currentRound); // dev: Invalid round.
return _roundElderSpawns[round][elderId];
}
/// @notice Fetches the data of a single elder spirit
/// @param elderId The id of the elder being searched for
/// @return The elder's attributes in the following order (valid, raceId, classId, affinity)
function getElderSpirit(uint256 elderId)
external
view
override
isValidElderSpiritId(elderId)
returns (
bool,
uint8,
uint8,
string memory,
int256
)
{
ElderSpirit memory elderSpirit = _elderSpirits[elderId];
return (
elderSpirit.valid,
elderSpirit.raceId,
elderSpirit.classId,
elderSpirit.affinity,
elderSpirit.affinityPrice
);
}
/// @notice Hero getter function
/// @param heroId The hero id
/// @return valid, affinity, affinity price, round minted, elder id
function getHeroGameData(uint256 heroId)
external
view
override
isValidHero(heroId)
returns (
bool, // valid
string memory, // affinity
int256, // affinity price
uint256, // round minted
uint256 // elder id
)
{
return (
_heroes[heroId].valid,
_heroes[heroId].affinity,
_heroes[heroId].affinityPrice,
_heroes[heroId].roundMinted,
_heroes[heroId].elderId
);
}
/// @notice Hero getter function
/// @param heroId The hero id
/// @return name, race id, class id, appearance
function getHeroVisuals(uint256 heroId)
external
view
override
isValidHero(heroId)
returns (
string memory, // name
uint8, // race id
uint8, // class id
uint8 // appearance
)
{
return (_heroes[heroId].name, _heroes[heroId].raceId, _heroes[heroId].classId, _heroes[heroId].appearance);
}
/// @notice Hero getter function
/// @param heroId The hero id
/// @return trait 1, trait 2, skill 1, skill 2
function getHeroTraitsSkills(uint256 heroId)
external
view
override
isValidHero(heroId)
returns (
uint8, // trait 1
uint8, // trait 2
uint8, // skill 1
uint8 // skill 2
)
{
return (_heroes[heroId].trait1, _heroes[heroId].trait2, _heroes[heroId].skill1, _heroes[heroId].skill2);
}
/// @notice Hero getter function
/// @param heroId The hero id
/// @return alignment, background, hometown, weather
function getHeroLore(uint256 heroId)
external
view
override
isValidHero(heroId)
returns (
uint8, // alignment
uint8, // background
uint8, // hometown
uint8 // weather
)
{
return (
_heroes[heroId].alignment,
_heroes[heroId].background,
_heroes[heroId].hometown,
_heroes[heroId].weather
);
}
/// @notice Hero getter function
/// @param heroId The hero id
/// @return level, hp, mana
function getHeroVitals(uint256 heroId)
external
view
override
isValidHero(heroId)
returns (
uint8, // level
uint8, // hp
uint8, // mana
uint8 // stamina
)
{
return (_heroes[heroId].level, _heroes[heroId].hp, _heroes[heroId].mana, _heroes[heroId].stamina);
}
/// @notice Hero getter function
/// @param heroId The hero id
/// @return stamina, strength, dexterity, constitution, intelligence, wisdom, charisma
function getHeroStats(uint256 heroId)
external
view
override
isValidHero(heroId)
returns (
uint8, // strength
uint8, // dexterity
uint8, // constitution
uint8, // intelligence
uint8, // wisdom
uint8 // charisma
)
{
return (
_heroes[heroId].strength,
_heroes[heroId].dexterity,
_heroes[heroId].constitution,
_heroes[heroId].intelligence,
_heroes[heroId].wisdom,
_heroes[heroId].charisma
);
}
/// @notice Fetches the feed address for a given affinity
/// @param affinity The affinity being searched for
/// @return The address of the affinity's feed address
function getAffinityFeedAddress(string calldata affinity) external view override returns (address) {
return _affinities[affinity];
}
/// @notice Fetches the number of elders currently in the game
/// @return The current number of elders in the game
function getNumEldersInGame() external view override returns (uint256) {
return eldersInGame;
}
/***********************************|
| Price Game |
|__________________________________*/
/// @notice Declares a winning affinity for a round
/// @dev This can only be called by a game admin contract
/// @param winningAffinity The affinity that won the game
function declareRoundWinner(string calldata winningAffinity) external override atPhase(Phase.ACTION) onlyGameAdmin {
winningAffinitiesByRound[currentRound] = winningAffinity;
}
/// @notice Claims the rewards for the hero if eligible
/// @dev Can only claim once and only for the round the hero was minted
/// @param heroId The hero id
function claimReward(uint256 heroId) external override atPhase(Phase.SETUP) isValidHero(heroId) {
// Check if hero is eligible and if hero hasn't already claimed
require(_heroes[heroId].roundMinted == currentRound); // dev: Hero was not minted this round.
require(keccak256(bytes(_heroes[heroId].affinity)) == keccak256(bytes(winningAffinitiesByRound[currentRound]))); // dev: Hero does not have the winning affinity.
require(_heroRewardsClaimed[heroId][currentRound] == false); // dev: Reward has already been claimed.
(bool success, ) = ownerOf(heroId).call{ value: _heroRewardsShare }("");
require(success, "Payment failed");
rewardsPoolAmount = rewardsPoolAmount.sub(_heroRewardsShare);
_heroRewardsClaimed[heroId][currentRound] = true;
}
/// @notice Starts a new price game
/// @dev This can only be called by the admin of the contract
function _startNewPriceGame() internal {
address priceWarsFactoryAddress = _minigameFactoryRegistry.getFactory(PRICE_WARS_ID);
PriceWarsFactory priceWarsFactory = PriceWarsFactory(priceWarsFactoryAddress);
PriceWars priceWar = priceWarsFactory.createPriceWar(address(this));
grantRole(ROLE_GAME_ADMIN, address(priceWar));
priceWar.startGame();
}
/// @notice Transfers in game currency tokens from one address to another
/// @param to The receiving address
/// @param amount The amount to transfer
function transferInGameTokens(address to, uint256 amount) external override {
// TODO: make it work with ERC20
// bytes memory data;
// safeTransferFrom(msg.sender, to, IN_GAME_CURRENCY_ID, amount, data);
}
/// @notice Transfers in game currency tokens from one address to another.
/// @param from The sending address. Note that the sender must be authorized to transfer funds if the sender is different from the from address.
/// @param to The receiving address
/// @param amount The amount to transfer
function delegatedTransferInGameTokens(
address from,
address to,
uint256 amount
) external override {
// TODO: make it work with ERC20
// bytes memory data;
// safeTransferFrom(from, to, IN_GAME_CURRENCY_ID, amount, data);
}
/// @notice Returns whether or not hero has reward for the round
/// @param heroId The id of the hero being searched for
function hasRoundReward(uint256 heroId) external view returns (bool) {
Hero memory hero = _heroes[heroId];
string memory roundWinningAffinity = winningAffinitiesByRound[currentRound];
return
!_heroRewardsClaimed[heroId][currentRound] &&
keccak256(bytes(hero.affinity)) == keccak256(bytes(roundWinningAffinity)) &&
hero.roundMinted == currentRound;
}
}
| @notice Sets the duration of the setup phase @param numDays Number of days for the setup phase duration | function setSetupPhaseDuration(uint256 numDays) external onlyAdmin {
_setupPhaseDuration = numDays * 1 days;
}
| 6,458,075 | [
1,
2785,
326,
3734,
434,
326,
3875,
6855,
225,
818,
9384,
3588,
434,
4681,
364,
326,
3875,
6855,
3734,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
444,
7365,
11406,
5326,
12,
11890,
5034,
818,
9384,
13,
3903,
1338,
4446,
288,
203,
3639,
389,
8401,
11406,
5326,
273,
818,
9384,
380,
404,
4681,
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
] |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./interfaces/IERC20Decimals.sol";
import "./balancer-core-v2/lib/math/LogExpMath.sol";
import "./balancer-core-v2/lib/math/FixedPoint.sol";
import "./balancer-core-v2/vault/interfaces/IMinimalSwapInfoPool.sol";
import "./balancer-core-v2/vault/interfaces/IVault.sol";
import "./balancer-core-v2/pools/BalancerPoolToken.sol";
// SECURITY - A governance address can freeze trading and deposits but has no access to user funds
// and cannot stop withdraws.
contract ConvergentCurvePool is IMinimalSwapInfoPool, BalancerPoolToken {
using LogExpMath for uint256;
using FixedPoint for uint256;
// The token we expect to stay constant in value
IERC20 public immutable underlying;
uint8 public immutable underlyingDecimals;
// The token we expect to appreciate to match underlying
IERC20 public immutable bond;
uint8 public immutable bondDecimals;
// The expiration time
uint256 public immutable expiration;
// The number of seconds in our timescale
uint256 public immutable unitSeconds;
// The Balancer pool data
// Note we change style to match Balancer's custom getter
IVault private immutable _vault;
bytes32 private immutable _poolId;
// The fees recorded during swaps, this is the total fees collected by LPs on all trades.
// These will be 18 point not token decimal encoded
uint120 public feesUnderlying;
uint120 public feesBond;
// A bool to indicate if the contract is paused, stored with 'fees bond'
bool public paused;
// The fees which have been allocated to pay governance, a percent of LP fees on trades
// Since we don't have access to transfer they must be stored so governance can collect them later
uint128 public governanceFeesUnderlying;
uint128 public governanceFeesBond;
// A mapping of who can pause
mapping(address => bool) public pausers;
// Stored records of governance tokens
address public immutable governance;
// The percent of each trade's implied yield to collect as LP fee
uint256 public immutable percentFee;
// The percent of LP fees that is payed to governance
uint256 public immutable percentFeeGov;
// Store constant token indexes for ascending sorted order
// In this case despite these being internal it's cleaner
// to ignore linting rules that require _
/* solhint-disable private-vars-leading-underscore */
uint256 internal immutable baseIndex;
uint256 internal immutable bondIndex;
/* solhint-enable private-vars-leading-underscore */
// The max percent fee for governance, immutable after compilation
uint256 public constant FEE_BOUND = 3e17;
// State saying if the contract is paused
/// @notice This event allows the frontend to track the fees
/// @param collectedBase the base asset tokens fees collected in this txn
/// @param collectedBond the bond asset tokens fees collected in this txn
/// @param remainingBase the amount of base asset fees have been charged but not collected
/// @param remainingBond the amount of bond asset fees have been charged but not collected
/// @dev All values emitted by this event are 18 point fixed not token native decimals
event FeeCollection(
uint256 collectedBase,
uint256 collectedBond,
uint256 remainingBase,
uint256 remainingBond
);
/// @dev We need need to set the immutables on contract creation
/// Note - We expect both 'bond' and 'underlying' to have 'decimals()'
/// @param _underlying The asset which the second asset should appreciate to match
/// @param _bond The asset which should be appreciating
/// @param _expiration The time in unix seconds when the bond asset should equal the underlying asset
/// @param _unitSeconds The number of seconds in a unit of time, for example 1 year in seconds
/// @param vault The balancer vault
/// @param _percentFee The percent each trade's yield to collect as fees
/// @param _percentFeeGov The percent of collected that go to governance
/// @param _governance The address which gets minted reward lp
/// @param name The balancer pool token name
/// @param symbol The balancer pool token symbol
/// @param _pauser An address that can pause trades and deposits
constructor(
IERC20 _underlying,
IERC20 _bond,
uint256 _expiration,
uint256 _unitSeconds,
IVault vault,
uint256 _percentFee,
uint256 _percentFeeGov,
address _governance,
string memory name,
string memory symbol,
address _pauser
) BalancerPoolToken(name, symbol) {
// Sanity Check
require(_expiration - block.timestamp < _unitSeconds);
// Initialization on the vault
bytes32 poolId = vault.registerPool(
IVault.PoolSpecialization.TWO_TOKEN
);
IERC20[] memory tokens = new IERC20[](2);
if (_underlying < _bond) {
tokens[0] = _underlying;
tokens[1] = _bond;
} else {
tokens[0] = _bond;
tokens[1] = _underlying;
}
// Set that the _pauser can pause
pausers[_pauser] = true;
// Pass in zero addresses for Asset Managers
// Note - functions below assume this token order
vault.registerTokens(poolId, tokens, new address[](2));
// Set immutable state variables
_vault = vault;
_poolId = poolId;
percentFee = _percentFee;
// We check that the gov percent fee is less than bound
require(_percentFeeGov < FEE_BOUND, "Fee too high");
percentFeeGov = _percentFeeGov;
underlying = _underlying;
underlyingDecimals = IERC20Decimals(address(_underlying)).decimals();
bond = _bond;
bondDecimals = IERC20Decimals(address(_bond)).decimals();
expiration = _expiration;
unitSeconds = _unitSeconds;
governance = _governance;
// Calculate the preset indexes for ordering
bool underlyingFirst = _underlying < _bond;
baseIndex = underlyingFirst ? 0 : 1;
bondIndex = underlyingFirst ? 1 : 0;
}
// Balancer Interface required Getters
/// @dev Returns the vault for this pool
/// @return The vault for this pool
function getVault() external view returns (IVault) {
return _vault;
}
/// @dev Returns the poolId for this pool
/// @return The poolId for this pool
function getPoolId() external view returns (bytes32) {
return _poolId;
}
// Trade Functionality
/// @dev Called by the Vault on swaps to get a price quote
/// @param swapRequest The request which contains the details of the swap
/// @param currentBalanceTokenIn The input token balance
/// @param currentBalanceTokenOut The output token balance
/// @return the amount of the output or input token amount of for swap
function onSwap(
SwapRequest memory swapRequest,
uint256 currentBalanceTokenIn,
uint256 currentBalanceTokenOut
) public override notPaused returns (uint256) {
// Check that the sender is pool, we change state so must make
// this check.
require(msg.sender == address(_vault), "Non Vault caller");
// Tokens amounts are passed to us in decimal form of the tokens
// But we want theme in 18 point
uint256 amount;
bool isOutputSwap = swapRequest.kind == IVault.SwapKind.GIVEN_IN;
if (isOutputSwap) {
amount = _tokenToFixed(swapRequest.amount, swapRequest.tokenIn);
} else {
amount = _tokenToFixed(swapRequest.amount, swapRequest.tokenOut);
}
currentBalanceTokenIn = _tokenToFixed(
currentBalanceTokenIn,
swapRequest.tokenIn
);
currentBalanceTokenOut = _tokenToFixed(
currentBalanceTokenOut,
swapRequest.tokenOut
);
// We apply the trick which is used in the paper and
// double count the reserves because the curve provisions liquidity
// for prices above one underlying per bond, which we don't want to be accessible
(uint256 tokenInReserve, uint256 tokenOutReserve) = _adjustedReserve(
currentBalanceTokenIn,
swapRequest.tokenIn,
currentBalanceTokenOut,
swapRequest.tokenOut
);
// We switch on if this is an input or output case
if (isOutputSwap) {
// We get quote
uint256 quote = solveTradeInvariant(
amount,
tokenInReserve,
tokenOutReserve,
isOutputSwap
);
// We assign the trade fee
quote = _assignTradeFee(amount, quote, swapRequest.tokenOut, false);
// We return the quote
return _fixedToToken(quote, swapRequest.tokenOut);
} else {
// We get the quote
uint256 quote = solveTradeInvariant(
amount,
tokenOutReserve,
tokenInReserve,
isOutputSwap
);
// We assign the trade fee
quote = _assignTradeFee(quote, amount, swapRequest.tokenOut, true);
// We return the output
return _fixedToToken(quote, swapRequest.tokenIn);
}
}
/// @dev Hook for joining the pool that must be called from the vault.
/// It mints a proportional number of tokens compared to current LP pool,
/// based on the maximum input the user indicates.
/// @param poolId The balancer pool id, checked to ensure non erroneous vault call
// @param sender Unused by this pool but in interface
/// @param recipient The address which will receive lp tokens.
/// @param currentBalances The current pool balances, sorted by address low to high. length 2
// @param latestBlockNumberUsed last block number unused in this pool
/// @param protocolSwapFee no fee is collected on join only when they are paid to governance
/// @param userData Abi encoded fixed length 2 array containing max inputs also sorted by
/// address low to high
/// @return amountsIn The actual amounts of token the vault should move to this pool
/// @return dueProtocolFeeAmounts The amounts of each token to pay as protocol fees
function onJoinPool(
bytes32 poolId,
address, // sender
address recipient,
uint256[] memory currentBalances,
uint256,
uint256 protocolSwapFee,
bytes calldata userData
)
external
override
notPaused
returns (
uint256[] memory amountsIn,
uint256[] memory dueProtocolFeeAmounts
)
{
// Default checks
require(msg.sender == address(_vault), "Non Vault caller");
require(poolId == _poolId, "Wrong pool id");
uint256[] memory maxAmountsIn = abi.decode(userData, (uint256[]));
require(
currentBalances.length == 2 && maxAmountsIn.length == 2,
"Invalid format"
);
require(
recipient != governance,
"Governance address LP would be locked"
);
// We must normalize the inputs to 18 point
_normalizeSortedArray(currentBalances);
_normalizeSortedArray(maxAmountsIn);
// This (1) removes governance fees and balancer fees which are collected but not paid
// from the current balances (2) adds any to be collected gov fees to state (3) calculates
// the fees to be paid to balancer on this call.
dueProtocolFeeAmounts = _feeAccounting(
currentBalances,
protocolSwapFee
);
// Mint for the user
amountsIn = _mintLP(
maxAmountsIn[baseIndex],
maxAmountsIn[bondIndex],
currentBalances,
recipient
);
// We now have make the outputs have the correct decimals
_denormalizeSortedArray(amountsIn);
_denormalizeSortedArray(dueProtocolFeeAmounts);
}
/// @dev Hook for leaving the pool that must be called from the vault.
/// It burns a proportional number of tokens compared to current LP pool,
/// based on the minium output the user wants.
/// @param poolId The balancer pool id, checked to ensure non erroneous vault call
/// @param sender The address which is the source of the LP token
// @param recipient Unused by this pool but in interface
/// @param currentBalances The current pool balances, sorted by address low to high. length 2
// @param latestBlockNumberUsed last block number unused in this pool
/// @param protocolSwapFee The percent of pool fees to be paid to the Balancer Protocol
/// @param userData Abi encoded uint256 which is the number of LP tokens the user wants to
/// withdraw
/// @return amountsOut The number of each token to send to the caller
/// @return dueProtocolFeeAmounts The amounts of each token to pay as protocol fees
function onExitPool(
bytes32 poolId,
address sender,
address,
uint256[] memory currentBalances,
uint256,
uint256 protocolSwapFee,
bytes calldata userData
)
external
override
returns (
uint256[] memory amountsOut,
uint256[] memory dueProtocolFeeAmounts
)
{
// Default checks
require(msg.sender == address(_vault), "Non Vault caller");
require(poolId == _poolId, "Wrong pool id");
uint256 lpOut = abi.decode(userData, (uint256));
// We have to convert to 18 decimals
_normalizeSortedArray(currentBalances);
// This (1) removes governance fees and balancer fees which are collected but not paid
// from the current balances (2) adds any to be collected gov fees to state (3) calculates
// the fees to be paid to balancer on this call.
dueProtocolFeeAmounts = _feeAccounting(
currentBalances,
protocolSwapFee
);
// If governance is withdrawing they can get all of the fees
if (sender == governance) {
// Init the array
amountsOut = new uint256[](2);
// Governance withdraws the fees which have been paid to them
amountsOut[baseIndex] = uint256(governanceFeesUnderlying);
amountsOut[bondIndex] = uint256(governanceFeesBond);
// We now have to zero the governance fees
governanceFeesUnderlying = 0;
governanceFeesBond = 0;
} else {
// Calculate the user's proportion of the reserves
amountsOut = _burnLP(lpOut, currentBalances, sender);
}
// We need to convert the balancer outputs to token decimals instead of 18
_denormalizeSortedArray(amountsOut);
_denormalizeSortedArray(dueProtocolFeeAmounts);
return (amountsOut, dueProtocolFeeAmounts);
}
/// @dev Returns the balances so that they'll be in the order [underlying, bond].
/// @param currentBalances balances sorted low to high of address value.
function _getSortedBalances(uint256[] memory currentBalances)
internal
view
returns (uint256 underlyingBalance, uint256 bondBalance)
{
return (currentBalances[baseIndex], currentBalances[bondIndex]);
}
/// @dev Turns an array of token amounts into an array of 18 point amounts
/// @param data The data to normalize
function _normalizeSortedArray(uint256[] memory data) internal view {
data[baseIndex] = _normalize(data[baseIndex], underlyingDecimals, 18);
data[bondIndex] = _normalize(data[bondIndex], bondDecimals, 18);
}
/// @dev Turns an array of 18 point amounts into token amounts
/// @param data The data to turn in to token decimals
function _denormalizeSortedArray(uint256[] memory data) internal view {
data[baseIndex] = _normalize(data[baseIndex], 18, underlyingDecimals);
data[bondIndex] = _normalize(data[bondIndex], 18, bondDecimals);
}
// Permission-ed functions
/// @notice checks for a pause on trading and depositing functionality
modifier notPaused() {
require(!paused, "Paused");
_;
}
/// @notice Allows an authorized address or the owner to pause this contract
/// @param pauseStatus true for paused, false for not paused
/// @dev the caller must be authorized
function pause(bool pauseStatus) external {
require(pausers[msg.sender], "Sender not Authorized");
paused = pauseStatus;
}
/// @notice Governance sets someone's pause status
/// @param who The address
/// @param status true for able to pause false for not
function setPauser(address who, bool status) external {
require(msg.sender == governance, "Sender not Owner");
pausers[who] = status;
}
// Math libraries and internal routing
/// @dev Calculates how many tokens should be outputted given an input plus reserve variables
/// Assumes all inputs are in 18 point fixed compatible with the balancer fixed math lib.
/// Since solving for an input is almost exactly the same as an output you can indicate
/// if this is an input or output calculation in the call.
/// @param amountX The amount of token x sent in normalized to have 18 decimals
/// @param reserveX The amount of the token x currently held by the pool normalized to 18 decimals
/// @param reserveY The amount of the token y currently held by the pool normalized to 18 decimals
/// @param out Is true if the pool will receive amountX and false if it is expected to produce it.
/// @return Either if 'out' is true the amount of Y token to send to the user or
/// if 'out' is false the amount of Y Token to take from the user
function solveTradeInvariant(
uint256 amountX,
uint256 reserveX,
uint256 reserveY,
bool out
) public view returns (uint256) {
// Gets 1 - t
uint256 a = _getYieldExponent();
// calculate x before ^ a
uint256 xBeforePowA = LogExpMath.pow(reserveX, a);
// calculate y before ^ a
uint256 yBeforePowA = LogExpMath.pow(reserveY, a);
// calculate x after ^ a
uint256 xAfterPowA = out
? LogExpMath.pow(reserveX + amountX, a)
: LogExpMath.pow(reserveX.sub(amountX), a);
// Calculate y_after = ( x_before ^a + y_ before ^a - x_after^a)^(1/a)
// Will revert with underflow here if the liquidity isn't enough for the trade
uint256 yAfter = (xBeforePowA + yBeforePowA).sub(xAfterPowA);
// Note that this call is to FixedPoint Div so works as intended
yAfter = LogExpMath.pow(yAfter, uint256(FixedPoint.ONE).divDown(a));
// The amount of Y token to send is (reserveY_before - reserveY_after)
return out ? reserveY.sub(yAfter) : yAfter.sub(reserveY);
}
/// @dev Adds a fee equal to to 'feePercent' of remaining interest to each trade
/// This function accepts both input and output trades, amd expects that all
/// inputs are in fixed 18 point
/// @param amountIn The trade's amountIn in fixed 18 point
/// @param amountOut The trade's amountOut in fixed 18 point
/// @param outputToken The output token
/// @param isInputTrade True if the trader is requesting a quote for the amount of input
/// they need to provide to get 'amountOut' false otherwise
/// @return The updated output quote
// Note - The safe math in this function implicitly prevents the price of 'bond' in underlying
// from being higher than 1.
function _assignTradeFee(
uint256 amountIn,
uint256 amountOut,
IERC20 outputToken,
bool isInputTrade
) internal returns (uint256) {
// The math splits on if this is input or output
if (isInputTrade) {
// Then it splits again on which token is the bond
if (outputToken == bond) {
// If the output is bond the implied yield is out - in
uint256 impliedYieldFee = percentFee.mulDown(
amountOut.sub(amountIn)
);
// we record that fee collected from the underlying
feesUnderlying += uint120(impliedYieldFee);
// and return the adjusted input quote
return amountIn.add(impliedYieldFee);
} else {
// If the input token is bond the implied yield is in - out
uint256 impliedYieldFee = percentFee.mulDown(
amountIn.sub(amountOut)
);
// we record that collected fee from the input bond
feesBond += uint120(impliedYieldFee);
// and return the updated input quote
return amountIn.add(impliedYieldFee);
}
} else {
if (outputToken == bond) {
// If the output is bond the implied yield is out - in
uint256 impliedYieldFee = percentFee.mulDown(
amountOut.sub(amountIn)
);
// we record that fee collected from the bond output
feesBond += uint120(impliedYieldFee);
// and then return the updated output
return amountOut.sub(impliedYieldFee);
} else {
// If the output is underlying the implied yield is in - out
uint256 impliedYieldFee = percentFee.mulDown(
amountIn.sub(amountOut)
);
// we record the collected underlying fee
feesUnderlying += uint120(impliedYieldFee);
// and then return the updated output quote
return amountOut.sub(impliedYieldFee);
}
}
}
/// @dev Mints the maximum possible LP given a set of max inputs
/// @param inputUnderlying The max underlying to deposit
/// @param inputBond The max bond to deposit
/// @param currentBalances The current pool balances, sorted by address low to high. length 2
/// @param recipient The person who receives the lp funds
/// @return amountsIn The actual amounts of token deposited in token sorted order
function _mintLP(
uint256 inputUnderlying,
uint256 inputBond,
uint256[] memory currentBalances,
address recipient
) internal returns (uint256[] memory amountsIn) {
// Initialize the memory array with length
amountsIn = new uint256[](2);
// Passing in in memory array helps stack but we use locals for better names
(uint256 reserveUnderlying, uint256 reserveBond) = _getSortedBalances(
currentBalances
);
uint256 localTotalSupply = totalSupply();
// Check if the pool is initialized
if (localTotalSupply == 0) {
// When uninitialized we mint exactly the underlying input
// in LP tokens
_mintPoolTokens(recipient, inputUnderlying);
// Return the right data
amountsIn[baseIndex] = inputUnderlying;
amountsIn[bondIndex] = 0;
return (amountsIn);
}
// Get the reserve ratio, the say how many underlying per bond in the reserve
// (input underlying / reserve underlying) is the percent increase caused by deposit
uint256 underlyingPerBond = reserveUnderlying.divDown(reserveBond);
// Use the underlying per bond to get the needed number of input underlying
uint256 neededUnderlying = underlyingPerBond.mulDown(inputBond);
// If the user can't provide enough underlying
if (neededUnderlying > inputUnderlying) {
// The increase in total supply is the input underlying
// as a ratio to reserve
uint256 mintAmount = (inputUnderlying.mulDown(localTotalSupply))
.divDown(reserveUnderlying);
// We mint a new amount of as the the percent increase given
// by the ratio of the input underlying to the reserve underlying
_mintPoolTokens(recipient, mintAmount);
// In this case we use the whole input of underlying
// and consume (inputUnderlying/underlyingPerBond) bonds
amountsIn[baseIndex] = inputUnderlying;
amountsIn[bondIndex] = inputUnderlying.divDown(underlyingPerBond);
} else {
// We calculate the percent increase in the reserves from contributing
// all of the bond
uint256 mintAmount = (neededUnderlying.mulDown(localTotalSupply))
.divDown(reserveUnderlying);
// We then mint an amount of pool token which corresponds to that increase
_mintPoolTokens(recipient, mintAmount);
// The indicate we consumed the input bond and (inputBond*underlyingPerBond)
amountsIn[baseIndex] = neededUnderlying;
amountsIn[bondIndex] = inputBond;
}
}
/// @dev Burns a number of LP tokens and returns the amount of the pool which they own.
/// @param lpOut The minimum output in underlying
/// @param currentBalances The current pool balances, sorted by address low to high. length 2
/// @param source The address to burn from.
/// @return amountsReleased in address sorted order
function _burnLP(
uint256 lpOut,
uint256[] memory currentBalances,
address source
) internal returns (uint256[] memory amountsReleased) {
// Load the number of LP token
uint256 localTotalSupply = totalSupply();
// Burn the LP tokens from the user
_burnPoolTokens(source, lpOut);
// Initialize the memory array with length 2
amountsReleased = new uint256[](2);
// They get a percent ratio of the pool, div down will cause a very small
// rounding error loss.
amountsReleased[baseIndex] = (currentBalances[baseIndex].mulDown(lpOut))
.divDown(localTotalSupply);
amountsReleased[bondIndex] = (currentBalances[bondIndex].mulDown(lpOut))
.divDown(localTotalSupply);
}
/// @dev Calculates 1 - t
/// @return Returns 1 - t, encoded as a fraction in 18 decimal fixed point
function _getYieldExponent() internal view virtual returns (uint256) {
// The fractional time
uint256 timeTillExpiry = block.timestamp < expiration
? expiration - block.timestamp
: 0;
timeTillExpiry *= 1e18;
// timeTillExpiry now contains the a fixed point of the years remaining
timeTillExpiry = timeTillExpiry.divDown(unitSeconds * 1e18);
uint256 result = uint256(FixedPoint.ONE).sub(timeTillExpiry);
// Sanity Check
require(result != 0);
// Return result
return result;
}
/// @dev Applies the reserve adjustment from the paper and returns the reserves
/// Note: The inputs should be in 18 point fixed to match the LP decimals
/// @param reserveTokenIn The reserve of the input token
/// @param tokenIn The address of the input token
/// @param reserveTokenOut The reserve of the output token
/// @return Returns (adjustedReserveIn, adjustedReserveOut)
function _adjustedReserve(
uint256 reserveTokenIn,
IERC20 tokenIn,
uint256 reserveTokenOut,
IERC20 tokenOut
) internal view returns (uint256, uint256) {
// We need to identify the bond asset and the underlying
// This check is slightly redundant in most cases but more secure
if (tokenIn == underlying && tokenOut == bond) {
// We return (underlyingReserve, bondReserve + totalLP)
return (reserveTokenIn, reserveTokenOut + totalSupply());
} else if (tokenIn == bond && tokenOut == underlying) {
// We return (bondReserve + totalLP, underlyingReserve)
return (reserveTokenIn + totalSupply(), reserveTokenOut);
}
// This should never be hit
revert("Token request doesn't match stored");
}
/// @notice Mutates the input current balances array to remove fees paid to governance and balancer
/// Also resets the LP storage and realizes governance fees, returns the fees which are paid
/// to balancer
/// @param currentBalances The overall balances
/// @param balancerFee The percent of LP fees that balancer takes as a fee
/// @return dueProtocolFees The fees which will be paid to balancer on this join or exit
/// @dev WARNING - Solidity will implicitly cast a 'uint256[] calldata' to 'uint256[] memory' on function calls, but
/// since calldata is immutable mutations made in this call are discarded in future references to the
/// variable in other functions. 'currentBalances' must STRICTLY be of type uint256[] memory for this
/// function to work.
function _feeAccounting(
uint256[] memory currentBalances,
uint256 balancerFee
) internal returns (uint256[] memory dueProtocolFees) {
// Load the total fees
uint256 localFeeUnderlying = uint256(feesUnderlying);
uint256 localFeeBond = uint256(feesBond);
dueProtocolFees = new uint256[](2);
// Calculate the balancer fee [this also implicitly returns this data]
dueProtocolFees[baseIndex] = localFeeUnderlying.mulDown(balancerFee);
dueProtocolFees[bondIndex] = localFeeBond.mulDown(balancerFee);
// Calculate the governance fee from total LP
uint256 govFeeBase = localFeeUnderlying.mulDown(percentFeeGov);
uint256 govFeeBond = localFeeBond.mulDown(percentFeeGov);
// Add the fees collected by gov to the stored ones
governanceFeesUnderlying += uint128(govFeeBase);
governanceFeesBond += uint128(govFeeBond);
// We subtract the amounts which are paid as fee but have not been collected.
// This leaves LPs with the deposits plus their amount of fees
currentBalances[baseIndex] = currentBalances[baseIndex]
.sub(dueProtocolFees[baseIndex])
.sub(governanceFeesUnderlying);
currentBalances[bondIndex] = currentBalances[bondIndex]
.sub(dueProtocolFees[bondIndex])
.sub(governanceFeesBond);
// Since all fees have been accounted for we reset the LP fees collected to zero
feesUnderlying = uint120(0);
feesBond = uint120(0);
}
/// @dev Turns a token which is either 'bond' or 'underlying' into 18 point decimal
/// @param amount The amount of the token in native decimal encoding
/// @param token The address of the token
/// @return The amount of token encoded into 18 point fixed point
function _tokenToFixed(uint256 amount, IERC20 token)
internal
view
returns (uint256)
{
// In both cases we are targeting 18 point
if (token == underlying) {
return _normalize(amount, underlyingDecimals, 18);
} else if (token == bond) {
return _normalize(amount, bondDecimals, 18);
}
// Should never happen
revert("Called with non pool token");
}
/// @dev Turns an 18 fixed point amount into a token amount
/// Token must be either 'bond' or 'underlying'
/// @param amount The amount of the token in 18 decimal fixed point
/// @param token The address of the token
/// @return The amount of token encoded in native decimal point
function _fixedToToken(uint256 amount, IERC20 token)
internal
view
returns (uint256)
{
if (token == underlying) {
// Recodes to 'underlyingDecimals' decimals
return _normalize(amount, 18, underlyingDecimals);
} else if (token == bond) {
// Recodes to 'bondDecimals' decimals
return _normalize(amount, 18, bondDecimals);
}
// Should never happen
revert("Called with non pool token");
}
/// @dev Takes an 'amount' encoded with 'decimalsBefore' decimals and
/// re encodes it with 'decimalsAfter' decimals
/// @param amount The amount to normalize
/// @param decimalsBefore The decimal encoding before
/// @param decimalsAfter The decimal encoding after
function _normalize(
uint256 amount,
uint8 decimalsBefore,
uint8 decimalsAfter
) internal pure returns (uint256) {
// If we need to increase the decimals
if (decimalsBefore > decimalsAfter) {
// Then we shift right the amount by the number of decimals
amount = amount / 10**(decimalsBefore - decimalsAfter);
// If we need to decrease the number
} else if (decimalsBefore < decimalsAfter) {
// then we shift left by the difference
amount = amount * 10**(decimalsAfter - decimalsBefore);
}
// If nothing changed this is a no-op
return amount;
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity >=0.7.0;
import "../balancer-core-v2/lib/openzeppelin/ERC20.sol";
interface IERC20Decimals is IERC20 {
// Non standard but almost all erc20 have this
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the “Software”), to deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
// Software.
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/* solhint-disable */
/**
* @dev Exponentiation and logarithm functions for 18 decimal fixed point numbers (both base and exponent/argument).
*
* Exponentiation and logarithm with arbitrary bases (x^y and log_x(y)) are implemented by conversion to natural
* exponentiation and logarithm (where the base is Euler's number).
*
* @author Fernando Martinelli - @fernandomartinelli
* @author Sergio Yuhjtman - @sergioyuhjtman
* @author Daniel Fernandez - @dmf7z
*/
library LogExpMath {
// All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying
// two numbers, and multiply by ONE when dividing them.
// All arguments and return values are 18 decimal fixed point numbers.
int256 constant ONE_18 = 1e18;
// Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the
// case of ln36, 36 decimals.
int256 constant ONE_20 = 1e20;
int256 constant ONE_36 = 1e36;
// The domain of natural exponentiation is bound by the word size and number of decimals used.
//
// Because internally the result will be stored using 20 decimals, the largest possible result is
// (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221.
// The smallest possible result is 10^(-18), which makes largest negative argument
// ln(10^(-18)) = -41.446531673892822312.
// We use 130.0 and -41.0 to have some safety margin.
int256 constant MAX_NATURAL_EXPONENT = 130e18;
int256 constant MIN_NATURAL_EXPONENT = -41e18;
// Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point
// 256 bit integer.
int256 constant LN_36_LOWER_BOUND = ONE_18 - 1e17;
int256 constant LN_36_UPPER_BOUND = ONE_18 + 1e17;
uint256 constant MILD_EXPONENT_BOUND = 2**254 / uint256(ONE_20);
// 18 decimal constants
int256 constant x0 = 128000000000000000000; // 2ˆ7
int256 constant a0 = 38877084059945950922200000000000000000000000000000000000; // eˆ(x0) (no decimals)
int256 constant x1 = 64000000000000000000; // 2ˆ6
int256 constant a1 = 6235149080811616882910000000; // eˆ(x1) (no decimals)
// 20 decimal constants
int256 constant x2 = 3200000000000000000000; // 2ˆ5
int256 constant a2 = 7896296018268069516100000000000000; // eˆ(x2)
int256 constant x3 = 1600000000000000000000; // 2ˆ4
int256 constant a3 = 888611052050787263676000000; // eˆ(x3)
int256 constant x4 = 800000000000000000000; // 2ˆ3
int256 constant a4 = 298095798704172827474000; // eˆ(x4)
int256 constant x5 = 400000000000000000000; // 2ˆ2
int256 constant a5 = 5459815003314423907810; // eˆ(x5)
int256 constant x6 = 200000000000000000000; // 2ˆ1
int256 constant a6 = 738905609893065022723; // eˆ(x6)
int256 constant x7 = 100000000000000000000; // 2ˆ0
int256 constant a7 = 271828182845904523536; // eˆ(x7)
int256 constant x8 = 50000000000000000000; // 2ˆ-1
int256 constant a8 = 164872127070012814685; // eˆ(x8)
int256 constant x9 = 25000000000000000000; // 2ˆ-2
int256 constant a9 = 128402541668774148407; // eˆ(x9)
int256 constant x10 = 12500000000000000000; // 2ˆ-3
int256 constant a10 = 113314845306682631683; // eˆ(x10)
int256 constant x11 = 6250000000000000000; // 2ˆ-4
int256 constant a11 = 106449445891785942956; // eˆ(x11)
/**
* @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent.
*
* Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`.
*/
function pow(uint256 x, uint256 y) internal pure returns (uint256) {
if (y == 0) {
// We solve the 0^0 indetermination by making it equal one.
return uint256(ONE_18);
}
if (x == 0) {
return 0;
}
// Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to
// arrive at that result. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means
// x^y = exp(y * ln(x)).
// The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range.
_require(x < 2**255, Errors.X_OUT_OF_BOUNDS);
int256 x_int256 = int256(x);
// We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In
// both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end.
// This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range.
_require(y < MILD_EXPONENT_BOUND, Errors.Y_OUT_OF_BOUNDS);
int256 y_int256 = int256(y);
int256 logx_times_y;
if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) {
int256 ln_36_x = _ln_36(x_int256);
// ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just
// bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal
// multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the
// (downscaled) last 18 decimals.
logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18);
} else {
logx_times_y = _ln(x_int256) * y_int256;
}
logx_times_y /= ONE_18;
// Finally, we compute exp(y * ln(x)) to arrive at x^y
_require(
MIN_NATURAL_EXPONENT <= logx_times_y && logx_times_y <= MAX_NATURAL_EXPONENT,
Errors.PRODUCT_OUT_OF_BOUNDS
);
return uint256(exp(logx_times_y));
}
/**
* @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent.
*
* Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`.
*/
function exp(int256 x) internal pure returns (int256) {
_require(x >= MIN_NATURAL_EXPONENT && x <= MAX_NATURAL_EXPONENT, Errors.INVALID_EXPONENT);
if (x < 0) {
// We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it
// fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT).
// Fixed point division requires multiplying by ONE_18.
return ((ONE_18 * ONE_18) / exp(-x));
}
// First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n,
// where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7
// because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the
// decomposition.
// At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this
// decomposition, which will be lower than the smallest x_n.
// exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1.
// We mutate x by subtracting x_n, making it the remainder of the decomposition.
// The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause
// intermediate overflows. Instead we store them as plain integers, with 0 decimals.
// Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the
// decomposition.
// For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct
// it and compute the accumulated product.
int256 firstAN;
if (x >= x0) {
x -= x0;
firstAN = a0;
} else if (x >= x1) {
x -= x1;
firstAN = a1;
} else {
firstAN = 1; // One with no decimal places
}
// We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the
// smaller terms.
x *= 100;
// `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point
// one. Recall that fixed point multiplication requires dividing by ONE_20.
int256 product = ONE_20;
if (x >= x2) {
x -= x2;
product = (product * a2) / ONE_20;
}
if (x >= x3) {
x -= x3;
product = (product * a3) / ONE_20;
}
if (x >= x4) {
x -= x4;
product = (product * a4) / ONE_20;
}
if (x >= x5) {
x -= x5;
product = (product * a5) / ONE_20;
}
if (x >= x6) {
x -= x6;
product = (product * a6) / ONE_20;
}
if (x >= x7) {
x -= x7;
product = (product * a7) / ONE_20;
}
if (x >= x8) {
x -= x8;
product = (product * a8) / ONE_20;
}
if (x >= x9) {
x -= x9;
product = (product * a9) / ONE_20;
}
// x10 and x11 are unnecessary here since we have high enough precision already.
// Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series
// expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!).
int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places.
int256 term; // Each term in the sum, where the nth term is (x^n / n!).
// The first term is simply x.
term = x;
seriesSum += term;
// Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number,
// multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not.
term = ((term * x) / ONE_20) / 2;
seriesSum += term;
term = ((term * x) / ONE_20) / 3;
seriesSum += term;
term = ((term * x) / ONE_20) / 4;
seriesSum += term;
term = ((term * x) / ONE_20) / 5;
seriesSum += term;
term = ((term * x) / ONE_20) / 6;
seriesSum += term;
term = ((term * x) / ONE_20) / 7;
seriesSum += term;
term = ((term * x) / ONE_20) / 8;
seriesSum += term;
term = ((term * x) / ONE_20) / 9;
seriesSum += term;
term = ((term * x) / ONE_20) / 10;
seriesSum += term;
term = ((term * x) / ONE_20) / 11;
seriesSum += term;
term = ((term * x) / ONE_20) / 12;
seriesSum += term;
// 12 Taylor terms are sufficient for 18 decimal precision.
// We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor
// approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply
// all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication),
// and then drop two digits to return an 18 decimal value.
return (((product * seriesSum) / ONE_20) * firstAN) / 100;
}
/**
* @dev Logarithm (log(arg, base), with signed 18 decimal fixed point base and argument.
*/
function log(int256 arg, int256 base) internal pure returns (int256) {
// This performs a simple base change: log(arg, base) = ln(arg) / ln(base).
// Both logBase and logArg are computed as 36 decimal fixed point numbers, either by using ln_36, or by
// upscaling.
int256 logBase;
if (LN_36_LOWER_BOUND < base && base < LN_36_UPPER_BOUND) {
logBase = _ln_36(base);
} else {
logBase = _ln(base) * ONE_18;
}
int256 logArg;
if (LN_36_LOWER_BOUND < arg && arg < LN_36_UPPER_BOUND) {
logArg = _ln_36(arg);
} else {
logArg = _ln(arg) * ONE_18;
}
// When dividing, we multiply by ONE_18 to arrive at a result with 18 decimal places
return (logArg * ONE_18) / logBase;
}
/**
* @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument.
*/
function ln(int256 a) internal pure returns (int256) {
// The real natural logarithm is not defined for negative numbers or zero.
_require(a > 0, Errors.OUT_OF_BOUNDS);
if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) {
return _ln_36(a) / ONE_18;
} else {
return _ln(a);
}
}
/**
* @dev Internal natural logarithm (ln(a)) with signed 18 decimal fixed point argument.
*/
function _ln(int256 a) private pure returns (int256) {
if (a < ONE_18) {
// Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less
// than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call.
// Fixed point division requires multiplying by ONE_18.
return (-_ln((ONE_18 * ONE_18) / a));
}
// First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which
// we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is,
// ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot
// be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a.
// At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this
// decomposition, which will be lower than the smallest a_n.
// ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1.
// We mutate a by subtracting a_n, making it the remainder of the decomposition.
// For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point
// numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by
// ONE_18 to convert them to fixed point.
// For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide
// by it and compute the accumulated sum.
int256 sum = 0;
if (a >= a0 * ONE_18) {
a /= a0; // Integer, not fixed point division
sum += x0;
}
if (a >= a1 * ONE_18) {
a /= a1; // Integer, not fixed point division
sum += x1;
}
// All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format.
sum *= 100;
a *= 100;
// Because further a_n are 20 digit fixed point numbers, we multiply by ONE_20 when dividing by them.
if (a >= a2) {
a = (a * ONE_20) / a2;
sum += x2;
}
if (a >= a3) {
a = (a * ONE_20) / a3;
sum += x3;
}
if (a >= a4) {
a = (a * ONE_20) / a4;
sum += x4;
}
if (a >= a5) {
a = (a * ONE_20) / a5;
sum += x5;
}
if (a >= a6) {
a = (a * ONE_20) / a6;
sum += x6;
}
if (a >= a7) {
a = (a * ONE_20) / a7;
sum += x7;
}
if (a >= a8) {
a = (a * ONE_20) / a8;
sum += x8;
}
if (a >= a9) {
a = (a * ONE_20) / a9;
sum += x9;
}
if (a >= a10) {
a = (a * ONE_20) / a10;
sum += x10;
}
if (a >= a11) {
a = (a * ONE_20) / a11;
sum += x11;
}
// a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series
// that converges rapidly for values of `a` close to one - the same one used in ln_36.
// Let z = (a - 1) / (a + 1).
// ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))
// Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires
// division by ONE_20.
int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20);
int256 z_squared = (z * z) / ONE_20;
// num is the numerator of the series: the z^(2 * n + 1) term
int256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial z
int256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_20;
seriesSum += num / 3;
num = (num * z_squared) / ONE_20;
seriesSum += num / 5;
num = (num * z_squared) / ONE_20;
seriesSum += num / 7;
num = (num * z_squared) / ONE_20;
seriesSum += num / 9;
num = (num * z_squared) / ONE_20;
seriesSum += num / 11;
// 6 Taylor terms are sufficient for 36 decimal precision.
// Finally, we multiply by 2 (non fixed point) to compute ln(remainder)
seriesSum *= 2;
// We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both
// with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal
// value.
return (sum + seriesSum) / 100;
}
/**
* @dev Intrnal high precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument,
* for x close to one.
*
* Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND.
*/
function _ln_36(int256 x) private pure returns (int256) {
// Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits
// worthwhile.
// First, we transform x to a 36 digit fixed point value.
x *= ONE_18;
// We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1).
// ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))
// Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires
// division by ONE_36.
int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36);
int256 z_squared = (z * z) / ONE_36;
// num is the numerator of the series: the z^(2 * n + 1) term
int256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial z
int256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_36;
seriesSum += num / 3;
num = (num * z_squared) / ONE_36;
seriesSum += num / 5;
num = (num * z_squared) / ONE_36;
seriesSum += num / 7;
num = (num * z_squared) / ONE_36;
seriesSum += num / 9;
num = (num * z_squared) / ONE_36;
seriesSum += num / 11;
num = (num * z_squared) / ONE_36;
seriesSum += num / 13;
num = (num * z_squared) / ONE_36;
seriesSum += num / 15;
// 8 Taylor terms are sufficient for 36 decimal precision.
// All that remains is multiplying by 2 (non fixed point).
return seriesSum * 2;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "./LogExpMath.sol";
import "../helpers/BalancerErrors.sol";
/* solhint-disable private-vars-leading-underscore */
library FixedPoint {
uint256 internal constant ONE = 1e18; // 18 decimal places
uint256 internal constant MAX_POW_RELATIVE_ERROR = 10000; // 10^(-14)
// Minimum base for the power function when the exponent is 'free' (larger than ONE).
uint256 internal constant MIN_POW_BASE_FREE_EXPONENT = 0.7e18;
function add(uint256 a, uint256 b) internal pure returns (uint256) {
// Fixed Point addition is the same as regular checked addition
uint256 c = a + b;
_require(c >= a, Errors.ADD_OVERFLOW);
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
// Fixed Point addition is the same as regular checked addition
_require(b <= a, Errors.SUB_OVERFLOW);
uint256 c = a - b;
return c;
}
function mulDown(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 product = a * b;
_require(a == 0 || product / a == b, Errors.MUL_OVERFLOW);
return product / ONE;
}
function mulUp(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 product = a * b;
_require(a == 0 || product / a == b, Errors.MUL_OVERFLOW);
if (product == 0) {
return 0;
} else {
// The traditional divUp formula is:
// divUp(x, y) := (x + y - 1) / y
// To avoid intermediate overflow in the addition, we distribute the division and get:
// divUp(x, y) := (x - 1) / y + 1
// Note that this requires x != 0, which we already tested for.
return ((product - 1) / ONE) + 1;
}
}
function divDown(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
if (a == 0) {
return 0;
} else {
uint256 aInflated = a * ONE;
_require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow
return aInflated / b;
}
}
function divUp(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
if (a == 0) {
return 0;
} else {
uint256 aInflated = a * ONE;
_require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow
// The traditional divUp formula is:
// divUp(x, y) := (x + y - 1) / y
// To avoid intermediate overflow in the addition, we distribute the division and get:
// divUp(x, y) := (x - 1) / y + 1
// Note that this requires x != 0, which we already tested for.
return ((aInflated - 1) / b) + 1;
}
}
/**
* @dev Returns x^y, assuming both are fixed point numbers, rounding down. The result is guaranteed to not be above
* the true value (that is, the error function expected - actual is always positive).
*/
function powDown(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 raw = LogExpMath.pow(x, y);
uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1);
if (raw < maxError) {
return 0;
} else {
return sub(raw, maxError);
}
}
/**
* @dev Returns x^y, assuming both are fixed point numbers, rounding up. The result is guaranteed to not be below
* the true value (that is, the error function expected - actual is always negative).
*/
function powUp(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 raw = LogExpMath.pow(x, y);
uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1);
return add(raw, maxError);
}
/**
* @dev Returns the complement of a value (1 - x), capped to 0 if x is larger than 1.
*
* Useful when computing the complement for values with some level of relative error, as it strips this error and
* prevents intermediate negative values.
*/
function complement(uint256 x) internal pure returns (uint256) {
return (x < ONE) ? (ONE - x) : 0;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./IBasePool.sol";
/**
* @dev Pool contracts with the MinimalSwapInfo or TwoToken specialization settings should implement this interface.
*
* This is called by the Vault when a user calls `IVault.swap` or `IVault.batchSwap` to swap with this Pool.
* Returns the number of tokens the Pool will grant to the user in a 'given in' swap, or that the user will grant
* to the pool in a 'given out' swap.
*
* This can often be implemented by a `view` function, since many pricing algorithms don't need to track state
* changes in swaps. However, contracts implementing this in non-view functions should check that the caller is
* indeed the Vault.
*/
interface IMinimalSwapInfoPool is IBasePool {
function onSwap(
SwapRequest memory swapRequest,
uint256 currentBalanceTokenIn,
uint256 currentBalanceTokenOut
) external returns (uint256 amount);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma experimental ABIEncoderV2;
import "../../lib/openzeppelin/IERC20.sol";
import "./IWETH.sol";
import "./IAsset.sol";
import "./IAuthorizer.sol";
import "./IFlashLoanRecipient.sol";
import "../ProtocolFeesCollector.sol";
import "../../lib/helpers/ISignaturesValidator.sol";
import "../../lib/helpers/ITemporarilyPausable.sol";
pragma solidity ^0.7.0;
/**
* @dev Full external interface for the Vault core contract - no external or public methods exist in the contract that
* don't override one of these declarations.
*/
interface IVault is ISignaturesValidator, ITemporarilyPausable {
// Generalities about the Vault:
//
// - Whenever documentation refers to 'tokens', it strictly refers to ERC20-compliant token contracts. Tokens are
// transferred out of the Vault by calling the `IERC20.transfer` function, and transferred in by calling
// `IERC20.transferFrom`. In these cases, the sender must have previously allowed the Vault to use their tokens by
// calling `IERC20.approve`. The only deviation from the ERC20 standard that is supported is functions not returning
// a boolean value: in these scenarios, a non-reverting call is assumed to be successful.
//
// - All non-view functions in the Vault are non-reentrant: calling them while another one is mid-execution (e.g.
// while execution control is transferred to a token contract during a swap) will result in a revert. View
// functions can be called in a re-reentrant way, but doing so might cause them to return inconsistent results.
// Contracts calling view functions in the Vault must make sure the Vault has not already been entered.
//
// - View functions revert if referring to either unregistered Pools, or unregistered tokens for registered Pools.
// Authorizer
//
// Some system actions are permissioned, like setting and collecting protocol fees. This permissioning system exists
// outside of the Vault in the Authorizer contract: the Vault simply calls the Authorizer to check if the caller
// can perform a given action.
/**
* @dev Returns the Vault's Authorizer.
*/
function getAuthorizer() external view returns (IAuthorizer);
/**
* @dev Sets a new Authorizer for the Vault. The caller must be allowed by the current Authorizer to do this.
*
* Emits an `AuthorizerChanged` event.
*/
function setAuthorizer(IAuthorizer newAuthorizer) external;
/**
* @dev Emitted when a new authorizer is set by `setAuthorizer`.
*/
event AuthorizerChanged(IAuthorizer indexed newAuthorizer);
// Relayers
//
// Additionally, it is possible for an account to perform certain actions on behalf of another one, using their
// Vault ERC20 allowance and Internal Balance. These accounts are said to be 'relayers' for these Vault functions,
// and are expected to be smart contracts with sound authentication mechanisms. For an account to be able to wield
// this power, two things must occur:
// - The Authorizer must grant the account the permission to be a relayer for the relevant Vault function. This
// means that Balancer governance must approve each individual contract to act as a relayer for the intended
// functions.
// - Each user must approve the relayer to act on their behalf.
// This double protection means users cannot be tricked into approving malicious relayers (because they will not
// have been allowed by the Authorizer via governance), nor can malicious relayers approved by a compromised
// Authorizer or governance drain user funds, since they would also need to be approved by each individual user.
/**
* @dev Returns true if `user` has approved `relayer` to act as a relayer for them.
*/
function hasApprovedRelayer(address user, address relayer) external view returns (bool);
/**
* @dev Allows `relayer` to act as a relayer for `sender` if `approved` is true, and disallows it otherwise.
*
* Emits a `RelayerApprovalChanged` event.
*/
function setRelayerApproval(
address sender,
address relayer,
bool approved
) external;
/**
* @dev Emitted every time a relayer is approved or disapproved by `setRelayerApproval`.
*/
event RelayerApprovalChanged(address indexed relayer, address indexed sender, bool approved);
// Internal Balance
//
// Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later
// transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination
// when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced
// gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users.
//
// Internal Balance management features batching, which means a single contract call can be used to perform multiple
// operations of different kinds, with different senders and recipients, at once.
/**
* @dev Returns `user`'s Internal Balance for a set of tokens.
*/
function getInternalBalance(address user, IERC20[] memory tokens) external view returns (uint256[] memory);
/**
* @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer)
* and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as
* it lets integrators reuse a user's Vault allowance.
*
* For each operation, if the caller is not `sender`, it must be an authorized relayer for them.
*/
function manageUserBalance(UserBalanceOp[] memory ops) external payable;
/**
* @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received
without manual WETH wrapping or unwrapping.
*/
struct UserBalanceOp {
UserBalanceOpKind kind;
IAsset asset;
uint256 amount;
address sender;
address payable recipient;
}
// There are four possible operations in `manageUserBalance`:
//
// - DEPOSIT_INTERNAL
// Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding
// `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`.
//
// ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped
// and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is
// relevant for relayers).
//
// Emits an `InternalBalanceChanged` event.
//
//
// - WITHDRAW_INTERNAL
// Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`.
//
// ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send
// it to the recipient as ETH.
//
// Emits an `InternalBalanceChanged` event.
//
//
// - TRANSFER_INTERNAL
// Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`.
//
// Reverts if the ETH sentinel value is passed.
//
// Emits an `InternalBalanceChanged` event.
//
//
// - TRANSFER_EXTERNAL
// Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by
// relayers, as it lets them reuse a user's Vault allowance.
//
// Reverts if the ETH sentinel value is passed.
//
// Emits an `ExternalBalanceTransfer` event.
enum UserBalanceOpKind { DEPOSIT_INTERNAL, WITHDRAW_INTERNAL, TRANSFER_INTERNAL, TRANSFER_EXTERNAL }
/**
* @dev Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or through
* interacting with Pools using Internal Balance.
*
* Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETH
* address.
*/
event InternalBalanceChanged(address indexed user, IERC20 indexed token, int256 delta);
/**
* @dev Emitted when a user's Vault ERC20 allowance is used by the Vault to transfer tokens to an external account.
*/
event ExternalBalanceTransfer(IERC20 indexed token, address indexed sender, address recipient, uint256 amount);
// Pools
//
// There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced
// functionality:
//
// - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the
// balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads),
// which increase with the number of registered tokens.
//
// - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the
// balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted
// constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are
// independent of the number of registered tokens.
//
// - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like
// minimal swap info Pools, these are called via IMinimalSwapInfoPool.
enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN }
/**
* @dev Registers the caller account as a Pool with a given specialization setting. Returns the Pool's ID, which
* is used in all Pool-related functions. Pools cannot be deregistered, nor can the Pool's specialization be
* changed.
*
* The caller is expected to be a smart contract that implements either `IGeneralPool` or `IMinimalSwapInfoPool`,
* depending on the chosen specialization setting. This contract is known as the Pool's contract.
*
* Note that the same contract may register itself as multiple Pools with unique Pool IDs, or in other words,
* multiple Pools may share the same contract.
*
* Emits a `PoolRegistered` event.
*/
function registerPool(PoolSpecialization specialization) external returns (bytes32);
/**
* @dev Emitted when a Pool is registered by calling `registerPool`.
*/
event PoolRegistered(bytes32 indexed poolId, address indexed poolAddress, PoolSpecialization specialization);
/**
* @dev Returns a Pool's contract address and specialization setting.
*/
function getPool(bytes32 poolId) external view returns (address, PoolSpecialization);
/**
* @dev Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract.
*
* Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens,
* exit by receiving registered tokens, and can only swap registered tokens.
*
* Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a length
* of two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted in
* ascending order.
*
* The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the Asset
* Manager for the corresponding token. Asset Managers can manage a Pool's tokens via `managePoolBalance`,
* depositing and withdrawing them directly, and can even set their balance to arbitrary amounts. They are therefore
* expected to be highly secured smart contracts with sound design principles, and the decision to register an
* Asset Manager should not be made lightly.
*
* Pools can choose not to assign an Asset Manager to a given token by passing in the zero address. Once an Asset
* Manager is set, it cannot be changed except by deregistering the associated token and registering again with a
* different Asset Manager.
*
* Emits a `TokensRegistered` event.
*/
function registerTokens(
bytes32 poolId,
IERC20[] memory tokens,
address[] memory assetManagers
) external;
/**
* @dev Emitted when a Pool registers tokens by calling `registerTokens`.
*/
event TokensRegistered(bytes32 indexed poolId, IERC20[] tokens, address[] assetManagers);
/**
* @dev Deregisters `tokens` for the `poolId` Pool. Must be called by the Pool's contract.
*
* Only registered tokens (via `registerTokens`) can be deregistered. Additionally, they must have zero total
* balance. For Pools with the Two Token specialization, `tokens` must have a length of two, that is, both tokens
* must be deregistered in the same `deregisterTokens` call.
*
* A deregistered token can be re-registered later on, possibly with a different Asset Manager.
*
* Emits a `TokensDeregistered` event.
*/
function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external;
/**
* @dev Emitted when a Pool deregisters tokens by calling `deregisterTokens`.
*/
event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens);
/**
* @dev Returns detailed information for a Pool's registered token.
*
* `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokens
* withdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token`
* equals the sum of `cash` and `managed`.
*
* Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`,
* `managed` or `total` balance to be greater than 2^112 - 1.
*
* `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either a
* join, exit, swap, or Asset Manager update). This value is useful to avoid so-called 'sandwich attacks', for
* example when developing price oracles. A change of zero (e.g. caused by a swap with amount zero) is considered a
* change for this purpose, and will update `lastChangeBlock`.
*
* `assetManager` is the Pool's token Asset Manager.
*/
function getPoolTokenInfo(bytes32 poolId, IERC20 token)
external
view
returns (
uint256 cash,
uint256 managed,
uint256 lastChangeBlock,
address assetManager
);
/**
* @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of
* the tokens' `balances` changed.
*
* The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all
* Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order.
*
* If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same
* order as passed to `registerTokens`.
*
* Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are
* the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo`
* instead.
*/
function getPoolTokens(bytes32 poolId)
external
view
returns (
IERC20[] memory tokens,
uint256[] memory balances,
uint256 lastChangeBlock
);
/**
* @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will
* trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized
* Pool shares.
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount
* to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces
* these maximums.
*
* If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable
* this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the
* WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent
* back to the caller (not the sender, which is important for relayers).
*
* `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
* interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be
* sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final
* `assets` array might not be sorted. Pools with no registered tokens cannot be joined.
*
* If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only
* be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be
* withdrawn from Internal Balance: attempting to do so will trigger a revert.
*
* This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement
* their own custom logic. This typically requires additional information from the user (such as the expected number
* of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed
* directly to the Pool's contract, as is `recipient`.
*
* Emits a `PoolBalanceChanged` event.
*/
function joinPool(
bytes32 poolId,
address sender,
address recipient,
JoinPoolRequest memory request
) external payable;
struct JoinPoolRequest {
IAsset[] assets;
uint256[] maxAmountsIn;
bytes userData;
bool fromInternalBalance;
}
/**
* @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will
* trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized
* Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see
* `getPoolTokenInfo`).
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum
* token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault:
* it just enforces these minimums.
*
* If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To
* enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead
* of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit.
*
* `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
* interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must
* be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the
* final `assets` array might not be sorted. Pools with no registered tokens cannot be exited.
*
* If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise,
* an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to
* do so will trigger a revert.
*
* `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the
* `tokens` array. This array must match the Pool's registered tokens.
*
* This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement
* their own custom logic. This typically requires additional information from the user (such as the expected number
* of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and
* passed directly to the Pool's contract.
*
* Emits a `PoolBalanceChanged` event.
*/
function exitPool(
bytes32 poolId,
address sender,
address payable recipient,
ExitPoolRequest memory request
) external;
struct ExitPoolRequest {
IAsset[] assets;
uint256[] minAmountsOut;
bytes userData;
bool toInternalBalance;
}
/**
* @dev Emitted when a user joins or exits a Pool by calling `joinPool` or `exitPool`, respectively.
*/
event PoolBalanceChanged(
bytes32 indexed poolId,
address indexed liquidityProvider,
IERC20[] tokens,
int256[] deltas,
uint256[] protocolFeeAmounts
);
enum PoolBalanceChangeKind { JOIN, EXIT }
// Swaps
//
// Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this,
// they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be
// aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote.
//
// The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence.
// In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'),
// and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out').
// More complex swaps, such as one token in to multiple tokens out can be achieved by batching together
// individual swaps.
//
// There are two swap kinds:
// - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the
// `onSwap` hook) the amount of tokens out (to send to the recipient).
// - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines
// (via the `onSwap` hook) the amount of tokens in (to receive from the sender).
//
// Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with
// the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated
// tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended
// swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at
// the final intended token.
//
// In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal
// Balance) after all individual swaps have been completed, and the net token balance change computed. This makes
// certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost
// much less gas than they would otherwise.
//
// It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple
// Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only
// updating the Pool's internal accounting).
//
// To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token
// involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the
// minimum amount of tokens to receive (by passing a negative value) is specified.
//
// Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after
// this point in time (e.g. if the transaction failed to be included in a block promptly).
//
// If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do
// the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be
// passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the
// same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers).
//
// Finally, Internal Balance can be used when either sending or receiving tokens.
enum SwapKind { GIVEN_IN, GIVEN_OUT }
/**
* @dev Performs a swap with a single Pool.
*
* If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens
* taken from the Pool, which must be greater than or equal to `limit`.
*
* If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens
* sent to the Pool, which must be less than or equal to `limit`.
*
* Internal Balance usage and the recipient are determined by the `funds` struct.
*
* Emits a `Swap` event.
*/
function swap(
SingleSwap memory singleSwap,
FundManagement memory funds,
uint256 limit,
uint256 deadline
) external payable returns (uint256);
/**
* @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on
* the `kind` value.
*
* `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address).
* Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct SingleSwap {
bytes32 poolId;
SwapKind kind;
IAsset assetIn;
IAsset assetOut;
uint256 amount;
bytes userData;
}
/**
* @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either
* the amount of tokens sent to or received from the Pool, depending on the `kind` value.
*
* Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the
* Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at
* the same index in the `assets` array.
*
* Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a
* Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or
* `amountOut` depending on the swap kind.
*
* Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out
* of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal
* the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`.
*
* The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses,
* or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and
* out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to
* or unwrapped from WETH by the Vault.
*
* Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies
* the minimum or maximum amount of each token the vault is allowed to transfer.
*
* `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the
* equivalent `swap` call.
*
* Emits `Swap` events.
*/
function batchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds,
int256[] memory limits,
uint256 deadline
) external payable returns (int256[] memory);
/**
* @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the
* `assets` array passed to that function, and ETH assets are converted to WETH.
*
* If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out
* from the previous swap, depending on the swap kind.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct BatchSwapStep {
bytes32 poolId;
uint256 assetInIndex;
uint256 assetOutIndex;
uint256 amount;
bytes userData;
}
/**
* @dev Emitted for each individual swap performed by `swap` or `batchSwap`.
*/
event Swap(
bytes32 indexed poolId,
IERC20 indexed tokenIn,
IERC20 indexed tokenOut,
uint256 amountIn,
uint256 amountOut
);
/**
* @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the
* `recipient` account.
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20
* transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender`
* must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of
* `joinPool`.
*
* If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of
* transferred. This matches the behavior of `exitPool`.
*
* Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a
* revert.
*/
struct FundManagement {
address sender;
bool fromInternalBalance;
address payable recipient;
bool toInternalBalance;
}
/**
* @dev Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be
* simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result.
*
* Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH)
* the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it
* receives are the same that an equivalent `batchSwap` call would receive.
*
* Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct.
* This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens,
* approve them for the Vault, or even know a user's address.
*
* Note that this function is not 'view' (due to implementation details): the client code must explicitly execute
* eth_call instead of eth_sendTransaction.
*/
function queryBatchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds
) external returns (int256[] memory assetDeltas);
// Flash Loans
/**
* @dev Performs a 'flash loan', sending tokens to `recipient`, executing the `receiveFlashLoan` hook on it,
* and then reverting unless the tokens plus a proportional protocol fee have been returned.
*
* The `tokens` and `amounts` arrays must have the same length, and each entry in these indicates the loan amount
* for each token contract. `tokens` must be sorted in ascending order.
*
* The 'userData' field is ignored by the Vault, and forwarded as-is to `recipient` as part of the
* `receiveFlashLoan` call.
*
* Emits `FlashLoan` events.
*/
function flashLoan(
IFlashLoanRecipient recipient,
IERC20[] memory tokens,
uint256[] memory amounts,
bytes memory userData
) external;
/**
* @dev Emitted for each individual flash loan performed by `flashLoan`.
*/
event FlashLoan(IFlashLoanRecipient indexed recipient, IERC20 indexed token, uint256 amount, uint256 feeAmount);
// Asset Management
//
// Each token registered for a Pool can be assigned an Asset Manager, which is able to freely withdraw the Pool's
// tokens from the Vault, deposit them, or assign arbitrary values to its `managed` balance (see
// `getPoolTokenInfo`). This makes them extremely powerful and dangerous. Even if an Asset Manager only directly
// controls one of the tokens in a Pool, a malicious manager could set that token's balance to manipulate the
// prices of the other tokens, and then drain the Pool with swaps. The risk of using Asset Managers is therefore
// not constrained to the tokens they are managing, but extends to the entire Pool's holdings.
//
// However, a properly designed Asset Manager smart contract can be safely used for the Pool's benefit,
// for example by lending unused tokens out for interest, or using them to participate in voting protocols.
//
// This concept is unrelated to the IAsset interface.
/**
* @dev Performs a set of Pool balance operations, which may be either withdrawals, deposits or updates.
*
* Pool Balance management features batching, which means a single contract call can be used to perform multiple
* operations of different kinds, with different Pools and tokens, at once.
*
* For each operation, the caller must be registered as the Asset Manager for `token` in `poolId`.
*/
function managePoolBalance(PoolBalanceOp[] memory ops) external;
struct PoolBalanceOp {
PoolBalanceOpKind kind;
bytes32 poolId;
IERC20 token;
uint256 amount;
}
/**
* Withdrawals decrease the Pool's cash, but increase its managed balance, leaving the total balance unchanged.
*
* Deposits increase the Pool's cash, but decrease its managed balance, leaving the total balance unchanged.
*
* Updates don't affect the Pool's cash balance, but because the managed balance changes, it does alter the total.
* The external amount can be either increased or decreased by this call (i.e., reporting a gain or a loss).
*/
enum PoolBalanceOpKind { WITHDRAW, DEPOSIT, UPDATE }
/**
* @dev Emitted when a Pool's token Asset Manager alters its balance via `managePoolBalance`.
*/
event PoolBalanceManaged(
bytes32 indexed poolId,
address indexed assetManager,
IERC20 indexed token,
int256 cashDelta,
int256 managedDelta
);
// Protocol Fees
//
// Some operations cause the Vault to collect tokens in the form of protocol fees, which can then be withdrawn by
// permissioned accounts.
//
// There are two kinds of protocol fees:
//
// - flash loan fees: charged on all flash loans, as a percentage of the amounts lent.
//
// - swap fees: a percentage of the fees charged by Pools when performing swaps. For a number of reasons, including
// swap gas costs and interface simplicity, protocol swap fees are not charged on each individual swap. Rather,
// Pools are expected to keep track of how much they have charged in swap fees, and pay any outstanding debts to the
// Vault when they are joined or exited. This prevents users from joining a Pool with unpaid debt, as well as
// exiting a Pool in debt without first paying their share.
/**
* @dev Returns the current protocol fee module.
*/
function getProtocolFeesCollector() external view returns (ProtocolFeesCollector);
/**
* @dev Safety mechanism to pause most Vault operations in the event of an emergency - typically detection of an
* error in some part of the system.
*
* The Vault can only be paused during an initial time period, after which pausing is forever disabled.
*
* While the contract is paused, the following features are disabled:
* - depositing and transferring internal balance
* - transferring external balance (using the Vault's allowance)
* - swaps
* - joining Pools
* - Asset Manager interactions
*
* Internal Balance can still be withdrawn, and Pools exited.
*/
function setPaused(bool paused) external;
/**
* @dev Returns the Vault's WETH instance.
*/
function WETH() external view returns (IWETH);
// solhint-disable-previous-line func-name-mixedcase
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "../lib/math/Math.sol";
import "../lib/openzeppelin/IERC20.sol";
import "../lib/openzeppelin/IERC20Permit.sol";
import "../lib/openzeppelin/EIP712.sol";
/**
* @title Highly opinionated token implementation
* @author Balancer Labs
* @dev
* - Includes functions to increase and decrease allowance as a workaround
* for the well-known issue with `approve`:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* - Allows for 'infinite allowance', where an allowance of 0xff..ff is not
* decreased by calls to transferFrom
* - Lets a token holder use `transferFrom` to send their own tokens,
* without first setting allowance
* - Emits 'Approval' events whenever allowance is changed by `transferFrom`
*/
contract BalancerPoolToken is IERC20, IERC20Permit, EIP712 {
using Math for uint256;
// State variables
uint8 private constant _DECIMALS = 18;
mapping(address => uint256) private _balance;
mapping(address => mapping(address => uint256)) private _allowance;
uint256 private _totalSupply;
string private _name;
string private _symbol;
mapping(address => uint256) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private immutable _PERMIT_TYPE_HASH = keccak256(
"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
);
// Function declarations
constructor(string memory tokenName, string memory tokenSymbol) EIP712(tokenName, "1") {
_name = tokenName;
_symbol = tokenSymbol;
}
// External functions
function allowance(address owner, address spender) external view override returns (uint256) {
return _allowance[owner][spender];
}
function balanceOf(address account) external view override returns (uint256) {
return _balance[account];
}
function approve(address spender, uint256 amount) external override returns (bool) {
_setAllowance(msg.sender, spender, amount);
return true;
}
function increaseApproval(address spender, uint256 amount) external returns (bool) {
_setAllowance(msg.sender, spender, _allowance[msg.sender][spender].add(amount));
return true;
}
function decreaseApproval(address spender, uint256 amount) external returns (bool) {
uint256 currentAllowance = _allowance[msg.sender][spender];
if (amount >= currentAllowance) {
_setAllowance(msg.sender, spender, 0);
} else {
_setAllowance(msg.sender, spender, currentAllowance.sub(amount));
}
return true;
}
function transfer(address recipient, uint256 amount) external override returns (bool) {
_move(msg.sender, recipient, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) external override returns (bool) {
uint256 currentAllowance = _allowance[sender][msg.sender];
_require(msg.sender == sender || currentAllowance >= amount, Errors.INSUFFICIENT_ALLOWANCE);
_move(sender, recipient, amount);
if (msg.sender != sender && currentAllowance != uint256(-1)) {
// Because of the previous require, we know that if msg.sender != sender then currentAllowance >= amount
_setAllowance(sender, msg.sender, currentAllowance - amount);
}
return true;
}
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
// solhint-disable-next-line not-rely-on-time
_require(block.timestamp <= deadline, Errors.EXPIRED_PERMIT);
uint256 nonce = _nonces[owner];
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPE_HASH, owner, spender, value, nonce, deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ecrecover(hash, v, r, s);
_require((signer != address(0)) && (signer == owner), Errors.INVALID_SIGNATURE);
_nonces[owner] = nonce + 1;
_setAllowance(owner, spender, value);
}
// Public functions
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _DECIMALS;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function nonces(address owner) external view override returns (uint256) {
return _nonces[owner];
}
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
// Internal functions
function _mintPoolTokens(address recipient, uint256 amount) internal {
_balance[recipient] = _balance[recipient].add(amount);
_totalSupply = _totalSupply.add(amount);
emit Transfer(address(0), recipient, amount);
}
function _burnPoolTokens(address sender, uint256 amount) internal {
uint256 currentBalance = _balance[sender];
_require(currentBalance >= amount, Errors.INSUFFICIENT_BALANCE);
_balance[sender] = currentBalance - amount;
_totalSupply = _totalSupply.sub(amount);
emit Transfer(sender, address(0), amount);
}
function _move(
address sender,
address recipient,
uint256 amount
) internal {
uint256 currentBalance = _balance[sender];
_require(currentBalance >= amount, Errors.INSUFFICIENT_BALANCE);
// Prohibit transfers to the zero address to avoid confusion with the
// Transfer event emitted by `_burnPoolTokens`
_require(recipient != address(0), Errors.ERC20_TRANSFER_TO_ZERO_ADDRESS);
_balance[sender] = currentBalance - amount;
_balance[recipient] = _balance[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
// Private functions
function _setAllowance(
address owner,
address spender,
uint256 amount
) private {
_allowance[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
import "./IERC20.sol";
import "./SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
msg.sender,
_allowances[sender][msg.sender].sub(amount, Errors.ERC20_TRANSFER_EXCEEDS_ALLOWANCE)
);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(
msg.sender,
spender,
_allowances[msg.sender][spender].sub(subtractedValue, Errors.ERC20_DECREASED_ALLOWANCE_BELOW_ZERO)
);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
_require(sender != address(0), Errors.ERC20_TRANSFER_FROM_ZERO_ADDRESS);
_require(recipient != address(0), Errors.ERC20_TRANSFER_TO_ZERO_ADDRESS);
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, Errors.ERC20_TRANSFER_EXCEEDS_BALANCE);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
_require(account != address(0), Errors.ERC20_MINT_TO_ZERO_ADDRESS);
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
_require(account != address(0), Errors.ERC20_BURN_FROM_ZERO_ADDRESS);
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, Errors.ERC20_BURN_EXCEEDS_ALLOWANCE);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
_require(owner != address(0), Errors.ERC20_APPROVE_FROM_ZERO_ADDRESS);
_require(spender != address(0), Errors.ERC20_APPROVE_TO_ZERO_ADDRESS);
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
// solhint-disable
/**
* @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are
* supported.
*/
function _require(bool condition, uint256 errorCode) pure {
if (!condition) _revert(errorCode);
}
/**
* @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported.
*/
function _revert(uint256 errorCode) pure {
// We're going to dynamically create a revert string based on the error code, with the following format:
// 'BAL#{errorCode}'
// where the code is left-padded with zeroes to three digits (so they range from 000 to 999).
//
// We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a
// number (8 to 16 bits) than the individual string characters.
//
// The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a
// much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a
// safe place to rely on it without worrying about how its usage might affect e.g. memory contents.
assembly {
// First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999
// range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for
// the '0' character.
let units := add(mod(errorCode, 10), 0x30)
errorCode := div(errorCode, 10)
let tenths := add(mod(errorCode, 10), 0x30)
errorCode := div(errorCode, 10)
let hundreds := add(mod(errorCode, 10), 0x30)
// With the individual characters, we can now construct the full string. The "BAL#" part is a known constant
// (0x42414c23): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the
// characters to it, each shifted by a multiple of 8.
// The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits
// per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte
// array).
let revertReason := shl(200, add(0x42414c23000000, add(add(units, shl(8, tenths)), shl(16, hundreds))))
// We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded
// message will have the following layout:
// [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ]
// The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We
// also write zeroes to the next 28 bytes of memory, but those are about to be overwritten.
mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
// Next is the offset to the location of the string, which will be placed immediately after (20 bytes away).
mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020)
// The string length is fixed: 7 characters.
mstore(0x24, 7)
// Finally, the string itself is stored.
mstore(0x44, revertReason)
// Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of
// the encoded message is therefore 4 + 32 + 32 + 32 = 100.
revert(0, 100)
}
}
library Errors {
// Math
uint256 internal constant ADD_OVERFLOW = 0;
uint256 internal constant SUB_OVERFLOW = 1;
uint256 internal constant SUB_UNDERFLOW = 2;
uint256 internal constant MUL_OVERFLOW = 3;
uint256 internal constant ZERO_DIVISION = 4;
uint256 internal constant DIV_INTERNAL = 5;
uint256 internal constant X_OUT_OF_BOUNDS = 6;
uint256 internal constant Y_OUT_OF_BOUNDS = 7;
uint256 internal constant PRODUCT_OUT_OF_BOUNDS = 8;
uint256 internal constant INVALID_EXPONENT = 9;
// Input
uint256 internal constant OUT_OF_BOUNDS = 100;
uint256 internal constant UNSORTED_ARRAY = 101;
uint256 internal constant UNSORTED_TOKENS = 102;
uint256 internal constant INPUT_LENGTH_MISMATCH = 103;
uint256 internal constant ZERO_TOKEN = 104;
// Shared pools
uint256 internal constant MIN_TOKENS = 200;
uint256 internal constant MAX_TOKENS = 201;
uint256 internal constant MAX_SWAP_FEE_PERCENTAGE = 202;
uint256 internal constant MIN_SWAP_FEE_PERCENTAGE = 203;
uint256 internal constant MINIMUM_BPT = 204;
uint256 internal constant CALLER_NOT_VAULT = 205;
uint256 internal constant UNINITIALIZED = 206;
uint256 internal constant BPT_IN_MAX_AMOUNT = 207;
uint256 internal constant BPT_OUT_MIN_AMOUNT = 208;
uint256 internal constant EXPIRED_PERMIT = 209;
// Pools
uint256 internal constant MIN_AMP = 300;
uint256 internal constant MAX_AMP = 301;
uint256 internal constant MIN_WEIGHT = 302;
uint256 internal constant MAX_STABLE_TOKENS = 303;
uint256 internal constant MAX_IN_RATIO = 304;
uint256 internal constant MAX_OUT_RATIO = 305;
uint256 internal constant MIN_BPT_IN_FOR_TOKEN_OUT = 306;
uint256 internal constant MAX_OUT_BPT_FOR_TOKEN_IN = 307;
uint256 internal constant NORMALIZED_WEIGHT_INVARIANT = 308;
uint256 internal constant INVALID_TOKEN = 309;
uint256 internal constant UNHANDLED_JOIN_KIND = 310;
uint256 internal constant ZERO_INVARIANT = 311;
uint256 internal constant ORACLE_INVALID_SECONDS_QUERY = 312;
uint256 internal constant ORACLE_NOT_INITIALIZED = 313;
uint256 internal constant ORACLE_QUERY_TOO_OLD = 314;
uint256 internal constant ORACLE_INVALID_INDEX = 315;
uint256 internal constant ORACLE_BAD_SECS = 316;
// Lib
uint256 internal constant REENTRANCY = 400;
uint256 internal constant SENDER_NOT_ALLOWED = 401;
uint256 internal constant PAUSED = 402;
uint256 internal constant PAUSE_WINDOW_EXPIRED = 403;
uint256 internal constant MAX_PAUSE_WINDOW_DURATION = 404;
uint256 internal constant MAX_BUFFER_PERIOD_DURATION = 405;
uint256 internal constant INSUFFICIENT_BALANCE = 406;
uint256 internal constant INSUFFICIENT_ALLOWANCE = 407;
uint256 internal constant ERC20_TRANSFER_FROM_ZERO_ADDRESS = 408;
uint256 internal constant ERC20_TRANSFER_TO_ZERO_ADDRESS = 409;
uint256 internal constant ERC20_MINT_TO_ZERO_ADDRESS = 410;
uint256 internal constant ERC20_BURN_FROM_ZERO_ADDRESS = 411;
uint256 internal constant ERC20_APPROVE_FROM_ZERO_ADDRESS = 412;
uint256 internal constant ERC20_APPROVE_TO_ZERO_ADDRESS = 413;
uint256 internal constant ERC20_TRANSFER_EXCEEDS_ALLOWANCE = 414;
uint256 internal constant ERC20_DECREASED_ALLOWANCE_BELOW_ZERO = 415;
uint256 internal constant ERC20_TRANSFER_EXCEEDS_BALANCE = 416;
uint256 internal constant ERC20_BURN_EXCEEDS_ALLOWANCE = 417;
uint256 internal constant SAFE_ERC20_CALL_FAILED = 418;
uint256 internal constant ADDRESS_INSUFFICIENT_BALANCE = 419;
uint256 internal constant ADDRESS_CANNOT_SEND_VALUE = 420;
uint256 internal constant SAFE_CAST_VALUE_CANT_FIT_INT256 = 421;
uint256 internal constant GRANT_SENDER_NOT_ADMIN = 422;
uint256 internal constant REVOKE_SENDER_NOT_ADMIN = 423;
uint256 internal constant RENOUNCE_SENDER_NOT_ALLOWED = 424;
uint256 internal constant BUFFER_PERIOD_EXPIRED = 425;
// Vault
uint256 internal constant INVALID_POOL_ID = 500;
uint256 internal constant CALLER_NOT_POOL = 501;
uint256 internal constant SENDER_NOT_ASSET_MANAGER = 502;
uint256 internal constant USER_DOESNT_ALLOW_RELAYER = 503;
uint256 internal constant INVALID_SIGNATURE = 504;
uint256 internal constant EXIT_BELOW_MIN = 505;
uint256 internal constant JOIN_ABOVE_MAX = 506;
uint256 internal constant SWAP_LIMIT = 507;
uint256 internal constant SWAP_DEADLINE = 508;
uint256 internal constant CANNOT_SWAP_SAME_TOKEN = 509;
uint256 internal constant UNKNOWN_AMOUNT_IN_FIRST_SWAP = 510;
uint256 internal constant MALCONSTRUCTED_MULTIHOP_SWAP = 511;
uint256 internal constant INTERNAL_BALANCE_OVERFLOW = 512;
uint256 internal constant INSUFFICIENT_INTERNAL_BALANCE = 513;
uint256 internal constant INVALID_ETH_INTERNAL_BALANCE = 514;
uint256 internal constant INVALID_POST_LOAN_BALANCE = 515;
uint256 internal constant INSUFFICIENT_ETH = 516;
uint256 internal constant UNALLOCATED_ETH = 517;
uint256 internal constant ETH_TRANSFER = 518;
uint256 internal constant CANNOT_USE_ETH_SENTINEL = 519;
uint256 internal constant TOKENS_MISMATCH = 520;
uint256 internal constant TOKEN_NOT_REGISTERED = 521;
uint256 internal constant TOKEN_ALREADY_REGISTERED = 522;
uint256 internal constant TOKENS_ALREADY_SET = 523;
uint256 internal constant TOKENS_LENGTH_MUST_BE_2 = 524;
uint256 internal constant NONZERO_TOKEN_BALANCE = 525;
uint256 internal constant BALANCE_TOTAL_OVERFLOW = 526;
uint256 internal constant POOL_NO_TOKENS = 527;
uint256 internal constant INSUFFICIENT_FLASH_LOAN_BALANCE = 528;
// Fees
uint256 internal constant SWAP_FEE_PERCENTAGE_TOO_HIGH = 600;
uint256 internal constant FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH = 601;
uint256 internal constant INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT = 602;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
_require(c >= a, Errors.ADD_OVERFLOW);
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, Errors.SUB_OVERFLOW);
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, uint256 errorCode) internal pure returns (uint256) {
_require(b <= a, errorCode);
uint256 c = a - b;
return c;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./IVault.sol";
import "./IPoolSwapStructs.sol";
/**
* @dev Interface for adding and removing liquidity that all Pool contracts should implement. Note that this is not
* the complete Pool contract interface, as it is missing the swap hooks. Pool contracts should also inherit from
* either IGeneralPool or IMinimalSwapInfoPool
*/
interface IBasePool is IPoolSwapStructs {
/**
* @dev Called by the Vault when a user calls `IVault.joinPool` to add liquidity to this Pool. Returns how many of
* each registered token the user should provide, as well as the amount of protocol fees the Pool owes to the Vault.
* The Vault will then take tokens from `sender` and add them to the Pool's balances, as well as collect
* the reported amount in protocol fees, which the pool should calculate based on `protocolSwapFeePercentage`.
*
* Protocol fees are reported and charged on join events so that the Pool is free of debt whenever new users join.
*
* `sender` is the account performing the join (from which tokens will be withdrawn), and `recipient` is the account
* designated to receive any benefits (typically pool shares). `currentBalances` contains the total balances
* for each token the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return.
*
* `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total
* balance.
*
* `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of
* join (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.)
*
* Contracts implementing this function should check that the caller is indeed the Vault before performing any
* state-changing operations, such as minting pool shares.
*/
function onJoinPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts);
/**
* @dev Called by the Vault when a user calls `IVault.exitPool` to remove liquidity from this Pool. Returns how many
* tokens the Vault should deduct from the Pool's balances, as well as the amount of protocol fees the Pool owes
* to the Vault. The Vault will then take tokens from the Pool's balances and send them to `recipient`,
* as well as collect the reported amount in protocol fees, which the Pool should calculate based on
* `protocolSwapFeePercentage`.
*
* Protocol fees are charged on exit events to guarantee that users exiting the Pool have paid their share.
*
* `sender` is the account performing the exit (typically the pool shareholder), and `recipient` is the account
* to which the Vault will send the proceeds. `currentBalances` contains the total token balances for each token
* the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return.
*
* `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total
* balance.
*
* `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of
* exit (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.)
*
* Contracts implementing this function should check that the caller is indeed the Vault before performing any
* state-changing operations, such as burning pool shares.
*/
function onExitPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../../lib/openzeppelin/IERC20.sol";
import "./IVault.sol";
interface IPoolSwapStructs {
// This is not really an interface - it just defines common structs used by other interfaces: IGeneralPool and
// IMinimalSwapInfoPool.
//
// This data structure represents a request for a token swap, where `kind` indicates the swap type ('given in' or
// 'given out') which indicates whether or not the amount sent by the pool is known.
//
// The pool receives `tokenIn` and sends `tokenOut`. `amount` is the number of `tokenIn` tokens the pool will take
// in, or the number of `tokenOut` tokens the Pool will send out, depending on the given swap `kind`.
//
// All other fields are not strictly necessary for most swaps, but are provided to support advanced scenarios in
// some Pools.
//
// `poolId` is the ID of the Pool involved in the swap - this is useful for Pool contracts that implement more than
// one Pool.
//
// The meaning of `lastChangeBlock` depends on the Pool specialization:
// - Two Token or Minimal Swap Info: the last block in which either `tokenIn` or `tokenOut` changed its total
// balance.
// - General: the last block in which *any* of the Pool's registered tokens changed its total balance.
//
// `from` is the origin address for the funds the Pool receives, and `to` is the destination address
// where the Pool sends the outgoing tokens.
//
// `userData` is extra data provided by the caller - typically a signature from a trusted party.
struct SwapRequest {
IVault.SwapKind kind;
IERC20 tokenIn;
IERC20 tokenOut;
uint256 amount;
// Misc data
bytes32 poolId;
uint256 lastChangeBlock;
address from;
address to;
bytes userData;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "../../lib/openzeppelin/IERC20.sol";
/**
* @dev Interface for the WETH token contract used internally for wrapping and unwrapping, to support
* sending and receiving ETH in joins, swaps, and internal balance deposits and withdrawals.
*/
interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 amount) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
/**
* @dev This is an empty interface used to represent either ERC20-conforming token contracts or ETH (using the zero
* address sentinel value). We're just relying on the fact that `interface` can be used to declare new address-like
* types.
*
* This concept is unrelated to a Pool's Asset Managers.
*/
interface IAsset {
// solhint-disable-previous-line no-empty-blocks
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
interface IAuthorizer {
/**
* @dev Returns true if `account` can perform the action described by `actionId` in the contract `where`.
*/
function canPerform(
bytes32 actionId,
address account,
address where
) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
// Inspired by Aave Protocol's IFlashLoanReceiver.
import "../../lib/openzeppelin/IERC20.sol";
interface IFlashLoanRecipient {
/**
* @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient.
*
* At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this
* call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the
* Vault, or else the entire flash loan will revert.
*
* `userData` is the same value passed in the `IVault.flashLoan` call.
*/
function receiveFlashLoan(
IERC20[] memory tokens,
uint256[] memory amounts,
uint256[] memory feeAmounts,
bytes memory userData
) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/openzeppelin/IERC20.sol";
import "../lib/helpers/InputHelpers.sol";
import "../lib/helpers/Authentication.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "./interfaces/IVault.sol";
import "./interfaces/IAuthorizer.sol";
/**
* @dev This an auxiliary contract to the Vault, deployed by it during construction. It offloads some of the tasks the
* Vault performs to reduce its overall bytecode size.
*
* The current values for all protocol fee percentages are stored here, and any tokens charged as protocol fees are
* sent to this contract, where they may be withdrawn by authorized entities. All authorization tasks are delegated
* to the Vault's own authorizer.
*/
contract ProtocolFeesCollector is Authentication, ReentrancyGuard {
using SafeERC20 for IERC20;
// Absolute maximum fee percentages (1e18 = 100%, 1e16 = 1%).
uint256 private constant _MAX_PROTOCOL_SWAP_FEE_PERCENTAGE = 50e16; // 50%
uint256 private constant _MAX_PROTOCOL_FLASH_LOAN_FEE_PERCENTAGE = 1e16; // 1%
IVault public immutable vault;
// All fee percentages are 18-decimal fixed point numbers.
// The swap fee is charged whenever a swap occurs, as a percentage of the fee charged by the Pool. These are not
// actually charged on each individual swap: the `Vault` relies on the Pools being honest and reporting fees due
// when users join and exit them.
uint256 private _swapFeePercentage;
// The flash loan fee is charged whenever a flash loan occurs, as a percentage of the tokens lent.
uint256 private _flashLoanFeePercentage;
event SwapFeePercentageChanged(uint256 newSwapFeePercentage);
event FlashLoanFeePercentageChanged(uint256 newFlashLoanFeePercentage);
constructor(IVault _vault)
// The ProtocolFeesCollector is a singleton, so it simply uses its own address to disambiguate action
// identifiers.
Authentication(bytes32(uint256(address(this))))
{
vault = _vault;
}
function withdrawCollectedFees(
IERC20[] calldata tokens,
uint256[] calldata amounts,
address recipient
) external nonReentrant authenticate {
InputHelpers.ensureInputLengthMatch(tokens.length, amounts.length);
for (uint256 i = 0; i < tokens.length; ++i) {
IERC20 token = tokens[i];
uint256 amount = amounts[i];
token.safeTransfer(recipient, amount);
}
}
function setSwapFeePercentage(uint256 newSwapFeePercentage) external authenticate {
_require(newSwapFeePercentage <= _MAX_PROTOCOL_SWAP_FEE_PERCENTAGE, Errors.SWAP_FEE_PERCENTAGE_TOO_HIGH);
_swapFeePercentage = newSwapFeePercentage;
emit SwapFeePercentageChanged(newSwapFeePercentage);
}
function setFlashLoanFeePercentage(uint256 newFlashLoanFeePercentage) external authenticate {
_require(
newFlashLoanFeePercentage <= _MAX_PROTOCOL_FLASH_LOAN_FEE_PERCENTAGE,
Errors.FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH
);
_flashLoanFeePercentage = newFlashLoanFeePercentage;
emit FlashLoanFeePercentageChanged(newFlashLoanFeePercentage);
}
function getSwapFeePercentage() external view returns (uint256) {
return _swapFeePercentage;
}
function getFlashLoanFeePercentage() external view returns (uint256) {
return _flashLoanFeePercentage;
}
function getCollectedFeeAmounts(IERC20[] memory tokens) external view returns (uint256[] memory feeAmounts) {
feeAmounts = new uint256[](tokens.length);
for (uint256 i = 0; i < tokens.length; ++i) {
feeAmounts[i] = tokens[i].balanceOf(address(this));
}
}
function getAuthorizer() external view returns (IAuthorizer) {
return _getAuthorizer();
}
function _canPerform(bytes32 actionId, address account) internal view override returns (bool) {
return _getAuthorizer().canPerform(actionId, account, address(this));
}
function _getAuthorizer() internal view returns (IAuthorizer) {
return vault.getAuthorizer();
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
/**
* @dev Interface for the SignatureValidator helper, used to support meta-transactions.
*/
interface ISignaturesValidator {
/**
* @dev Returns the EIP712 domain separator.
*/
function getDomainSeparator() external view returns (bytes32);
/**
* @dev Returns the next nonce used by an address to sign messages.
*/
function getNextNonce(address user) external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
/**
* @dev Interface for the TemporarilyPausable helper.
*/
interface ITemporarilyPausable {
/**
* @dev Emitted every time the pause state changes by `_setPaused`.
*/
event PausedStateChanged(bool paused);
/**
* @dev Returns the current paused state.
*/
function getPausedState()
external
view
returns (
bool paused,
uint256 pauseWindowEndTime,
uint256 bufferPeriodEndTime
);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "../openzeppelin/IERC20.sol";
import "./BalancerErrors.sol";
import "../../vault/interfaces/IAsset.sol";
library InputHelpers {
function ensureInputLengthMatch(uint256 a, uint256 b) internal pure {
_require(a == b, Errors.INPUT_LENGTH_MISMATCH);
}
function ensureInputLengthMatch(
uint256 a,
uint256 b,
uint256 c
) internal pure {
_require(a == b && b == c, Errors.INPUT_LENGTH_MISMATCH);
}
function ensureArrayIsSorted(IAsset[] memory array) internal pure {
address[] memory addressArray;
// solhint-disable-next-line no-inline-assembly
assembly {
addressArray := array
}
ensureArrayIsSorted(addressArray);
}
function ensureArrayIsSorted(IERC20[] memory array) internal pure {
address[] memory addressArray;
// solhint-disable-next-line no-inline-assembly
assembly {
addressArray := array
}
ensureArrayIsSorted(addressArray);
}
function ensureArrayIsSorted(address[] memory array) internal pure {
if (array.length < 2) {
return;
}
address previous = array[0];
for (uint256 i = 1; i < array.length; ++i) {
address current = array[i];
_require(previous < current, Errors.UNSORTED_ARRAY);
previous = current;
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "./BalancerErrors.sol";
import "./IAuthentication.sol";
/**
* @dev Building block for performing access control on external functions.
*
* This contract is used via the `authenticate` modifier (or the `_authenticateCaller` function), which can be applied
* to external functions to only make them callable by authorized accounts.
*
* Derived contracts must implement the `_canPerform` function, which holds the actual access control logic.
*/
abstract contract Authentication is IAuthentication {
bytes32 private immutable _actionIdDisambiguator;
/**
* @dev The main purpose of the `actionIdDisambiguator` is to prevent accidental function selector collisions in
* multi contract systems.
*
* There are two main uses for it:
* - if the contract is a singleton, any unique identifier can be used to make the associated action identifiers
* unique. The contract's own address is a good option.
* - if the contract belongs to a family that shares action identifiers for the same functions, an identifier
* shared by the entire family (and no other contract) should be used instead.
*/
constructor(bytes32 actionIdDisambiguator) {
_actionIdDisambiguator = actionIdDisambiguator;
}
/**
* @dev Reverts unless the caller is allowed to call this function. Should only be applied to external functions.
*/
modifier authenticate() {
_authenticateCaller();
_;
}
/**
* @dev Reverts unless the caller is allowed to call the entry point function.
*/
function _authenticateCaller() internal view {
bytes32 actionId = getActionId(msg.sig);
_require(_canPerform(actionId, msg.sender), Errors.SENDER_NOT_ALLOWED);
}
function getActionId(bytes4 selector) public view override returns (bytes32) {
// Each external function is dynamically assigned an action identifier as the hash of the disambiguator and the
// function selector. Disambiguation is necessary to avoid potential collisions in the function selectors of
// multiple contracts.
return keccak256(abi.encodePacked(_actionIdDisambiguator, selector));
}
function _canPerform(bytes32 actionId, address user) internal view virtual returns (bool);
}
// SPDX-License-Identifier: MIT
// Based on the ReentrancyGuard library from OpenZeppelin Contracts, altered to reduce bytecode size.
// Modifier code is inlined by the compiler, which causes its code to appear multiple times in the codebase. By using
// private functions, we achieve the same end result with slightly higher runtime gas costs, but reduced bytecode size.
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_enterNonReentrant();
_;
_exitNonReentrant();
}
function _enterNonReentrant() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
_require(_status != _ENTERED, Errors.REENTRANCY);
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _exitNonReentrant() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// Based on the ReentrancyGuard library from OpenZeppelin Contracts, altered to reduce gas costs.
// The `safeTransfer` and `safeTransferFrom` functions assume that `token` is a contract (an account with code), and
// work differently from the OpenZeppelin version if it is not.
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
import "./IERC20.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(address(token), abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(address(token), abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
*
* WARNING: `token` is assumed to be a contract: calls to EOAs will *not* revert.
*/
function _callOptionalReturn(address token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
(bool success, bytes memory returndata) = token.call(data);
// If the low-level call didn't succeed we return whatever was returned from it.
assembly {
if eq(success, 0) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
// Finally we check the returndata size is either zero or true - note that this check will always pass for EOAs
_require(returndata.length == 0 || abi.decode(returndata, (bool)), Errors.SAFE_ERC20_CALL_FAILED);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
interface IAuthentication {
/**
* @dev Returns the action identifier associated with the external function described by `selector`.
*/
function getActionId(bytes4 selector) external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow checks.
* Adapted from OpenZeppelin's SafeMath library
*/
library Math {
/**
* @dev Returns the addition of two unsigned integers of 256 bits, reverting on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
_require(c >= a, Errors.ADD_OVERFLOW);
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
_require((b >= 0 && c >= a) || (b < 0 && c < a), Errors.ADD_OVERFLOW);
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers of 256 bits, reverting on overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b <= a, Errors.SUB_OVERFLOW);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
_require((b >= 0 && c <= a) || (b < 0 && c > a), Errors.SUB_OVERFLOW);
return c;
}
/**
* @dev Returns the largest of two numbers of 256 bits.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers of 256 bits.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
_require(a == 0 || c / a == b, Errors.MUL_OVERFLOW);
return c;
}
function divDown(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
return a / b;
}
function divUp(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
if (a == 0) {
return 0;
} else {
return 1 + (a - 1) / b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over `owner`'s tokens,
* given `owner`'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
_HASHED_NAME = keccak256(bytes(name));
_HASHED_VERSION = keccak256(bytes(version));
_TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view virtual returns (bytes32) {
return keccak256(abi.encode(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION, _getChainId(), address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash));
}
function _getChainId() private view returns (uint256 chainId) {
// Silence state mutability warning without generating bytecode.
// See https://github.com/ethereum/solidity/issues/10090#issuecomment-741789128 and
// https://github.com/ethereum/solidity/issues/2691
this;
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
}
} | Set immutable state variables | _vault = vault;
| 106,473 | [
1,
694,
11732,
919,
3152,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
389,
26983,
273,
9229,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-04-25
*/
/*
-.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.-
-.--.--.-BLUEBIRD Decentralized Finance-.--.--.--.-
-.--.--.--.--.--.--.--.--.--.--.--.--.--.-.---.--.-
-.--.- FAIR LAUNCH, 70% BURN BEFORE LAUNCH-.--.--.-
-.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.-
-.--.-Buy/Sell Tax: 10%-.--.----.--.--.--.--.--.-.-
-.--.-Max Wallet: 2.5%-.--.--.--.--.--.--.--.--.--.
-.--.-Max TX: 1.5%-.--.--.--.--.--.--.--.--.--.--.-
-.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.-
- FAIR LAUNCH
- 70% BURN BEFORE LAUNCH
- 5 ETH LIQUIDITY POOL
- RENOUNCE AFTER LAUNCH
JOIN OUR TG: https://t.me/bluebirdtoken
LONG LIVE LORD ELON!
*/
pragma solidity 0.8.9;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this;
return msg.data;
}
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
contract ERC20 is Context, IERC20, IERC20Metadata {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract BLUEBIRD is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
address public constant deadAddress = address(0xdead);
bool private swapping;
address public marketingWallet;
address public devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
uint256 public percentForLPBurn = 1;
bool public lpBurnEnabled = false;
uint256 public lpBurnFrequency = 7200 seconds;
uint256 public lastLpBurnTime;
uint256 public manualBurnFrequency = 30 minutes;
uint256 public lastManualLpBurnTime;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
/******************/
// exlcude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet);
event devWalletUpdated(address indexed newWallet, address indexed oldWallet);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20("BLUEBIRD", "BLUEBIRD") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 8;
uint256 _buyLiquidityFee = 2;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 8;
uint256 _sellLiquidityFee = 2;
uint256 _sellDevFee = 0;
uint256 totalSupply = 1 * 1e8 * 1e18;
// 1.5% Max Transaction Size
maxTransactionAmount = totalSupply * 15 / 1000;
// 2.5% Max Wallet Size
maxWallet = totalSupply * 25 / 1000;
// 0.1% Minimum Swap
swapTokensAtAmount = totalSupply * 10 / 10000;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
marketingWallet = address(owner());
devWallet = address(owner());
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(msg.sender, totalSupply);
}
receive() external payable {
}
// once enabled, can never be turned off
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
lastLpBurnTime = block.timestamp;
}
// remove limits after token is stable
function removeLimits() external onlyOwner returns (bool){
limitsInEffect = false;
return true;
}
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool){
transferDelayEnabled = false;
return true;
}
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){
require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply.");
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 1 / 100000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%");
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%");
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(address newMarketingWallet) external onlyOwner {
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
// at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
//when buy
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
//when sell
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
// only take fees on buys/sells, do not take on wallet transfers
if(takeFee){
// on sell
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
// on buy
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
deadAddress,
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
// Halve the amount of liquidity tokens
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
(success,) = address(devWallet).call{value: ethForDev}("");
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
(success,) = address(marketingWallet).call{value: address(this).balance}("");
}
} | at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.when buywhen sell if any account belongs to _isExcludedFromFee account then remove the fee only take fees on buys/sells, do not take on wallet transfers on sell on buy | function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
| 2,335,462 | [
1,
270,
8037,
309,
326,
7412,
4624,
353,
3696,
16,
3387,
326,
1203,
11267,
364,
5405,
343,
345,
414,
353,
444,
1493,
4982,
8037,
18,
13723,
30143,
13723,
357,
80,
309,
1281,
2236,
11081,
358,
389,
291,
16461,
1265,
14667,
2236,
1508,
1206,
326,
14036,
1338,
4862,
1656,
281,
603,
25666,
1900,
19,
87,
1165,
87,
16,
741,
486,
4862,
603,
9230,
29375,
603,
357,
80,
603,
30143,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
13866,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
2713,
3849,
288,
203,
3639,
2583,
12,
2080,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
628,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
869,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
358,
326,
3634,
1758,
8863,
203,
540,
203,
540,
309,
12,
8949,
422,
374,
13,
288,
203,
5411,
2240,
6315,
13866,
12,
2080,
16,
358,
16,
374,
1769,
203,
5411,
327,
31,
203,
3639,
289,
203,
540,
203,
3639,
309,
12,
14270,
382,
12477,
15329,
203,
5411,
309,
261,
203,
7734,
628,
480,
3410,
1435,
597,
203,
7734,
358,
480,
3410,
1435,
597,
203,
7734,
358,
480,
1758,
12,
20,
13,
597,
203,
7734,
358,
480,
1758,
12,
20,
92,
22097,
13,
597,
203,
7734,
401,
22270,
1382,
203,
5411,
262,
95,
203,
7734,
309,
12,
5,
313,
14968,
3896,
15329,
203,
10792,
2583,
24899,
291,
16461,
1265,
2954,
281,
63,
2080,
65,
747,
389,
291,
16461,
1265,
2954,
281,
63,
869,
6487,
315,
1609,
7459,
353,
486,
2695,
1199,
1769,
203,
7734,
289,
203,
203,
7734,
309,
261,
13866,
6763,
1526,
15329,
203,
10792,
309,
261,
869,
480,
3410,
1435,
597,
358,
480,
1758,
12,
318,
291,
91,
438,
58,
22,
8259,
13,
597,
358,
480,
1758,
12,
318,
291,
91,
438,
58,
22,
4154,
3719,
95,
203,
13491,
2583,
24899,
4505,
3024,
5912,
4921,
63,
978,
18,
10012,
65,
2
] |
// SPDX-License-Identifier: MIT
// Universe.sol -- Part of the Charged Particles Protocol
// Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
pragma solidity 0.6.12;
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "./interfaces/IUniverse.sol";
import "./interfaces/IChargedParticles.sol";
import "./interfaces/ILepton.sol";
import "./lib/TokenInfo.sol";
import "./lib/BlackholePrevention.sol";
/**
* @notice Charged Particles Universe Contract
* @dev Upgradeable Contract
*/
contract Universe is IUniverse, Initializable, OwnableUpgradeable, BlackholePrevention {
using SafeMathUpgradeable for uint256;
using TokenInfo for address;
using SafeERC20Upgradeable for IERC20Upgradeable;
// The ChargedParticles Contract Address
address public chargedParticles;
address public proton;
address public lepton;
address public quark;
address public boson;
uint256 constant internal PERCENTAGE_SCALE = 1e4; // 10000 (100%)
// Positive Charge
uint256 internal photonMaxSupply;
uint256 internal totalPhotonDischarged;
// Source of Positive Charge
IERC20Upgradeable public photonSource;
// Asset Token => Electrostatic Attraction Multiplier
mapping (address => uint256) internal esaMultiplier;
// Account => Electrostatic Attraction Levels
mapping (address => uint256) internal esaLevel;
// Energizing Account => Referral Source
mapping (address => address) internal referralSource;
// NFT Token UUID => Bonded Lepton Mass
mapping (uint256 => uint256) internal bondedLeptonMass;
/***********************************|
| Initialization |
|__________________________________*/
function initialize() public initializer {
__Ownable_init();
}
/***********************************|
| Public Functions |
|__________________________________*/
function getStaticCharge(address account) external view virtual returns (uint256 positiveEnergy) {
return esaLevel[account];
}
function conductElectrostaticDischarge(address account, uint256 amount) external virtual returns (uint256 positiveEnergy) {
require(esaLevel[account] > 0, "UNI:E-411");
require(photonSource.balanceOf(address(this)) > 0, "UNI:E-413");
return _conductElectrostaticDischarge(account, amount);
}
/***********************************|
| Only Charged Particles |
|__________________________________*/
function onEnergize(
address sender,
address referrer,
address /* contractAddress */,
uint256 /* tokenId */,
string calldata /* walletManagerId */,
address /* assetToken */,
uint256 /* assetAmount */
)
external
virtual
override
onlyChargedParticles
{
if (referralSource[sender] == address(0x0) && referrer != address(0x0)) {
referralSource[sender] = referrer;
}
}
function onDischarge(
address contractAddress,
uint256 tokenId,
string calldata,
address assetToken,
uint256 creatorEnergy,
uint256 receiverEnergy
)
external
virtual
override
onlyChargedParticles
{
if (esaMultiplier[assetToken] > 0 && receiverEnergy > 0) {
uint256 tokenUuid = contractAddress.getTokenUUID(tokenId);
address nftOwner = IERC721Upgradeable(contractAddress).ownerOf(tokenId);
_electrostaticAttraction(tokenUuid, nftOwner, assetToken, creatorEnergy.add(receiverEnergy));
}
}
function onDischargeForCreator(
address contractAddress,
uint256 tokenId,
string calldata,
address /* creator */,
address assetToken,
uint256 receiverEnergy
)
external
virtual
override
onlyChargedParticles
{
if (esaMultiplier[assetToken] > 0 && receiverEnergy > 0) {
uint256 tokenUuid = contractAddress.getTokenUUID(tokenId);
address nftOwner = IERC721Upgradeable(contractAddress).ownerOf(tokenId);
_electrostaticAttraction(tokenUuid, nftOwner, assetToken, receiverEnergy);
}
}
function onRelease(
address contractAddress,
uint256 tokenId,
string calldata,
address assetToken,
uint256 principalAmount,
uint256 creatorEnergy,
uint256 receiverEnergy
)
external
virtual
override
onlyChargedParticles
{
uint256 totalEnergy = creatorEnergy.add(receiverEnergy);
if (esaMultiplier[assetToken] > 0 && totalEnergy > principalAmount) {
uint256 tokenUuid = contractAddress.getTokenUUID(tokenId);
address nftOwner = IERC721Upgradeable(contractAddress).ownerOf(tokenId);
_electrostaticAttraction(tokenUuid, nftOwner, assetToken, totalEnergy.sub(principalAmount));
}
}
function onCovalentBond(
address contractAddress,
uint256 tokenId,
string calldata /* managerId */,
address nftTokenAddress,
uint256 nftTokenId
)
external
virtual
override
onlyChargedParticles
{
if (lepton != address(0x0) && nftTokenAddress == lepton) {
uint256 tokenUuid = contractAddress.getTokenUUID(tokenId);
bondedLeptonMass[tokenUuid] = ILepton(nftTokenAddress).getMultiplier(nftTokenId);
}
}
function onCovalentBreak(
address contractAddress,
uint256 tokenId,
string calldata /* managerId */,
address nftTokenAddress,
uint256 /* nftTokenId */
)
external
virtual
override
onlyChargedParticles
{
if (lepton != address(0x0) && nftTokenAddress == lepton) {
uint256 tokenUuid = contractAddress.getTokenUUID(tokenId);
delete bondedLeptonMass[tokenUuid];
}
}
function onProtonSale(
address contractAddress,
uint256 tokenId,
address oldOwner,
address newOwner,
uint256 salePrice,
address creator,
uint256 creatorRoyalties
)
external
virtual
override
onlyProton
{
// no-op
}
/***********************************|
| Only Admin/DAO |
|__________________________________*/
function setChargedParticles(
address controller
)
external
virtual
onlyOwner
onlyValidContractAddress(controller)
{
chargedParticles = controller;
emit ChargedParticlesSet(controller);
}
function setPhoton(
address token,
uint256 maxSupply
)
external
virtual
onlyOwner
onlyValidContractAddress(token)
{
photonSource = IERC20Upgradeable(token);
photonMaxSupply = maxSupply;
emit PhotonSet(token, maxSupply);
}
function setProtonToken(
address token
)
external
virtual
onlyOwner
onlyValidContractAddress(token)
{
proton = token;
emit ProtonTokenSet(token);
}
function setLeptonToken(
address token
)
external
virtual
onlyOwner
onlyValidContractAddress(token)
{
lepton = token;
emit LeptonTokenSet(token);
}
function setQuarkToken(
address token
)
external
virtual
onlyOwner
onlyValidContractAddress(token)
{
quark = token;
emit QuarkTokenSet(token);
}
function setBosonToken(
address token
)
external
virtual
onlyOwner
onlyValidContractAddress(token)
{
boson = token;
emit BosonTokenSet(token);
}
function setEsaMultiplier(
address assetToken,
uint256 multiplier
)
external
virtual
onlyOwner
{
esaMultiplier[assetToken] = multiplier;
emit EsaMultiplierSet(assetToken, multiplier);
}
function withdrawEther(address payable receiver, uint256 amount) external virtual onlyOwner {
_withdrawEther(receiver, amount);
}
function withdrawErc20(address payable receiver, address tokenAddress, uint256 amount) external virtual onlyOwner {
_withdrawERC20(receiver, tokenAddress, amount);
}
function withdrawERC721(address payable receiver, address tokenAddress, uint256 tokenId) external virtual onlyOwner {
_withdrawERC721(receiver, tokenAddress, tokenId);
}
/***********************************|
| Private Functions |
|__________________________________*/
function _electrostaticAttraction(uint256 tokenUuid, address receiver, address assetToken, uint256 baseAmount) internal virtual {
if (address(photonSource) == address(0x0) || receiver == address(0x0)) { return; }
if (totalPhotonDischarged >= photonMaxSupply) { return; }
uint256 energy = baseAmount.mul(esaMultiplier[assetToken]).div(PERCENTAGE_SCALE);
uint256 bondedMass = bondedLeptonMass[tokenUuid];
if (bondedMass > 0) {
energy = energy.mul(bondedMass.add(PERCENTAGE_SCALE)).div(PERCENTAGE_SCALE);
}
if (totalPhotonDischarged.add(energy) > photonMaxSupply) {
energy = photonMaxSupply.sub(totalPhotonDischarged);
}
totalPhotonDischarged = totalPhotonDischarged.add(energy);
esaLevel[receiver] = esaLevel[receiver].add(energy);
emit ElectrostaticAttraction(receiver, address(photonSource), energy, bondedMass);
}
function _conductElectrostaticDischarge(address account, uint256 energy) internal virtual returns (uint256) {
uint256 electrostaticAttraction = esaLevel[account];
if (energy > electrostaticAttraction) {
energy = electrostaticAttraction;
}
uint256 bondable = photonSource.balanceOf(address(this));
if (energy > bondable) {
energy = bondable;
}
esaLevel[account] = esaLevel[account].sub(energy);
photonSource.safeTransfer(account, energy);
emit ElectrostaticDischarge(account, address(photonSource), energy);
return energy;
}
/***********************************|
| Modifiers |
|__________________________________*/
/// @dev Throws if called by any non-account
modifier onlyValidContractAddress(address account) {
require(account != address(0x0) && account.isContract(), "UNI:E-417");
_;
}
/// @dev Throws if called by any account other than the Charged Particles contract
modifier onlyChargedParticles() {
require(chargedParticles == msg.sender, "UNI:E-108");
_;
}
/// @dev Throws if called by any account other than the Proton NFT contract
modifier onlyProton() {
require(proton == msg.sender, "UNI:E-110");
_;
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
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 SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.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 SafeMathUpgradeable for uint256;
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).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20Upgradeable 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(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: MIT
// IUniverse.sol -- Part of the Charged Particles Protocol
// Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
pragma solidity >=0.6.0;
/**
* @title Universal Controller interface
* @dev ...
*/
interface IUniverse {
event ChargedParticlesSet(address indexed chargedParticles);
event PhotonSet(address indexed photonToken, uint256 maxSupply);
event ProtonTokenSet(address indexed protonToken);
event LeptonTokenSet(address indexed leptonToken);
event QuarkTokenSet(address indexed quarkToken);
event BosonTokenSet(address indexed bosonToken);
event EsaMultiplierSet(address indexed assetToken, uint256 multiplier);
event ElectrostaticAttraction(address indexed account, address photonSource, uint256 energy, uint256 multiplier);
event ElectrostaticDischarge(address indexed account, address photonSource, uint256 energy);
function onEnergize(
address sender,
address referrer,
address contractAddress,
uint256 tokenId,
string calldata managerId,
address assetToken,
uint256 assetEnergy
) external;
function onDischarge(
address contractAddress,
uint256 tokenId,
string calldata managerId,
address assetToken,
uint256 creatorEnergy,
uint256 receiverEnergy
) external;
function onDischargeForCreator(
address contractAddress,
uint256 tokenId,
string calldata managerId,
address creator,
address assetToken,
uint256 receiverEnergy
) external;
function onRelease(
address contractAddress,
uint256 tokenId,
string calldata managerId,
address assetToken,
uint256 principalEnergy,
uint256 creatorEnergy,
uint256 receiverEnergy
) external;
function onCovalentBond(
address contractAddress,
uint256 tokenId,
string calldata managerId,
address nftTokenAddress,
uint256 nftTokenId
) external;
function onCovalentBreak(
address contractAddress,
uint256 tokenId,
string calldata managerId,
address nftTokenAddress,
uint256 nftTokenId
) external;
function onProtonSale(
address contractAddress,
uint256 tokenId,
address oldOwner,
address newOwner,
uint256 salePrice,
address creator,
uint256 creatorRoyalties
) external;
}
// SPDX-License-Identifier: MIT
// IChargedParticles.sol -- Part of the Charged Particles Protocol
// Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
pragma solidity >=0.6.0;
/**
* @notice Interface for Charged Particles
*/
interface IChargedParticles {
/***********************************|
| Public API |
|__________________________________*/
function getStateAddress() external view returns (address stateAddress);
function getSettingsAddress() external view returns (address settingsAddress);
function baseParticleMass(address contractAddress, uint256 tokenId, string calldata walletManagerId, address assetToken) external returns (uint256);
function currentParticleCharge(address contractAddress, uint256 tokenId, string calldata walletManagerId, address assetToken) external returns (uint256);
function currentParticleKinetics(address contractAddress, uint256 tokenId, string calldata walletManagerId, address assetToken) external returns (uint256);
function currentParticleCovalentBonds(address contractAddress, uint256 tokenId, string calldata basketManagerId) external view returns (uint256);
/***********************************|
| Particle Mechanics |
|__________________________________*/
function energizeParticle(
address contractAddress,
uint256 tokenId,
string calldata walletManagerId,
address assetToken,
uint256 assetAmount,
address referrer
) external returns (uint256 yieldTokensAmount);
function dischargeParticle(
address receiver,
address contractAddress,
uint256 tokenId,
string calldata walletManagerId,
address assetToken
) external returns (uint256 creatorAmount, uint256 receiverAmount);
function dischargeParticleAmount(
address receiver,
address contractAddress,
uint256 tokenId,
string calldata walletManagerId,
address assetToken,
uint256 assetAmount
) external returns (uint256 creatorAmount, uint256 receiverAmount);
function dischargeParticleForCreator(
address receiver,
address contractAddress,
uint256 tokenId,
string calldata walletManagerId,
address assetToken,
uint256 assetAmount
) external returns (uint256 receiverAmount);
function releaseParticle(
address receiver,
address contractAddress,
uint256 tokenId,
string calldata walletManagerId,
address assetToken
) external returns (uint256 creatorAmount, uint256 receiverAmount);
function releaseParticleAmount(
address receiver,
address contractAddress,
uint256 tokenId,
string calldata walletManagerId,
address assetToken,
uint256 assetAmount
) external returns (uint256 creatorAmount, uint256 receiverAmount);
function covalentBond(
address contractAddress,
uint256 tokenId,
string calldata basketManagerId,
address nftTokenAddress,
uint256 nftTokenId
) external returns (bool success);
function breakCovalentBond(
address receiver,
address contractAddress,
uint256 tokenId,
string calldata basketManagerId,
address nftTokenAddress,
uint256 nftTokenId
) external returns (bool success);
/***********************************|
| Particle Events |
|__________________________________*/
event UniverseSet(address indexed universeAddress);
event ChargedStateSet(address indexed chargedState);
event ChargedSettingsSet(address indexed chargedSettings);
event LeptonTokenSet(address indexed leptonToken);
}
// SPDX-License-Identifier: MIT
// ILepton.sol -- Part of the Charged Particles Protocol
// Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
pragma solidity >=0.6.0;
/**
* @title Charged Particles Lepton Interface
* @dev ...
*/
interface ILepton {
struct Classification {
string tokenUri;
uint256 price;
uint128 _upperBounds;
uint32 supply;
uint32 multiplier;
uint32 bonus;
}
function mintLepton() external payable returns (uint256 newTokenId);
function batchMintLepton(uint256 count) external payable;
function getNextType() external view returns (uint256);
function getNextPrice() external view returns (uint256);
function getMultiplier(uint256 tokenId) external view returns (uint256);
function getBonus(uint256 tokenId) external view returns (uint256);
event MaxMintPerTxSet(uint256 maxAmount);
event LeptonTypeAdded(string tokenUri, uint256 price, uint32 supply, uint32 multiplier, uint32 bonus, uint256 upperBounds);
event LeptonTypeUpdated(uint256 leptonIndex, string tokenUri, uint256 price, uint32 supply, uint32 multiplier, uint32 bonus, uint256 upperBounds);
event LeptonMinted(address indexed receiver, uint256 indexed tokenId, uint256 price, uint32 multiplier);
event LeptonBatchMinted(address indexed receiver, uint256 indexed tokenId, uint256 count, uint256 price, uint32 multiplier);
event PausedStateSet(bool isPaused);
}
// SPDX-License-Identifier: MIT
// TokenInfo.sol -- Part of the Charged Particles Protocol
// Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
pragma solidity 0.6.12;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "../interfaces/IERC721Chargeable.sol";
library TokenInfo {
function getTokenUUID(address contractAddress, uint256 tokenId) internal pure virtual returns (uint256) {
return uint256(keccak256(abi.encodePacked(contractAddress, tokenId)));
}
function getTokenOwner(address contractAddress, uint256 tokenId) internal view virtual returns (address) {
IERC721Chargeable tokenInterface = IERC721Chargeable(contractAddress);
return tokenInterface.ownerOf(tokenId);
}
function getTokenCreator(address contractAddress, uint256 tokenId) internal view virtual returns (address) {
IERC721Chargeable tokenInterface = IERC721Chargeable(contractAddress);
return tokenInterface.creatorOf(tokenId);
}
/// @dev Checks if an account is the Owner of an External NFT contract
/// @param contractAddress The Address to the Contract of the NFT to check
/// @param account The Address of the Account to check
/// @return True if the account owns the contract
function isContractOwner(address contractAddress, address account) internal view virtual returns (bool) {
address contractOwner = IERC721Chargeable(contractAddress).owner();
return contractOwner != address(0x0) && contractOwner == account;
}
/// @dev Checks if an account is the Creator of a Proton-based NFT
/// @param contractAddress The Address to the Contract of the Proton-based NFT to check
/// @param tokenId The Token ID of the Proton-based NFT to check
/// @param sender The Address of the Account to check
/// @return True if the account is the creator of the Proton-based NFT
function isTokenCreator(address contractAddress, uint256 tokenId, address sender) internal view virtual returns (bool) {
IERC721Chargeable tokenInterface = IERC721Chargeable(contractAddress);
address tokenCreator = tokenInterface.creatorOf(tokenId);
return (sender == tokenCreator);
}
/// @dev Checks if an account is the Creator of a Proton-based NFT or the Contract itself
/// @param contractAddress The Address to the Contract of the Proton-based NFT to check
/// @param tokenId The Token ID of the Proton-based NFT to check
/// @param sender The Address of the Account to check
/// @return True if the account is the creator of the Proton-based NFT or the Contract itself
function isTokenContractOrCreator(address contractAddress, uint256 tokenId, address creator, address sender) internal view virtual returns (bool) {
IERC721Chargeable tokenInterface = IERC721Chargeable(contractAddress);
address tokenCreator = tokenInterface.creatorOf(tokenId);
if (sender == contractAddress && creator == tokenCreator) { return true; }
return (sender == tokenCreator);
}
/// @dev Checks if an account is the Owner or Operator of an External NFT
/// @param contractAddress The Address to the Contract of the External NFT to check
/// @param tokenId The Token ID of the External NFT to check
/// @param sender The Address of the Account to check
/// @return True if the account is the Owner or Operator of the External NFT
function isErc721OwnerOrOperator(address contractAddress, uint256 tokenId, address sender) internal view virtual returns (bool) {
IERC721Chargeable tokenInterface = IERC721Chargeable(contractAddress);
address tokenOwner = tokenInterface.ownerOf(tokenId);
return (sender == tokenOwner || tokenInterface.isApprovedForAll(tokenOwner, sender));
}
/**
* @dev Returns true if `account` is a contract.
* @dev Taken from OpenZeppelin library
*
* [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.
* @dev Taken from OpenZeppelin library
*
* 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, "TokenInfo: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "TokenInfo: unable to send value, recipient may have reverted");
}
}
// SPDX-License-Identifier: MIT
// BlackholePrevention.sol -- Part of the Charged Particles Protocol
// Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
pragma solidity >=0.6.0;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
/**
* @notice Prevents ETH or Tokens from getting stuck in a contract by allowing
* the Owner/DAO to pull them out on behalf of a user
* This is only meant to contracts that are not expected to hold tokens, but do handle transferring them.
*/
contract BlackholePrevention {
using Address for address payable;
using SafeERC20 for IERC20;
event WithdrawStuckEther(address indexed receiver, uint256 amount);
event WithdrawStuckERC20(address indexed receiver, address indexed tokenAddress, uint256 amount);
event WithdrawStuckERC721(address indexed receiver, address indexed tokenAddress, uint256 indexed tokenId);
function _withdrawEther(address payable receiver, uint256 amount) internal virtual {
require(receiver != address(0x0), "BHP:E-403");
if (address(this).balance >= amount) {
receiver.sendValue(amount);
emit WithdrawStuckEther(receiver, amount);
}
}
function _withdrawERC20(address payable receiver, address tokenAddress, uint256 amount) internal virtual {
require(receiver != address(0x0), "BHP:E-403");
if (IERC20(tokenAddress).balanceOf(address(this)) >= amount) {
IERC20(tokenAddress).safeTransfer(receiver, amount);
emit WithdrawStuckERC20(receiver, tokenAddress, amount);
}
}
function _withdrawERC721(address payable receiver, address tokenAddress, uint256 tokenId) internal virtual {
require(receiver != address(0x0), "BHP:E-403");
if (IERC721(tokenAddress).ownerOf(tokenId) == address(this)) {
IERC721(tokenAddress).transferFrom(address(this), receiver, tokenId);
emit WithdrawStuckERC721(receiver, tokenAddress, tokenId);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <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.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.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 IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// IERC721Chargeable.sol -- Part of the Charged Particles Protocol
// Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
pragma solidity >=0.6.0;
import "@openzeppelin/contracts-upgradeable/introspection/IERC165Upgradeable.sol";
interface IERC721Chargeable is IERC165Upgradeable {
function owner() external view returns (address);
function creatorOf(uint256 tokenId) external view returns (address);
function balanceOf(address tokenOwner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address tokenOwner);
function safeTransferFrom(address from, address to, uint256 tokenId) external;
function transferFrom(address from, address to, uint256 tokenId) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address tokenOwner, address operator) external view returns (bool);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// 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);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transfered 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.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the 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);
} | * @title Charged Particles Lepton Interface @dev .../ | interface ILepton {
}
struct Classification {
string tokenUri;
uint256 price;
uint128 _upperBounds;
uint32 supply;
uint32 multiplier;
uint32 bonus;
}
}
| 14,738,675 | [
1,
2156,
2423,
6393,
8383,
3519,
337,
265,
6682,
225,
1372,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5831,
467,
1682,
337,
265,
288,
203,
203,
97,
203,
203,
203,
225,
1958,
1659,
1480,
288,
203,
565,
533,
1147,
3006,
31,
203,
565,
2254,
5034,
6205,
31,
203,
565,
2254,
10392,
389,
5797,
5694,
31,
203,
565,
2254,
1578,
14467,
31,
203,
565,
2254,
1578,
15027,
31,
203,
565,
2254,
1578,
324,
22889,
31,
203,
225,
289,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xE5fEB62FB34aDbA661B7c8256887a8B9a21C2278/sources/contracts/core/SoundEditionV1_1.sol | * @inheritdoc ISoundEditionV1_1/ | function withdrawERC20(address[] calldata tokens) external {
unchecked {
uint256 n = tokens.length;
uint256[] memory amounts = new uint256[](n);
for (uint256 i; i != n; ++i) {
uint256 amount = IERC20(tokens[i]).balanceOf(address(this));
SafeTransferLib.safeTransfer(tokens[i], fundingRecipient, amount);
amounts[i] = amount;
}
emit ERC20Withdrawn(fundingRecipient, tokens, amounts, msg.sender);
}
}
| 3,644,436 | [
1,
36,
10093,
4437,
772,
41,
1460,
58,
21,
67,
21,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
598,
9446,
654,
39,
3462,
12,
2867,
8526,
745,
892,
2430,
13,
3903,
288,
203,
3639,
22893,
288,
203,
5411,
2254,
5034,
290,
273,
2430,
18,
2469,
31,
203,
5411,
2254,
5034,
8526,
3778,
30980,
273,
394,
2254,
5034,
8526,
12,
82,
1769,
203,
5411,
364,
261,
11890,
5034,
277,
31,
277,
480,
290,
31,
965,
77,
13,
288,
203,
7734,
2254,
5034,
3844,
273,
467,
654,
39,
3462,
12,
7860,
63,
77,
65,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
7734,
14060,
5912,
5664,
18,
4626,
5912,
12,
7860,
63,
77,
6487,
22058,
18241,
16,
3844,
1769,
203,
7734,
30980,
63,
77,
65,
273,
3844,
31,
203,
5411,
289,
203,
5411,
3626,
4232,
39,
3462,
1190,
9446,
82,
12,
74,
14351,
18241,
16,
2430,
16,
30980,
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
] |
./full_match/1/0x8fc72dcfbf39FE686c96f47C697663EE08C78380/sources/contracts/ZunamiBaseAPS.sol | * @dev Returns total holdings for all pools (strategy's) @return Returns sum holdings (USD) for all pools/ | function totalHoldings() public view returns (uint256) {
uint256 length = _poolInfo.length;
uint256 totalHold = 0;
for (uint256 pid = 0; pid < length; pid++) {
PoolInfo memory poolInfo_ = _poolInfo[pid];
if (poolInfo_.lpShares > 0) {
totalHold += poolInfo_.strategy.totalHoldings();
}
}
return totalHold;
}
| 4,944,114 | [
1,
1356,
2078,
6887,
899,
364,
777,
16000,
261,
14914,
1807,
13,
327,
2860,
2142,
6887,
899,
261,
3378,
40,
13,
364,
777,
16000,
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,
2078,
20586,
899,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
769,
273,
389,
6011,
966,
18,
2469,
31,
203,
3639,
2254,
5034,
2078,
20586,
273,
374,
31,
203,
3639,
364,
261,
11890,
5034,
4231,
273,
374,
31,
4231,
411,
769,
31,
4231,
27245,
288,
203,
5411,
8828,
966,
3778,
2845,
966,
67,
273,
389,
6011,
966,
63,
6610,
15533,
203,
5411,
309,
261,
6011,
966,
27799,
9953,
24051,
405,
374,
13,
288,
203,
7734,
2078,
20586,
1011,
2845,
966,
27799,
14914,
18,
4963,
20586,
899,
5621,
203,
5411,
289,
203,
3639,
289,
203,
3639,
327,
2078,
20586,
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
] |
./full_match/97/0x9B718b515B024015715D36C8551d839daF631EB3/sources/project_/contracts/diamond/libraries/LibPairsManager.sol | todo: 后面改回 apollox.pairs.manager.storage | library LibPairsManager {
bytes32 constant PAIRS_MANAGER_STORAGE_POSITION = keccak256("apollox.pairs.manager.storage.20230217");
tier notionalUsd maxLeverage initialLostP liqLostP
1 (0 ~ 10,000] 20 95% 97.5%
2 (10,000 ~ 50,000] 10 90% 95%
3 (50,000 ~ 100,000] 5 80% 90%
4 (100,000 ~ 200,000] 3 75% 85%
5 (200,000 ~ 500,000] 2 60% 75%
6 (500,000 ~ 800,000] 1 40% 50%
pragma solidity ^0.8.18;
struct LeverageMargin {
uint16 tier;
uint256 notionalUsd;
uint16 maxLeverage;
}
struct SlippageConfig {
string name;
uint256 onePercentDepthAboveUsd;
uint256 onePercentDepthBelowUsd;
uint16 index;
IPairsManager.SlippageType slippageType;
bool enable;
}
struct Pair {
string name;
address base;
uint16 basePosition;
IPairsManager.PairType pairType;
IPairsManager.PairStatus status;
uint16 slippageConfigIndex;
uint16 slippagePosition;
uint16 feeConfigIndex;
uint16 feePosition;
uint256 maxLongOiUsd;
uint256 maxShortOiUsd;
uint16 maxTier;
mapping(uint16 => LeverageMargin) leverageMargins;
}
struct PairsManagerStorage {
mapping(uint16 => SlippageConfig) slippageConfigs;
mapping(uint16 => address[]) slippageConfigPairs;
mapping(address => Pair) pairs;
address[] pairBases;
}
function pairsManagerStorage() internal pure returns (PairsManagerStorage storage pms) {
bytes32 position = PAIRS_MANAGER_STORAGE_POSITION;
assembly {
pms.slot := position
}
}
event AddSlippageConfig(
uint16 indexed index, IPairsManager.SlippageType indexed slippageType,
uint256 onePercentDepthAboveUsd, uint256 onePercentDepthBelowUsd,
uint16 slippageLongP, uint16 slippageShortP, string name
);
event RemoveSlippageConfig(uint16 indexed index);
event UpdateSlippageConfig(
uint16 indexed index,
SlippageConfig oldConfig, SlippageConfig config
);
event AddPair(
address indexed base,
IPairsManager.PairType indexed pairType,
uint256 maxLongOiUsd, uint256 maxShortOiUsd,
uint16 slippageConfigIndex, uint16 feeConfigIndex,
string name, LeverageMargin[] leverageMargins
);
event RemovePair(address indexed base);
event UpdatePairStatus(
address indexed base,
IPairsManager.PairStatus indexed oldStatus,
IPairsManager.PairStatus indexed status
);
event UpdatePairSlippage(address indexed base, uint16 indexed oldSlippageConfigIndexed, uint16 indexed slippageConfigIndex);
event UpdatePairFee(address indexed base, uint16 indexed oldfeeConfigIndex, uint16 indexed feeConfigIndex);
event UpdatePairLeverageMargin(
address indexed base,
LeverageMargin[] oldLeverageMargins,
LeverageMargin[] leverageMargins
);
function pairsManagerStorage() internal pure returns (PairsManagerStorage storage pms) {
bytes32 position = PAIRS_MANAGER_STORAGE_POSITION;
assembly {
pms.slot := position
}
}
event AddSlippageConfig(
uint16 indexed index, IPairsManager.SlippageType indexed slippageType,
uint256 onePercentDepthAboveUsd, uint256 onePercentDepthBelowUsd,
uint16 slippageLongP, uint16 slippageShortP, string name
);
event RemoveSlippageConfig(uint16 indexed index);
event UpdateSlippageConfig(
uint16 indexed index,
SlippageConfig oldConfig, SlippageConfig config
);
event AddPair(
address indexed base,
IPairsManager.PairType indexed pairType,
uint256 maxLongOiUsd, uint256 maxShortOiUsd,
uint16 slippageConfigIndex, uint16 feeConfigIndex,
string name, LeverageMargin[] leverageMargins
);
event RemovePair(address indexed base);
event UpdatePairStatus(
address indexed base,
IPairsManager.PairStatus indexed oldStatus,
IPairsManager.PairStatus indexed status
);
event UpdatePairSlippage(address indexed base, uint16 indexed oldSlippageConfigIndexed, uint16 indexed slippageConfigIndex);
event UpdatePairFee(address indexed base, uint16 indexed oldfeeConfigIndex, uint16 indexed feeConfigIndex);
event UpdatePairLeverageMargin(
address indexed base,
LeverageMargin[] oldLeverageMargins,
LeverageMargin[] leverageMargins
);
function addSlippageConfig(
uint16 index, string calldata name, IPairsManager.SlippageType slippageType,
uint256 onePercentDepthAboveUsd, uint256 onePercentDepthBelowUsd,
uint16 slippageLongP, uint16 slippageShortP
) internal {
PairsManagerStorage storage pms = pairsManagerStorage();
SlippageConfig storage config = pms.slippageConfigs[index];
require(!config.enable, "LibPairsManager: Configuration already exists");
config.index = index;
config.name = name;
config.enable = true;
config.slippageType = slippageType;
config.onePercentDepthAboveUsd = onePercentDepthAboveUsd;
config.onePercentDepthBelowUsd = onePercentDepthBelowUsd;
config.slippageLongP = slippageLongP;
config.slippageShortP = slippageShortP;
emit AddSlippageConfig(index, slippageType, onePercentDepthAboveUsd,
onePercentDepthBelowUsd, slippageLongP, slippageShortP, name);
}
function removeSlippageConfig(uint16 index) internal {
PairsManagerStorage storage pms = pairsManagerStorage();
SlippageConfig storage config = pms.slippageConfigs[index];
require(config.enable, "LibPairsManager: Configuration not enabled");
require(pms.slippageConfigPairs[index].length == 0, "LibPairsManager: Cannot remove a configuration that is still in use");
delete pms.slippageConfigs[index];
emit RemoveSlippageConfig(index);
}
function updateSlippageConfig(SlippageConfig memory sc) internal {
PairsManagerStorage storage pms = pairsManagerStorage();
SlippageConfig storage config = pms.slippageConfigs[sc.index];
require(config.enable, "LibPairsManager: Configuration not enabled");
config.slippageType = sc.slippageType;
config.onePercentDepthAboveUsd = sc.onePercentDepthAboveUsd;
config.onePercentDepthBelowUsd = sc.onePercentDepthBelowUsd;
config.slippageLongP = sc.slippageLongP;
config.slippageShortP = sc.slippageShortP;
sc.name = config.name;
emit UpdateSlippageConfig(sc.index, sc, config);
}
function addPair(
IPairsManager.PairSimple memory ps,
uint256 maxLongOiUsd, uint256 maxShortOiUsd,
uint16 slippageConfigIndex, uint16 feeConfigIndex,
LeverageMargin[] memory leverageMargins
) internal {
PairsManagerStorage storage pms = pairsManagerStorage();
Pair storage pair = pms.pairs[ps.base];
require(pair.base == address(0), "LibPairsManager: Pair already exists");
{
SlippageConfig memory slippageConfig = pms.slippageConfigs[slippageConfigIndex];
require(slippageConfig.enable, "LibPairsManager: Slippage configuration is not available");
(LibFeeManager.FeeConfig memory feeConfig, address[] storage feePairs) = LibFeeManager.getFeeConfigByIndex(feeConfigIndex);
require(feeConfig.enable, "LibPairsManager: Fee configuration is not available");
pair.slippageConfigIndex = slippageConfigIndex;
address[] storage slippagePairs = pms.slippageConfigPairs[slippageConfigIndex];
pair.slippagePosition = uint16(slippagePairs.length);
slippagePairs.push(ps.base);
pair.feeConfigIndex = feeConfigIndex;
pair.feePosition = uint16(feePairs.length);
feePairs.push(ps.base);
}
pair.name = ps.name;
pair.base = ps.base;
pair.basePosition = uint16(pms.pairBases.length);
pms.pairBases.push(ps.base);
pair.pairType = ps.pairType;
pair.status = ps.status;
pair.maxLongOiUsd = maxLongOiUsd;
pair.maxShortOiUsd = maxShortOiUsd;
pair.maxTier = uint16(leverageMargins.length);
for (uint16 i = 1; i <= leverageMargins.length;) {
pair.leverageMargins[i] = leverageMargins[i - 1];
unchecked {
i++;
}
}
emit AddPair(ps.base, ps.pairType, maxLongOiUsd, maxShortOiUsd,
slippageConfigIndex, feeConfigIndex, ps.name, leverageMargins);
}
function addPair(
IPairsManager.PairSimple memory ps,
uint256 maxLongOiUsd, uint256 maxShortOiUsd,
uint16 slippageConfigIndex, uint16 feeConfigIndex,
LeverageMargin[] memory leverageMargins
) internal {
PairsManagerStorage storage pms = pairsManagerStorage();
Pair storage pair = pms.pairs[ps.base];
require(pair.base == address(0), "LibPairsManager: Pair already exists");
{
SlippageConfig memory slippageConfig = pms.slippageConfigs[slippageConfigIndex];
require(slippageConfig.enable, "LibPairsManager: Slippage configuration is not available");
(LibFeeManager.FeeConfig memory feeConfig, address[] storage feePairs) = LibFeeManager.getFeeConfigByIndex(feeConfigIndex);
require(feeConfig.enable, "LibPairsManager: Fee configuration is not available");
pair.slippageConfigIndex = slippageConfigIndex;
address[] storage slippagePairs = pms.slippageConfigPairs[slippageConfigIndex];
pair.slippagePosition = uint16(slippagePairs.length);
slippagePairs.push(ps.base);
pair.feeConfigIndex = feeConfigIndex;
pair.feePosition = uint16(feePairs.length);
feePairs.push(ps.base);
}
pair.name = ps.name;
pair.base = ps.base;
pair.basePosition = uint16(pms.pairBases.length);
pms.pairBases.push(ps.base);
pair.pairType = ps.pairType;
pair.status = ps.status;
pair.maxLongOiUsd = maxLongOiUsd;
pair.maxShortOiUsd = maxShortOiUsd;
pair.maxTier = uint16(leverageMargins.length);
for (uint16 i = 1; i <= leverageMargins.length;) {
pair.leverageMargins[i] = leverageMargins[i - 1];
unchecked {
i++;
}
}
emit AddPair(ps.base, ps.pairType, maxLongOiUsd, maxShortOiUsd,
slippageConfigIndex, feeConfigIndex, ps.name, leverageMargins);
}
function addPair(
IPairsManager.PairSimple memory ps,
uint256 maxLongOiUsd, uint256 maxShortOiUsd,
uint16 slippageConfigIndex, uint16 feeConfigIndex,
LeverageMargin[] memory leverageMargins
) internal {
PairsManagerStorage storage pms = pairsManagerStorage();
Pair storage pair = pms.pairs[ps.base];
require(pair.base == address(0), "LibPairsManager: Pair already exists");
{
SlippageConfig memory slippageConfig = pms.slippageConfigs[slippageConfigIndex];
require(slippageConfig.enable, "LibPairsManager: Slippage configuration is not available");
(LibFeeManager.FeeConfig memory feeConfig, address[] storage feePairs) = LibFeeManager.getFeeConfigByIndex(feeConfigIndex);
require(feeConfig.enable, "LibPairsManager: Fee configuration is not available");
pair.slippageConfigIndex = slippageConfigIndex;
address[] storage slippagePairs = pms.slippageConfigPairs[slippageConfigIndex];
pair.slippagePosition = uint16(slippagePairs.length);
slippagePairs.push(ps.base);
pair.feeConfigIndex = feeConfigIndex;
pair.feePosition = uint16(feePairs.length);
feePairs.push(ps.base);
}
pair.name = ps.name;
pair.base = ps.base;
pair.basePosition = uint16(pms.pairBases.length);
pms.pairBases.push(ps.base);
pair.pairType = ps.pairType;
pair.status = ps.status;
pair.maxLongOiUsd = maxLongOiUsd;
pair.maxShortOiUsd = maxShortOiUsd;
pair.maxTier = uint16(leverageMargins.length);
for (uint16 i = 1; i <= leverageMargins.length;) {
pair.leverageMargins[i] = leverageMargins[i - 1];
unchecked {
i++;
}
}
emit AddPair(ps.base, ps.pairType, maxLongOiUsd, maxShortOiUsd,
slippageConfigIndex, feeConfigIndex, ps.name, leverageMargins);
}
function addPair(
IPairsManager.PairSimple memory ps,
uint256 maxLongOiUsd, uint256 maxShortOiUsd,
uint16 slippageConfigIndex, uint16 feeConfigIndex,
LeverageMargin[] memory leverageMargins
) internal {
PairsManagerStorage storage pms = pairsManagerStorage();
Pair storage pair = pms.pairs[ps.base];
require(pair.base == address(0), "LibPairsManager: Pair already exists");
{
SlippageConfig memory slippageConfig = pms.slippageConfigs[slippageConfigIndex];
require(slippageConfig.enable, "LibPairsManager: Slippage configuration is not available");
(LibFeeManager.FeeConfig memory feeConfig, address[] storage feePairs) = LibFeeManager.getFeeConfigByIndex(feeConfigIndex);
require(feeConfig.enable, "LibPairsManager: Fee configuration is not available");
pair.slippageConfigIndex = slippageConfigIndex;
address[] storage slippagePairs = pms.slippageConfigPairs[slippageConfigIndex];
pair.slippagePosition = uint16(slippagePairs.length);
slippagePairs.push(ps.base);
pair.feeConfigIndex = feeConfigIndex;
pair.feePosition = uint16(feePairs.length);
feePairs.push(ps.base);
}
pair.name = ps.name;
pair.base = ps.base;
pair.basePosition = uint16(pms.pairBases.length);
pms.pairBases.push(ps.base);
pair.pairType = ps.pairType;
pair.status = ps.status;
pair.maxLongOiUsd = maxLongOiUsd;
pair.maxShortOiUsd = maxShortOiUsd;
pair.maxTier = uint16(leverageMargins.length);
for (uint16 i = 1; i <= leverageMargins.length;) {
pair.leverageMargins[i] = leverageMargins[i - 1];
unchecked {
i++;
}
}
emit AddPair(ps.base, ps.pairType, maxLongOiUsd, maxShortOiUsd,
slippageConfigIndex, feeConfigIndex, ps.name, leverageMargins);
}
function removePair(address base) internal {
PairsManagerStorage storage pms = pairsManagerStorage();
Pair storage pair = pms.pairs[base];
require(pair.base != address(0), "LibPairsManager: Pair does not exist");
address[] storage slippagePairs = pms.slippageConfigPairs[pair.slippageConfigIndex];
uint lastPositionSlippage = slippagePairs.length - 1;
uint slippagePosition = pair.slippagePosition;
if (slippagePosition != lastPositionSlippage) {
address lastBase = slippagePairs[lastPositionSlippage];
slippagePairs[slippagePosition] = lastBase;
pms.pairs[lastBase].slippagePosition = uint16(slippagePosition);
}
slippagePairs.pop();
(, address[] storage feePairs) = LibFeeManager.getFeeConfigByIndex(pair.feeConfigIndex);
uint lastPositionFee = feePairs.length - 1;
uint feePosition = pair.feePosition;
if (feePosition != lastPositionFee) {
address lastBase = feePairs[lastPositionFee];
feePairs[feePosition] = lastBase;
pms.pairs[lastBase].feePosition = uint16(feePosition);
}
feePairs.pop();
address[] storage pairBases = pms.pairBases;
uint lastPositionBase = pairBases.length - 1;
uint basePosition = pair.basePosition;
if (basePosition != lastPositionBase) {
address lastBase = pairBases[lastPositionBase];
pairBases[basePosition] = lastBase;
pms.pairs[lastBase].basePosition = uint16(basePosition);
}
pairBases.pop();
delete pms.pairs[base];
emit RemovePair(base);
}
function removePair(address base) internal {
PairsManagerStorage storage pms = pairsManagerStorage();
Pair storage pair = pms.pairs[base];
require(pair.base != address(0), "LibPairsManager: Pair does not exist");
address[] storage slippagePairs = pms.slippageConfigPairs[pair.slippageConfigIndex];
uint lastPositionSlippage = slippagePairs.length - 1;
uint slippagePosition = pair.slippagePosition;
if (slippagePosition != lastPositionSlippage) {
address lastBase = slippagePairs[lastPositionSlippage];
slippagePairs[slippagePosition] = lastBase;
pms.pairs[lastBase].slippagePosition = uint16(slippagePosition);
}
slippagePairs.pop();
(, address[] storage feePairs) = LibFeeManager.getFeeConfigByIndex(pair.feeConfigIndex);
uint lastPositionFee = feePairs.length - 1;
uint feePosition = pair.feePosition;
if (feePosition != lastPositionFee) {
address lastBase = feePairs[lastPositionFee];
feePairs[feePosition] = lastBase;
pms.pairs[lastBase].feePosition = uint16(feePosition);
}
feePairs.pop();
address[] storage pairBases = pms.pairBases;
uint lastPositionBase = pairBases.length - 1;
uint basePosition = pair.basePosition;
if (basePosition != lastPositionBase) {
address lastBase = pairBases[lastPositionBase];
pairBases[basePosition] = lastBase;
pms.pairs[lastBase].basePosition = uint16(basePosition);
}
pairBases.pop();
delete pms.pairs[base];
emit RemovePair(base);
}
function removePair(address base) internal {
PairsManagerStorage storage pms = pairsManagerStorage();
Pair storage pair = pms.pairs[base];
require(pair.base != address(0), "LibPairsManager: Pair does not exist");
address[] storage slippagePairs = pms.slippageConfigPairs[pair.slippageConfigIndex];
uint lastPositionSlippage = slippagePairs.length - 1;
uint slippagePosition = pair.slippagePosition;
if (slippagePosition != lastPositionSlippage) {
address lastBase = slippagePairs[lastPositionSlippage];
slippagePairs[slippagePosition] = lastBase;
pms.pairs[lastBase].slippagePosition = uint16(slippagePosition);
}
slippagePairs.pop();
(, address[] storage feePairs) = LibFeeManager.getFeeConfigByIndex(pair.feeConfigIndex);
uint lastPositionFee = feePairs.length - 1;
uint feePosition = pair.feePosition;
if (feePosition != lastPositionFee) {
address lastBase = feePairs[lastPositionFee];
feePairs[feePosition] = lastBase;
pms.pairs[lastBase].feePosition = uint16(feePosition);
}
feePairs.pop();
address[] storage pairBases = pms.pairBases;
uint lastPositionBase = pairBases.length - 1;
uint basePosition = pair.basePosition;
if (basePosition != lastPositionBase) {
address lastBase = pairBases[lastPositionBase];
pairBases[basePosition] = lastBase;
pms.pairs[lastBase].basePosition = uint16(basePosition);
}
pairBases.pop();
delete pms.pairs[base];
emit RemovePair(base);
}
function removePair(address base) internal {
PairsManagerStorage storage pms = pairsManagerStorage();
Pair storage pair = pms.pairs[base];
require(pair.base != address(0), "LibPairsManager: Pair does not exist");
address[] storage slippagePairs = pms.slippageConfigPairs[pair.slippageConfigIndex];
uint lastPositionSlippage = slippagePairs.length - 1;
uint slippagePosition = pair.slippagePosition;
if (slippagePosition != lastPositionSlippage) {
address lastBase = slippagePairs[lastPositionSlippage];
slippagePairs[slippagePosition] = lastBase;
pms.pairs[lastBase].slippagePosition = uint16(slippagePosition);
}
slippagePairs.pop();
(, address[] storage feePairs) = LibFeeManager.getFeeConfigByIndex(pair.feeConfigIndex);
uint lastPositionFee = feePairs.length - 1;
uint feePosition = pair.feePosition;
if (feePosition != lastPositionFee) {
address lastBase = feePairs[lastPositionFee];
feePairs[feePosition] = lastBase;
pms.pairs[lastBase].feePosition = uint16(feePosition);
}
feePairs.pop();
address[] storage pairBases = pms.pairBases;
uint lastPositionBase = pairBases.length - 1;
uint basePosition = pair.basePosition;
if (basePosition != lastPositionBase) {
address lastBase = pairBases[lastPositionBase];
pairBases[basePosition] = lastBase;
pms.pairs[lastBase].basePosition = uint16(basePosition);
}
pairBases.pop();
delete pms.pairs[base];
emit RemovePair(base);
}
function updatePairStatus(address base, IPairsManager.PairStatus status) internal {
Pair storage pair = pairsManagerStorage().pairs[base];
require(pair.base != address(0), "LibPairsManager: Pair does not exist");
require(pair.status != status, "LibPairsManager: No change in status, no modification required");
IPairsManager.PairStatus oldStatus = pair.status;
pair.status = status;
emit UpdatePairStatus(base, oldStatus, status);
}
function updatePairSlippage(address base, uint16 slippageConfigIndex) internal {
PairsManagerStorage storage pms = pairsManagerStorage();
Pair storage pair = pms.pairs[base];
require(pair.base != address(0), "LibPairsManager: Pair does not exist");
SlippageConfig memory config = pms.slippageConfigs[slippageConfigIndex];
require(config.enable, "LibPairsManager: Slippage configuration is not available");
uint16 oldSlippageConfigIndex = pair.slippageConfigIndex;
address[] storage oldSlippagePairs = pms.slippageConfigPairs[oldSlippageConfigIndex];
uint lastPositionSlippage = oldSlippagePairs.length - 1;
uint oldSlippagePosition = pair.slippagePosition;
if (oldSlippagePosition != lastPositionSlippage) {
oldSlippagePairs[oldSlippagePosition] = oldSlippagePairs[lastPositionSlippage];
}
oldSlippagePairs.pop();
pair.slippageConfigIndex = slippageConfigIndex;
address[] storage slippagePairs = pms.slippageConfigPairs[slippageConfigIndex];
pair.slippagePosition = uint16(slippagePairs.length);
slippagePairs.push(base);
emit UpdatePairSlippage(base, oldSlippageConfigIndex, slippageConfigIndex);
}
function updatePairSlippage(address base, uint16 slippageConfigIndex) internal {
PairsManagerStorage storage pms = pairsManagerStorage();
Pair storage pair = pms.pairs[base];
require(pair.base != address(0), "LibPairsManager: Pair does not exist");
SlippageConfig memory config = pms.slippageConfigs[slippageConfigIndex];
require(config.enable, "LibPairsManager: Slippage configuration is not available");
uint16 oldSlippageConfigIndex = pair.slippageConfigIndex;
address[] storage oldSlippagePairs = pms.slippageConfigPairs[oldSlippageConfigIndex];
uint lastPositionSlippage = oldSlippagePairs.length - 1;
uint oldSlippagePosition = pair.slippagePosition;
if (oldSlippagePosition != lastPositionSlippage) {
oldSlippagePairs[oldSlippagePosition] = oldSlippagePairs[lastPositionSlippage];
}
oldSlippagePairs.pop();
pair.slippageConfigIndex = slippageConfigIndex;
address[] storage slippagePairs = pms.slippageConfigPairs[slippageConfigIndex];
pair.slippagePosition = uint16(slippagePairs.length);
slippagePairs.push(base);
emit UpdatePairSlippage(base, oldSlippageConfigIndex, slippageConfigIndex);
}
function updatePairFee(address base, uint16 feeConfigIndex) internal {
PairsManagerStorage storage pms = pairsManagerStorage();
Pair storage pair = pms.pairs[base];
require(pair.base != address(0), "LibPairsManager: Pair does not exist");
(LibFeeManager.FeeConfig memory feeConfig, address[] storage feePairs) = LibFeeManager.getFeeConfigByIndex(feeConfigIndex);
require(feeConfig.enable, "LibPairsManager: Fee configuration is not available");
uint16 oldFeeConfigIndex = pair.feeConfigIndex;
(, address[] storage oldFeePairs) = LibFeeManager.getFeeConfigByIndex(oldFeeConfigIndex);
uint lastPositionFee = oldFeePairs.length - 1;
uint oldFeePosition = pair.feePosition;
if (oldFeePosition != lastPositionFee) {
oldFeePairs[oldFeePosition] = oldFeePairs[lastPositionFee];
}
oldFeePairs.pop();
pair.feeConfigIndex = feeConfigIndex;
pair.feePosition = uint16(feePairs.length);
feePairs.push(base);
emit UpdatePairFee(base, oldFeeConfigIndex, feeConfigIndex);
}
function updatePairFee(address base, uint16 feeConfigIndex) internal {
PairsManagerStorage storage pms = pairsManagerStorage();
Pair storage pair = pms.pairs[base];
require(pair.base != address(0), "LibPairsManager: Pair does not exist");
(LibFeeManager.FeeConfig memory feeConfig, address[] storage feePairs) = LibFeeManager.getFeeConfigByIndex(feeConfigIndex);
require(feeConfig.enable, "LibPairsManager: Fee configuration is not available");
uint16 oldFeeConfigIndex = pair.feeConfigIndex;
(, address[] storage oldFeePairs) = LibFeeManager.getFeeConfigByIndex(oldFeeConfigIndex);
uint lastPositionFee = oldFeePairs.length - 1;
uint oldFeePosition = pair.feePosition;
if (oldFeePosition != lastPositionFee) {
oldFeePairs[oldFeePosition] = oldFeePairs[lastPositionFee];
}
oldFeePairs.pop();
pair.feeConfigIndex = feeConfigIndex;
pair.feePosition = uint16(feePairs.length);
feePairs.push(base);
emit UpdatePairFee(base, oldFeeConfigIndex, feeConfigIndex);
}
function updatePairLeverageMargin(address base, LeverageMargin[] memory leverageMargins) internal {
PairsManagerStorage storage pms = pairsManagerStorage();
Pair storage pair = pms.pairs[base];
require(pair.base != address(0), "LibPairsManager: Pair does not exist");
LeverageMargin[] memory oldLeverageMargins = new LeverageMargin[](pair.maxTier);
uint maxTier = pair.maxTier > leverageMargins.length ? pair.maxTier : leverageMargins.length;
for (uint16 i = 1; i <= maxTier;) {
if (i <= pair.maxTier) {
oldLeverageMargins[i - 1] = pair.leverageMargins[i];
}
if (i <= leverageMargins.length) {
pair.leverageMargins[i] = leverageMargins[i - 1];
delete pair.leverageMargins[i];
}
unchecked {
i++;
}
}
pair.maxTier = uint16(leverageMargins.length);
emit UpdatePairLeverageMargin(base, oldLeverageMargins, leverageMargins);
}
function updatePairLeverageMargin(address base, LeverageMargin[] memory leverageMargins) internal {
PairsManagerStorage storage pms = pairsManagerStorage();
Pair storage pair = pms.pairs[base];
require(pair.base != address(0), "LibPairsManager: Pair does not exist");
LeverageMargin[] memory oldLeverageMargins = new LeverageMargin[](pair.maxTier);
uint maxTier = pair.maxTier > leverageMargins.length ? pair.maxTier : leverageMargins.length;
for (uint16 i = 1; i <= maxTier;) {
if (i <= pair.maxTier) {
oldLeverageMargins[i - 1] = pair.leverageMargins[i];
}
if (i <= leverageMargins.length) {
pair.leverageMargins[i] = leverageMargins[i - 1];
delete pair.leverageMargins[i];
}
unchecked {
i++;
}
}
pair.maxTier = uint16(leverageMargins.length);
emit UpdatePairLeverageMargin(base, oldLeverageMargins, leverageMargins);
}
function updatePairLeverageMargin(address base, LeverageMargin[] memory leverageMargins) internal {
PairsManagerStorage storage pms = pairsManagerStorage();
Pair storage pair = pms.pairs[base];
require(pair.base != address(0), "LibPairsManager: Pair does not exist");
LeverageMargin[] memory oldLeverageMargins = new LeverageMargin[](pair.maxTier);
uint maxTier = pair.maxTier > leverageMargins.length ? pair.maxTier : leverageMargins.length;
for (uint16 i = 1; i <= maxTier;) {
if (i <= pair.maxTier) {
oldLeverageMargins[i - 1] = pair.leverageMargins[i];
}
if (i <= leverageMargins.length) {
pair.leverageMargins[i] = leverageMargins[i - 1];
delete pair.leverageMargins[i];
}
unchecked {
i++;
}
}
pair.maxTier = uint16(leverageMargins.length);
emit UpdatePairLeverageMargin(base, oldLeverageMargins, leverageMargins);
}
function updatePairLeverageMargin(address base, LeverageMargin[] memory leverageMargins) internal {
PairsManagerStorage storage pms = pairsManagerStorage();
Pair storage pair = pms.pairs[base];
require(pair.base != address(0), "LibPairsManager: Pair does not exist");
LeverageMargin[] memory oldLeverageMargins = new LeverageMargin[](pair.maxTier);
uint maxTier = pair.maxTier > leverageMargins.length ? pair.maxTier : leverageMargins.length;
for (uint16 i = 1; i <= maxTier;) {
if (i <= pair.maxTier) {
oldLeverageMargins[i - 1] = pair.leverageMargins[i];
}
if (i <= leverageMargins.length) {
pair.leverageMargins[i] = leverageMargins[i - 1];
delete pair.leverageMargins[i];
}
unchecked {
i++;
}
}
pair.maxTier = uint16(leverageMargins.length);
emit UpdatePairLeverageMargin(base, oldLeverageMargins, leverageMargins);
}
} else {
function updatePairLeverageMargin(address base, LeverageMargin[] memory leverageMargins) internal {
PairsManagerStorage storage pms = pairsManagerStorage();
Pair storage pair = pms.pairs[base];
require(pair.base != address(0), "LibPairsManager: Pair does not exist");
LeverageMargin[] memory oldLeverageMargins = new LeverageMargin[](pair.maxTier);
uint maxTier = pair.maxTier > leverageMargins.length ? pair.maxTier : leverageMargins.length;
for (uint16 i = 1; i <= maxTier;) {
if (i <= pair.maxTier) {
oldLeverageMargins[i - 1] = pair.leverageMargins[i];
}
if (i <= leverageMargins.length) {
pair.leverageMargins[i] = leverageMargins[i - 1];
delete pair.leverageMargins[i];
}
unchecked {
i++;
}
}
pair.maxTier = uint16(leverageMargins.length);
emit UpdatePairLeverageMargin(base, oldLeverageMargins, leverageMargins);
}
function getPairByBase(address base) internal view returns (IPairsManager.PairView memory) {
PairsManagerStorage storage pms = pairsManagerStorage();
Pair storage pair = pms.pairs[base];
return pairToView(pair, pms.slippageConfigs[pair.slippageConfigIndex]);
}
function pairToView(
Pair storage pair, SlippageConfig memory slippageConfig
) internal view returns (IPairsManager.PairView memory) {
LeverageMargin[] memory leverageMargins = new LeverageMargin[](pair.maxTier);
for (uint16 i = 0; i < pair.maxTier;) {
leverageMargins[i] = pair.leverageMargins[i + 1];
unchecked {
i++;
}
}
(LibFeeManager.FeeConfig memory feeConfig,) = LibFeeManager.getFeeConfigByIndex(pair.feeConfigIndex);
IPairsManager.PairView memory pv = IPairsManager.PairView(
pair.name, pair.base, pair.basePosition, pair.pairType, pair.status,
pair.maxLongOiUsd, pair.maxShortOiUsd, leverageMargins,
pair.slippageConfigIndex, pair.slippagePosition, slippageConfig,
pair.feeConfigIndex, pair.feePosition, feeConfig
);
return pv;
}
function pairToView(
Pair storage pair, SlippageConfig memory slippageConfig
) internal view returns (IPairsManager.PairView memory) {
LeverageMargin[] memory leverageMargins = new LeverageMargin[](pair.maxTier);
for (uint16 i = 0; i < pair.maxTier;) {
leverageMargins[i] = pair.leverageMargins[i + 1];
unchecked {
i++;
}
}
(LibFeeManager.FeeConfig memory feeConfig,) = LibFeeManager.getFeeConfigByIndex(pair.feeConfigIndex);
IPairsManager.PairView memory pv = IPairsManager.PairView(
pair.name, pair.base, pair.basePosition, pair.pairType, pair.status,
pair.maxLongOiUsd, pair.maxShortOiUsd, leverageMargins,
pair.slippageConfigIndex, pair.slippagePosition, slippageConfig,
pair.feeConfigIndex, pair.feePosition, feeConfig
);
return pv;
}
function pairToView(
Pair storage pair, SlippageConfig memory slippageConfig
) internal view returns (IPairsManager.PairView memory) {
LeverageMargin[] memory leverageMargins = new LeverageMargin[](pair.maxTier);
for (uint16 i = 0; i < pair.maxTier;) {
leverageMargins[i] = pair.leverageMargins[i + 1];
unchecked {
i++;
}
}
(LibFeeManager.FeeConfig memory feeConfig,) = LibFeeManager.getFeeConfigByIndex(pair.feeConfigIndex);
IPairsManager.PairView memory pv = IPairsManager.PairView(
pair.name, pair.base, pair.basePosition, pair.pairType, pair.status,
pair.maxLongOiUsd, pair.maxShortOiUsd, leverageMargins,
pair.slippageConfigIndex, pair.slippagePosition, slippageConfig,
pair.feeConfigIndex, pair.feePosition, feeConfig
);
return pv;
}
}
| 3,284,106 | [
1,
9012,
30,
225,
166,
243,
241,
170,
256,
100,
167,
247,
122,
166,
254,
257,
513,
355,
383,
92,
18,
11545,
18,
4181,
18,
5697,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
12083,
10560,
10409,
1318,
288,
203,
203,
565,
1731,
1578,
5381,
15662,
7937,
55,
67,
19402,
67,
19009,
67,
15258,
273,
417,
24410,
581,
5034,
2932,
438,
355,
383,
92,
18,
11545,
18,
4181,
18,
5697,
18,
18212,
23,
3103,
4033,
8863,
203,
203,
4202,
17742,
565,
486,
285,
287,
3477,
72,
377,
943,
1682,
5682,
1377,
2172,
19024,
52,
3639,
4501,
85,
19024,
52,
203,
3639,
404,
1377,
261,
20,
4871,
1728,
16,
3784,
65,
3639,
4200,
2868,
16848,
9,
7734,
16340,
18,
25,
9,
203,
3639,
576,
565,
261,
2163,
16,
3784,
4871,
6437,
16,
3784,
65,
377,
1728,
2868,
8566,
9,
1171,
16848,
9,
203,
3639,
890,
565,
261,
3361,
16,
3784,
4871,
2130,
16,
3784,
65,
377,
1381,
2868,
8958,
9,
1171,
8566,
9,
203,
3639,
1059,
565,
261,
6625,
16,
3784,
4871,
4044,
16,
3784,
65,
565,
890,
2868,
18821,
9,
1171,
19692,
9,
203,
3639,
1381,
565,
261,
6976,
16,
3784,
4871,
6604,
16,
3784,
65,
565,
576,
2868,
4752,
9,
1171,
18821,
9,
203,
3639,
1666,
565,
261,
12483,
16,
3784,
4871,
1725,
713,
16,
3784,
65,
565,
404,
2868,
8063,
9,
1171,
6437,
9,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
2643,
31,
203,
565,
1958,
3519,
5682,
9524,
288,
203,
3639,
2254,
2313,
17742,
31,
203,
3639,
2254,
5034,
486,
285,
287,
3477,
72,
31,
203,
3639,
2254,
2313,
943,
1682,
5682,
31,
203,
565,
289,
203,
203,
565,
1958,
348,
3169,
2433,
809,
288,
203,
3639,
533,
508,
31,
203,
3639,
2
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.