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.25;
// It's important to avoid vulnerabilities due to numeric overflow bugs
// OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs
// More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
//import "../contracts/FlightSuretyData.sol";
/************************************************** */
/* FlightSurety Smart Contract */
/************************************************** */
contract FlightSuretyApp {
using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript)
FlightSuretyData flightSuretyData;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
// Flight status codees
uint8 private constant STATUS_CODE_UNKNOWN = 0;
uint8 private constant STATUS_CODE_ON_TIME = 10;
uint8 private constant STATUS_CODE_LATE_AIRLINE = 20;
uint8 private constant STATUS_CODE_LATE_WEATHER = 30;
uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40;
uint8 private constant STATUS_CODE_LATE_OTHER = 50;
uint256 public constant MINIMUM_FUNDING = 10 ether;
uint256 private constant MAX_INSURANCE_PAYMENT = 1 ether;
uint256 private constant STARALLIANCE = 4;
mapping(address => address[]) public votesOfAirlines;
address private contractOwner; // Account used to deploy contract
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
event WithdrawRequest(address recipient);
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
require(flightSuretyData.isOperational(), "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
/**
* @dev Modifier that requires the "Airline" not to be registered
*/
modifier requireAirlineToBeNotRegistered(address _account)
{
require(!flightSuretyData.isAirlineRegistered(_account), "Airline is already registered.");
_;
}
/**
* @dev Modifier that requires the "Sender" to be an airline that provided fund.
*/
modifier requireProvidedFund()
{
require(flightSuretyData.isAirlineProvidedFund(msg.sender), "The Airline did not provide a funding.");
_;
}
modifier requireMinimumFundProvided() {
require(msg.value >= MINIMUM_FUNDING, "The minimum funding is 10 ether");
_;
}
modifier requireIsPaidEnough(uint _price) {
require(msg.value >= _price, "Sent value must cover the price");
_;
}
modifier requireValueCheck(uint _price) {
_;
uint amountToReturn = msg.value - _price;
msg.sender.transfer(amountToReturn);
}
/********************************************************************************************/
/* CONSTRUCTOR */
/********************************************************************************************/
/**
* @dev Contract constructor
*
*/
constructor(address dataContract) public {
contractOwner = msg.sender;
flightSuretyData = FlightSuretyData(dataContract);
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
*
*/
function registerAirline(address _account) external requireIsOperational
requireAirlineToBeNotRegistered(_account)
requireProvidedFund
{
if (flightSuretyData.getRegisteredAirlinesCount() < STARALLIANCE){
flightSuretyData.registerAirline(_account, msg.sender);
} else {
bool isDuplicate = false;
for(uint c=0; c < votesOfAirlines[_account].length; c++) {
if (votesOfAirlines[_account][c] == msg.sender) {
isDuplicate = true;
break;
}
}
require(!isDuplicate, "Caller has already called this function.");
votesOfAirlines[_account].push(msg.sender);
uint votes = votesOfAirlines[_account].length;
uint256 M = flightSuretyData.getRegisteredAirlinesCount().div(2);
if (votes > M) {
votesOfAirlines[_account] = new address[](0);
flightSuretyData.registerAirline(_account, msg.sender);
}
}
}
function provideFund() external payable requireMinimumFundProvided requireIsOperational{
flightSuretyData.fund.value(msg.value)(msg.sender);
}
function getFlightKey(string _flightCode, string _destination, uint _timestamp) public pure returns(bytes32) {
return keccak256(abi.encodePacked(_flightCode, _destination, _timestamp));
}
/**
* @dev Register a future flight for insuring.
*
*/
function registerFlight(string _flightCode, uint _timestamp, uint _price, string _departure, string _destination) external
requireIsOperational
requireProvidedFund
{
flightSuretyData.registerFlight(
_flightCode,
_timestamp,
_price,
_departure,
_destination,
msg.sender
);
}
function buyInsurance(string _flight, uint _timestamp, string _destination) public payable
requireIsOperational
requireIsPaidEnough(MAX_INSURANCE_PAYMENT)
requireValueCheck(MAX_INSURANCE_PAYMENT)
{
bytes32 flightKey = getFlightKey(_flight, _destination, _timestamp);
flightSuretyData.buy(flightKey, msg.value, msg.sender);
}
function withdraw() public requireIsOperational
{
flightSuretyData.pay(msg.sender);
}
// Generate a request for oracles to fetch flight information
function fetchFlightStatus(string _flight, string _destination, uint _timestamp) public
{
uint8 index = getRandomIndex(msg.sender);
// Generate a unique key for storing the request
bytes32 key = keccak256(abi.encodePacked(_flight, _timestamp, _destination));
oracleResponses[key] = ResponseInfo({
requester: msg.sender,
isOpen: true
});
emit OracleRequest(index, _flight, _destination, _timestamp);
}
// region ORACLE MANAGEMENT
// Incremented to add pseudo-randomness at various points
uint8 private nonce = 0;
// Fee to be paid when registering oracle
uint256 public constant REGISTRATION_FEE = 1 ether;
// Number of oracles that must respond for valid status
uint8 private constant MIN_RESPONSES = 3;
struct Oracle {
bool isRegistered;
uint8[3] indexes;
}
// Track all registered oracles
mapping(address => Oracle) private oracles;
// Model for responses from oracles
struct ResponseInfo {
address requester;
bool isOpen;
mapping(uint8 => address[]) responses;
}
// Track all oracle responses
// Key = hash(flight, destination, timestamp)
mapping(bytes32 => ResponseInfo) public oracleResponses;
event OracleRegistered(uint8[3] indexes);
// Event fired each time an oracle submits a response
event OracleReport(string flightCode, string destination, uint timestamp, uint8 status);
// Event fired when number of identical responses reaches the threshold: response is accepted and is processed
event FlightStatusInfo(string flightCode, string destination, uint timestamp, uint8 status);
// Event fired when flight status request is submitted
// Oracles track this and if they have a matching index
// they fetch data and submit a response
event OracleRequest(uint8 index, string flightCode, string destination, uint timestamp);
// Register an oracle with the contract
function registerOracle() external payable {
// Require registration fee
require(msg.value >= REGISTRATION_FEE, "Registration fee is required");
uint8[3] memory indexes = generateIndexes(msg.sender);
oracles[msg.sender] = Oracle({
isRegistered: true,
indexes: indexes
});
emit OracleRegistered(indexes);
}
function getMyIndexes() external view returns(uint8[3]) {
require(oracles[msg.sender].isRegistered, "Not registered as an oracle");
return oracles[msg.sender].indexes;
}
// Called by oracle when a response is available to an outstanding request
// For the response to be accepted, there must be a pending request that is open
// and matches one of the three Indexes randomly assigned to the oracle at the
// time of registration (i.e. uninvited oracles are not welcome)
function submitOracleResponse(uint8 _index, string _flightCode, string _destination, uint _timestamp, uint8 _status) external {
require((oracles[msg.sender].indexes[0] == _index) ||
(oracles[msg.sender].indexes[1] == _index) ||
(oracles[msg.sender].indexes[2] == _index),
"Index does not match oracle request"
);
bytes32 key = getFlightKey(_flightCode, _destination, _timestamp);
require(oracleResponses[key].isOpen,"Flight or timestamp do not match oracle request.");
oracleResponses[key].responses[_status].push(msg.sender);
emit OracleReport(_flightCode, _destination, _timestamp, _status);
/* Information isn't considered verified until at least
MIN_RESPONSES oracles respond with the *** same *** information
*/
if (oracleResponses[key].responses[_status].length == MIN_RESPONSES) {
// close responseInfo
oracleResponses[key].isOpen = false;
emit FlightStatusInfo(_flightCode, _destination, _timestamp, _status);
// Handle flight status as appropriate
flightSuretyData.processFlightStatus(key, _status);
}
}
// Returns array of three non-duplicating integers from 0-9
function generateIndexes(address _account) internal returns(uint8[3]) {
uint8[3] memory indexes;
indexes[0] = getRandomIndex(_account);
indexes[1] = indexes[0];
while (indexes[1] == indexes[0]) {
indexes[1] = getRandomIndex(_account);
}
indexes[2] = indexes[1];
while ((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) {
indexes[2] = getRandomIndex(_account);
}
return indexes;
}
// Returns array of three non-duplicating integers from 0-9
function getRandomIndex(address _account) internal returns (uint8) {
uint8 maxValue = 10;
// Pseudo random number...the incrementing nonce adds variation
uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), _account))) % maxValue);
if (nonce > 250) {
nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt
}
return random;
}
// endregion
}
// FlightSuretyData Interface contract
contract FlightSuretyData {
function isOperational() public view returns(bool);
function isAirlineRegistered(address account) external view returns(bool);
function isAirlineProvidedFund(address account) external view returns(bool);
function getRegisteredAirlinesCount() external view returns(uint);
function registerAirline(address _account, address _sender) external;
function fund(address _airline) public payable;
function registerFlight(string _flightCode, uint _timestamp, uint _price, string _departure, string _destination, address _airline) external;
function buy(bytes32 flightKey, uint amount, address originAddress) external payable;
function creditInsurees(bytes32 flightKey) internal;
function pay(address originAddress) external;
function processFlightStatus(bytes32 flightKey, uint8 flightStatus) external;
}
| Returns array of three non-duplicating integers from 0-9 Pseudo random number...the incrementing nonce adds variation | function getRandomIndex(address _account) internal returns (uint8) {
uint8 maxValue = 10;
uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), _account))) % maxValue);
if (nonce > 250) {
}
return random;
}
| 12,914,982 |
./full_match/4/0x8367a9B862c7a81E6b567Ea2Ff6f8e5c6C794527/sources/contracts/CryptoCameo.sol | prevent accidental triggers by seller | function review(uint256 agreementId, bool goodReview) external {
require(msg.sender == _agreement[agreementId].buyer, "Not buyer");
require(_agreement[agreementId].review == false, "Already reviewed");
_agreement[agreementId].review = true;
if (goodReview) {
_cameo[_agreement[agreementId].seller].reputation++;
_cameo[_agreement[agreementId].seller].reputation--;
}
emit Review (
agreementId,
_agreement[agreementId].seller,
_agreement[agreementId].buyer,
goodReview
);
}
| 12,352,171 |
/*
/$$$$$$$$ /$$$$$$ /$$ /$$ /$$ /$$$$$$$$ /$$$$$$$$
|_____ $$ /$$__ $$ | $$ | $$$ | $$| $$_____/|__ $$__/
/$$/ /$$$$$$ /$$$$$$ /$$$$$$ | $$ \__/ /$$$$$$ /$$$$$$$ /$$$$$$ | $$$$| $$| $$ | $$
/$$/ /$$__ $$ /$$__ $$ /$$__ $$| $$ /$$__ $$ /$$__ $$ /$$__ $$| $$ $$ $$| $$$$$ | $$
/$$/ | $$$$$$$$| $$ \__/| $$ \ $$| $$ | $$ \ $$| $$ | $$| $$$$$$$$| $$ $$$$| $$__/ | $$
/$$/ | $$_____/| $$ | $$ | $$| $$ $$| $$ | $$| $$ | $$| $$_____/| $$\ $$$| $$ | $$
/$$$$$$$$| $$$$$$$| $$ | $$$$$$/| $$$$$$/| $$$$$$/| $$$$$$$| $$$$$$$| $$ \ $$| $$ | $$
|________/ \_______/|__/ \______/ \______/ \______/ \_______/ \_______/|__/ \__/|__/ |__/
Drop Your NFT Collection With ZERO Coding Skills at https://zerocodenft.com
*/
// SPDX-License-Identifier: MIT
// solhint-disable-next-line
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
contract InvisibleCuties is ERC721, Ownable {
using Counters for Counters.Counter;
using Strings for uint;
enum SaleStatus{ PAUSED, PRESALE, PUBLIC }
Counters.Counter private _tokenIds;
uint public constant COLLECTION_SIZE = 500;
uint public constant TOKENS_PER_TRAN_LIMIT = 2;
uint public constant TOKENS_PER_PERSON_PUB_LIMIT = 2;
uint public constant TOKENS_PER_PERSON_WL_LIMIT = 2;
uint public constant PRESALE_MINT_PRICE = 0.03 ether;
uint public MINT_PRICE = 0.04 ether;
SaleStatus public saleStatus = SaleStatus.PAUSED;
bool public canReveal = false;
bytes32 public merkleRoot;
string private _baseURL;
string private _hiddenURI = "ipfs://QmT8kCLu4wG4Qs9gsTrPLswJdbkkJTeBM81JxceuagVP9H";
mapping(address => uint) private _mintedCount;
mapping(address => uint) private _whitelistMintedCount;
constructor() ERC721("InvisibleCuties", "CUTIE"){}
/// @notice Update the merkle tree root
function setMerkleRoot(bytes32 root) external onlyOwner {
merkleRoot = root;
}
/// @notice Reveal metadata for all the tokens
function reveal(string memory uri) external onlyOwner {
canReveal = true;
_baseURL = uri;
}
function totalSupply() external view returns (uint) {
return _tokenIds.current();
}
/// @dev override base uri. It will be combined with token ID
function _baseURI() internal view override returns (string memory) {
return _baseURL;
}
/// @notice Update current sale stage
function setSaleStatus(SaleStatus status) external onlyOwner {
saleStatus = status;
}
/// @notice Update public mint price
function setPublicMintPrice(uint price) external onlyOwner {
MINT_PRICE = price;
}
function setPlaceholder(string memory uri) external onlyOwner {
_hiddenURI = uri;
}
/// @notice Withdraw contract's balance
function withdraw() external onlyOwner {
uint balance = address(this).balance;
require(balance > 0, "No balance");
payable(owner()).transfer(balance);
}
/// @notice Allows owner to mint tokens to a specified address
function airdrop(address to, uint count) external onlyOwner {
require(_tokenIds.current() + count <= COLLECTION_SIZE, "Request exceeds collection size");
_mintTokens(to, count);
}
/// @notice Get token's URI. In case of delayed reveal we give user the json of the placeholer metadata.
/// @param tokenId token ID
function tokenURI(uint tokenId) public view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
if(!canReveal) {
return _hiddenURI;
}
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString(), ".json")) : "";
}
function redeem(bytes32[] calldata merkleProof, uint count) external payable {
require(saleStatus != SaleStatus.PAUSED, "Sales are off");
require(_tokenIds.current() + count <= COLLECTION_SIZE, "Number of requested tokens will exceed collection size");
require(count <= TOKENS_PER_TRAN_LIMIT, "Requested token count exceeds allowance (2)");
if(saleStatus == SaleStatus.PRESALE) {
require(msg.value >= count * PRESALE_MINT_PRICE, "Ether value sent is not sufficient");
require(_whitelistMintedCount[msg.sender] + count <= TOKENS_PER_PERSON_WL_LIMIT, "Requested token count exceeds allowance (2)");
bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
require(MerkleProof.verify(merkleProof, merkleRoot, leaf), "You are not whitelisted");
_whitelistMintedCount[msg.sender] += count;
}
else {
require(msg.value >= count * MINT_PRICE, "Ether value sent is not sufficient");
require(_mintedCount[msg.sender] + count <= TOKENS_PER_PERSON_PUB_LIMIT, "Requested token count exceeds allowance (2)");
_mintedCount[msg.sender] += count;
}
_mintTokens(msg.sender, count);
}
/// @dev Perform actual minting of the tokens
function _mintTokens(address to, uint count) internal {
for(uint index = 0; index < count; index++) {
_tokenIds.increment();
uint newItemId = _tokenIds.current();
_safeMint(to, newItemId);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol)
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) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
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 = _efficientHash(computedHash, proofElement);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = _efficientHash(proofElement, computedHash);
}
}
return computedHash;
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
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 {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// 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 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
} | Update current sale stage | function setSaleStatus(SaleStatus status) external onlyOwner {
saleStatus = status;
}
| 183,135 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
interface ICalculator {
function price() external view returns (uint256);
}
contract TBDPass is ERC1155, Ownable, ReentrancyGuard {
using ECDSA for bytes32;
// - events
event BurnerStateChanged(address indexed burner, bool indexed newState);
event ContractToggled(bool indexed newState);
event FloatingCapUpdated(uint256 indexed newCap);
event PriceCalculatorUpdated(address indexed calc);
event VerifiedSignerSet(address indexed signer);
// - constants
uint256 public constant PASS_ID = 0;
uint256 public constant STAGE1_CAP = 2000; // initial floating cap
uint256 public constant RESERVE_CAP = 2000; // global limit on the tokens mintable by owner
uint256 public constant HARD_CAP = 10000; // global limit on the tokens mintable by anyone
uint256 public constant MAX_MINT = 250; // global per-account limit of mintable tokens
uint256 public constant PRICE = .06 ether; // initial token price
uint256 public constant PRICE_INCREMENT = .05 ether; // increment it by this amount
uint256 public constant PRICE_TIER_SIZE = 500; // every ... tokens
address private constant TIP_RECEIVER =
0x3a6E4D326aeb315e85E3ac0A918361672842a496; //
// - storage variables;
uint256 public totalSupply; // all tokens minted
uint256 public reserveSupply; // minted by owner; never exceeds RESERVE_CAP
uint256 public reserveSupplyThisPeriod; // minted by owner this release period, never exceeds reserveCap
uint256 public reserveCapThisPeriod; // current reserve cap; never exceeds RESERVE_CAP - reserveSupply
uint256 public floatingCap; // current upper boundary of the floating cap; never exceeds HARD_CAP
uint256 public releasePeriod; // counter of floating cap updates; changing this invalidates wl signatures
bool public paused; // control wl minting and at-cost minting
address public verifiedSigner; // wl requests must be signed by this account
ICalculator public calculator; // external price source
mapping(address => bool) public burners; // accounts allowed to burn tokens
mapping(uint256 => mapping(address => uint256)) public allowances; // tracked wl allowances for current release cycle
mapping(address => uint256) public mints; // lifetime accumulators for tokens minted
constructor() ERC1155("https://studio-tbd.io/tokens/default.json") {
floatingCap = STAGE1_CAP;
}
function price() external view returns (uint256) {
return _price();
}
function getAllowance() external view returns (uint256) {
uint256 allowance = allowances[releasePeriod][msg.sender];
if (allowance > 1) {
return allowance - 1;
} else {
return 0;
}
}
function whitelistMint(
uint256 qt,
uint256 initialAllowance,
bytes calldata signature
) external {
_whenNotPaused();
// Signatures from previous `releasePeriod`s will not check out.
_validSignature(msg.sender, initialAllowance, signature);
// Set account's allowance on first use of the signature.
// The +1 offset allows to distinguish between a) first-time
// call; and b) fully claimed allowance. If the first use tx
// executes successfully, ownce never goes below 1.
mapping(address => uint256) storage ownce = allowances[releasePeriod];
if (ownce[msg.sender] == 0) {
ownce[msg.sender] = initialAllowance + 1;
}
// The actual allowance is always ownce -1;
// must be above 0 to proceed.
uint256 allowance = ownce[msg.sender] - 1;
require(allowance > 0, "OutOfAllowance");
// If the qt requested is 0, mint up to max allowance:
uint256 qt_ = (qt == 0)? allowance : qt;
// qt_ is never 0, since if it's 0, it assumes allowance,
// and that would revert earlier if 0.
assert(qt_ > 0);
// It is possible, however, that qt is non-zero and exceeds allowance:
require(qt_ <= allowance, "MintingExceedsAllowance");
// Observe lifetime per-account limit:
require(qt_ + mints[msg.sender] <= MAX_MINT, "MintingExceedsLifetimeLimit");
// In order to assess whether it's cool to extend the floating cap by qt_,
// calculate the extension upper bound. The gist: extend as long as
// the team's reserve is guarded.
uint256 reserveVault = (RESERVE_CAP - reserveSupply) - (reserveCapThisPeriod - reserveSupplyThisPeriod);
uint256 extensionMintable = HARD_CAP - floatingCap - reserveVault;
// split between over-the-cap supply and at-cost supply
uint256 mintableAtCost = _mintableAtCost();
uint256 wlMintable = extensionMintable + mintableAtCost;
require(qt_ <= wlMintable, "MintingExceedsAvailableSupply");
// adjust fc
floatingCap += (qt_ > extensionMintable)? extensionMintable : qt_;
// decrease caller's allowance in the current period
ownce[msg.sender] -= qt_;
_mintN(msg.sender, qt_);
}
function mint(uint256 qt) external payable {
_whenNotPaused();
require(qt > 0, "ZeroTokensRequested");
require(qt <= _mintableAtCost(), "MintingExceedsFloatingCap");
require(
mints[msg.sender] + qt <= MAX_MINT,
"MintingExceedsLifetimeLimit"
);
require(qt * _price() == msg.value, "InvalidETHAmount");
_mintN(msg.sender, qt);
}
function withdraw() external {
_onlyOwner();
uint256 tip = address(this).balance * 2 / 100;
payable(TIP_RECEIVER).transfer(tip);
payable(owner()).transfer(address(this).balance);
}
function setCalculator(address calc) external {
_onlyOwner();
require(calc != address(0), "ZeroCalculatorAddress");
emit PriceCalculatorUpdated(calc);
calculator = ICalculator(calc);
}
function setVerifiedSigner(address signer) external {
_onlyOwner();
require(signer != address(0), "ZeroSignerAddress");
emit VerifiedSignerSet(signer);
verifiedSigner = signer;
}
function setFloatingCap(uint256 cap, uint256 reserve) external {
_onlyOwner();
require(reserveSupply + reserve <= RESERVE_CAP, "OwnerReserveExceeded");
require(cap >= floatingCap, "CapUnderCurrentFloatingCap");
require(cap <= HARD_CAP, "HardCapExceeded");
require((RESERVE_CAP - reserveSupply - reserve) <= (HARD_CAP - cap),
"OwnerReserveViolation");
require(cap - totalSupply >= reserve, "ReserveExceedsTokensAvailable");
reserveCapThisPeriod = reserve;
reserveSupplyThisPeriod = 0;
emit FloatingCapUpdated(cap);
floatingCap = cap;
_nextPeriod();
}
function reduceReserve(uint256 to) external {
_onlyOwner();
require(to >= reserveSupplyThisPeriod, "CannotDecreaseBelowMinted");
require(to < reserveCapThisPeriod, "CannotIncreaseReserve");
// supply above floatingCap must be still sufficient to compensate
// for potentially excessive reduction
uint256 capExcess = HARD_CAP - floatingCap;
bool reserveViolated = capExcess < (RESERVE_CAP - reserveSupply) - (to - reserveSupplyThisPeriod);
require(!reserveViolated, "OwnerReserveViolation");
reserveCapThisPeriod = to;
}
function nextPeriod() external {
_onlyOwner();
_nextPeriod();
}
function setBurnerState(address burner, bool state) external {
_onlyOwner();
require(burner != address(0), "ZeroBurnerAddress");
emit BurnerStateChanged(burner, state);
burners[burner] = state;
}
function burn(address holder, uint256 qt) external {
_onlyBurners();
_burn(holder, PASS_ID, qt);
_mint(0x000000000000000000000000000000000000dEaD, PASS_ID, qt, "");
}
function setURI(string memory uri_) external {
_onlyOwner();
_setURI(uri_);
}
function toggle() external {
_onlyOwner();
emit ContractToggled(!paused);
paused = !paused;
}
function teamdrop(address to, uint256 qt) external {
_onlyOwner();
require(to != address(0), "ZeroReceiverAddress");
require(qt > 0, "ZeroTokensRequested");
require(releasePeriod > 0, "PrematureMintingByOwner");
require(reserveSupplyThisPeriod + qt <= reserveCapThisPeriod, "MintingExceedsPeriodReserve");
reserveSupply += qt;
reserveSupplyThisPeriod += qt;
_mintN(to, qt);
}
// - internals
function _nextPeriod() internal {
releasePeriod++;
}
function _mintN(address to, uint256 qt) internal nonReentrant {
totalSupply += qt;
mints[to] += qt;
_mint(to, PASS_ID, qt, "");
}
function _mintableAtCost() internal view returns (uint256) {
return floatingCap - totalSupply -
(reserveCapThisPeriod - reserveSupplyThisPeriod);
}
function _onlyOwner() internal view {
require(msg.sender == owner(), "UnauthorizedAccess");
}
function _onlyBurners() internal view {
require(burners[msg.sender], "UnauthorizedAccess");
}
function _whenNotPaused() internal view {
require(!paused, "ContractPaused");
}
function _validSignature(
address account,
uint256 allowance,
bytes calldata signature
) internal view {
bytes32 hash = keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
keccak256(abi.encodePacked(account, releasePeriod, allowance))
)
);
require(
hash.recover(signature) == verifiedSigner,
"InvalidSignature."
);
}
function _price() internal view returns (uint256 price_) {
if (calculator != ICalculator(address(0))) {
price_ = calculator.price();
} else {
price_ = PRICE + PRICE_INCREMENT * (totalSupply / PRICE_TIER_SIZE);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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;
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 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: 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/ERC1155/ERC1155.sol)
pragma solidity ^0.8.0;
import "./IERC1155.sol";
import "./IERC1155Receiver.sol";
import "./extensions/IERC1155MetadataURI.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: MIT
// 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 (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/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 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol)
pragma solidity ^0.8.0;
import "../IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// 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);
} | supply above floatingCap must be still sufficient to compensate for potentially excessive reduction | function reduceReserve(uint256 to) external {
_onlyOwner();
require(to >= reserveSupplyThisPeriod, "CannotDecreaseBelowMinted");
require(to < reserveCapThisPeriod, "CannotIncreaseReserve");
uint256 capExcess = HARD_CAP - floatingCap;
bool reserveViolated = capExcess < (RESERVE_CAP - reserveSupply) - (to - reserveSupplyThisPeriod);
require(!reserveViolated, "OwnerReserveViolation");
reserveCapThisPeriod = to;
}
| 11,927,730 |
pragma solidity ^0.5.16;
import "./CErc20.sol";
/**
* @title Compound's CErc20Immutable Contract
* @notice CTokens which wrap an EIP-20 underlying and are immutable
* @author Compound
*/
contract CErc20Immutable is CErc20 {
/**
* @notice Construct a new money market
* @param underlying_ The address of the underlying asset
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param admin_ Address of the administrator of this token
*/
constructor(address underlying_,
ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_,
address payable admin_) public {
// Creator of the contract is admin during initialization
admin = msg.sender;
// Initialize the market
initialize(underlying_, comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);
// Set the proper admin now that initialization is done
admin = admin_;
}
}
pragma solidity ^0.5.16;
import "./CToken.sol";
/**
* @title Compound's CErc20 Contract
* @notice CTokens which wrap an EIP-20 underlying
* @author Compound
*/
contract CErc20 is CToken, CErc20Interface {
/**
* @notice Initialize the new money market
* @param underlying_ The address of the underlying asset
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
*/
function initialize(address underlying_,
ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
// CToken initialize does the bulk of the work
super.initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);
// Set underlying and sanity check it
underlying = underlying_;
EIP20Interface(underlying).totalSupply();
}
/*** User Interface ***/
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(uint mintAmount) external returns (uint) {
(uint err,) = mintInternal(mintAmount);
return err;
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeem(uint redeemTokens) external returns (uint) {
return redeemInternal(redeemTokens);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to redeem
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint redeemAmount) external returns (uint) {
return redeemUnderlyingInternal(redeemAmount);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(uint borrowAmount) external returns (uint) {
return borrowInternal(borrowAmount);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrow(uint repayAmount) external returns (uint) {
(uint err,) = repayBorrowInternal(repayAmount);
return err;
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint) {
(uint err,) = repayBorrowBehalfInternal(borrower, repayAmount);
return err;
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param repayAmount The amount of the underlying borrowed asset to repay
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint) {
(uint err,) = liquidateBorrowInternal(borrower, repayAmount, cTokenCollateral);
return err;
}
/**
* @notice The sender adds to reserves.
* @param addAmount The amount fo underlying token to add as reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReserves(uint addAmount) external returns (uint) {
return _addReservesInternal(addAmount);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying tokens owned by this contract
*/
function getCashPrior() internal view returns (uint) {
EIP20Interface token = EIP20Interface(underlying);
return token.balanceOf(address(this));
}
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.
* This will revert due to insufficient balance or insufficient allowance.
* This function returns the actual amount received,
* which may be less than `amount` if there is a fee attached to the transfer.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferIn(address from, uint amount) internal returns (uint) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this));
token.transferFrom(from, address(this), amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a compliant ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_IN_FAILED");
// Calculate the amount that was *actually* transferred
uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this));
require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW");
return balanceAfter - balanceBefore; // underflow already checked above, just subtract
}
/**
* @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory
* error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to
* insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified
* it is >= amount, this should not revert in normal conditions.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferOut(address payable to, uint amount) internal {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
token.transfer(to, amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a complaint ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_OUT_FAILED");
}
}
pragma solidity ^0.5.16;
import "./ComptrollerInterface.sol";
import "./CTokenInterfaces.sol";
import "./ErrorReporter.sol";
import "./Exponential.sol";
import "./EIP20Interface.sol";
import "./EIP20NonStandardInterface.sol";
import "./InterestRateModel.sol";
/**
* @title Compound's CToken Contract
* @notice Abstract base for CTokens
* @author Compound
*/
contract CToken is CTokenInterface, Exponential, TokenErrorReporter {
/**
* @notice Initialize the money market
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
*/
function initialize(ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
require(msg.sender == admin, "only admin may initialize the market");
require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero.");
// Set the comptroller
uint err = _setComptroller(comptroller_);
require(err == uint(Error.NO_ERROR), "setting comptroller failed");
// Initialize block number and borrow index (block number mocks depend on comptroller being set)
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block number / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint(Error.NO_ERROR), "setting interest rate model failed");
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
/* Fail if transfer not allowed */
uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
MathError mathErr;
uint allowanceNew;
uint srcTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
}
(mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = srcTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
comptroller.transferVerify(address(this), src, dst, tokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
(MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
require(mErr == MathError.NO_ERROR, "balance could not be calculated");
return balance;
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by comptroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) {
uint cTokenBalance = accountTokens[account];
uint borrowBalance;
uint exchangeRateMantissa;
MathError mErr;
(mErr, borrowBalance) = borrowBalanceStoredInternal(account);
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
(mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this cToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this cToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external view returns (uint) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return totalBorrows;
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public view returns (uint) {
(MathError err, uint result) = borrowBalanceStoredInternal(account);
require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed");
return result;
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return (error code, the calculated balance or 0 if error code is non-zero)
*/
function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
/* Note: we do not assert that the market is up to date */
MathError mathErr;
uint principalTimesIndex;
uint result;
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
/* If borrowBalance = 0 then borrowIndex is likely also 0.
* Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
*/
if (borrowSnapshot.principal == 0) {
return (MathError.NO_ERROR, 0);
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
(mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, result);
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public view returns (uint) {
(MathError err, uint result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed");
return result;
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return (error code, calculated exchange rate scaled by 1e18)
*/
function exchangeRateStoredInternal() internal view returns (MathError, uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return (MathError.NO_ERROR, initialExchangeRateMantissa);
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves;
Exp memory exchangeRate;
MathError mathErr;
(mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, exchangeRate.mantissa);
}
}
/**
* @notice Get cash balance of this cToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint) {
return getCashPrior();
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
/* Calculate the number of blocks elapsed since the last accrual */
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calculate block delta");
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor;
uint interestAccumulated;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockNumber = currentBlockNumber;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount);
}
struct MintLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives cTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
/* Fail if mint not allowed */
uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the cToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of cTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
/*
* We calculate the new total supply of cTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming cTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, 0, redeemAmount);
}
struct RedeemLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems cTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero");
RedeemLocalVars memory vars;
/* exchangeRate = invoke Exchange Rate Stored() */
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
}
/* If redeemTokensIn > 0: */
if (redeemTokensIn > 0) {
/*
* We calculate the exchange rate and the amount of underlying to be redeemed:
* redeemTokens = redeemTokensIn
* redeemAmount = redeemTokensIn x exchangeRateCurrent
*/
vars.redeemTokens = redeemTokensIn;
(vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
}
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
(vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
}
vars.redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
(vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(redeemer, vars.redeemAmount);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);
/* We call the defense hook */
comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount);
}
struct BorrowLocalVars {
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
/* Fail if borrow not allowed */
uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
comptroller.borrowVerify(address(this), borrower, borrowAmount);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, borrower, repayAmount);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualRepayAmount;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
error = cTokenCollateral.accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify cTokenCollateral market's block number equals current block number */
if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount);
require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(cTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens);
/* We call the defense hook */
comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another cToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken.
* Its absolutely critical to use msg.sender as the seizer cToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed cToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
/* Fail if seize not allowed */
uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
MathError mathErr;
uint borrowerTokensNew;
uint liquidatorTokensNew;
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
(mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr));
}
(mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
/* We call the defense hook */
comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
return uint(Error.NO_ERROR);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new comptroller for the market
* @dev Admin function to set a new comptroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
}
ComptrollerInterface oldComptroller = comptroller;
// Ensure invoke comptroller.isComptroller() returns true
require(newComptroller.isComptroller(), "marker method returned false");
// Set market's comptroller to newComptroller
comptroller = newComptroller;
// Emit NewComptroller(oldComptroller, newComptroller)
emit NewComptroller(oldComptroller, newComptroller);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error, ) = _addReservesFresh(addAmount);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
*/
function _addReservesFresh(uint addAmount) internal returns (uint, uint) {
// totalReserves + actualAddAmount
uint totalReservesNew;
uint actualAddAmount;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
actualAddAmount = doTransferIn(msg.sender, addAmount);
totalReservesNew = totalReserves + actualAddAmount;
/* Revert on overflow */
require(totalReservesNew >= totalReserves, "add reserves unexpected overflow");
// Store reserves[n+1] = reserves[n] + actualAddAmount
totalReserves = totalReservesNew;
/* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
/* Return (NO_ERROR, actualAddAmount) */
return (uint(Error.NO_ERROR), actualAddAmount);
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
return _reduceReservesFresh(reduceAmount);
}
/**
* @notice Reduces reserves by transferring to admin
* @dev Requires fresh interest accrual
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
// totalReserves - reduceAmount
uint totalReservesNew;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
// Check reduceAmount ≤ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = totalReserves - reduceAmount;
// We checked reduceAmount <= totalReserves above, so this should never revert.
require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow");
// Store reserves[n+1] = reserves[n] - reduceAmount
totalReserves = totalReservesNew;
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
doTransferOut(admin, reduceAmount);
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
}
// _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
return _setInterestRateModelFresh(newInterestRateModel);
}
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) {
// Used to store old model for use in the event that is emitted on success
InterestRateModel oldInterestRateModel;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
}
// Track the market's current interest rate model
oldInterestRateModel = interestRateModel;
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal view returns (uint);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint amount) internal returns (uint);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address payable to, uint amount) internal;
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
}
pragma solidity ^0.5.16;
contract ComptrollerInterface {
/// @notice Indicator that this is a Comptroller contract (for inspection)
bool public constant isComptroller = true;
/*** Assets You Are In ***/
function enterMarkets(address[] calldata cTokens) external returns (uint[] memory);
function exitMarket(address cToken) external returns (uint);
/*** Policy Hooks ***/
function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint);
function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external;
function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint);
function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external;
function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint);
function borrowVerify(address cToken, address borrower, uint borrowAmount) external;
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint repayAmount) external returns (uint);
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint repayAmount,
uint borrowerIndex) external;
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint);
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount,
uint seizeTokens) external;
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint);
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external;
function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint);
function transferVerify(address cToken, address src, address dst, uint transferTokens) external;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address cTokenBorrowed,
address cTokenCollateral,
uint repayAmount) external view returns (uint, uint);
}
pragma solidity ^0.5.16;
import "./ComptrollerInterface.sol";
import "./InterestRateModel.sol";
contract CTokenStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Maximum borrow rate that can ever be applied (.0005% / block)
*/
uint internal constant borrowRateMaxMantissa = 0.0005e16;
/**
* @notice Maximum fraction of interest that can be set aside for reserves
*/
uint internal constant reserveFactorMaxMantissa = 1e18;
/**
* @notice Administrator for this contract
*/
address payable public admin;
/**
* @notice Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @notice Contract which oversees inter-cToken operations
*/
ComptrollerInterface public comptroller;
/**
* @notice Model which tells what the current interest rate should be
*/
InterestRateModel public interestRateModel;
/**
* @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0)
*/
uint internal initialExchangeRateMantissa;
/**
* @notice Fraction of interest currently set aside for reserves
*/
uint public reserveFactorMantissa;
/**
* @notice Block number that interest was last accrued at
*/
uint public accrualBlockNumber;
/**
* @notice Accumulator of the total earned interest rate since the opening of the market
*/
uint public borrowIndex;
/**
* @notice Total amount of outstanding borrows of the underlying in this market
*/
uint public totalBorrows;
/**
* @notice Total amount of reserves of the underlying held in this market
*/
uint public totalReserves;
/**
* @notice Total number of tokens in circulation
*/
uint public totalSupply;
/**
* @notice Official record of token balances for each account
*/
mapping (address => uint) internal accountTokens;
/**
* @notice Approved token transfer amounts on behalf of others
*/
mapping (address => mapping (address => uint)) internal transferAllowances;
/**
* @notice Container for borrow balance information
* @member principal Total balance (with accrued interest), after applying the most recent balance-changing action
* @member interestIndex Global borrowIndex as of the most recent balance-changing action
*/
struct BorrowSnapshot {
uint principal;
uint interestIndex;
}
/**
* @notice Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) internal accountBorrows;
}
contract CTokenInterface is CTokenStorage {
/**
* @notice Indicator that this is a CToken contract (for inspection)
*/
bool public constant isCToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint mintAmount, uint mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint redeemAmount, uint redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when comptroller is changed
*/
event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/**
* @notice Failure event
*/
event Failure(uint error, uint info, uint detail);
/*** User Interface ***/
function transfer(address dst, uint amount) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function borrowBalanceStored(address account) public view returns (uint);
function exchangeRateCurrent() public returns (uint);
function exchangeRateStored() public view returns (uint);
function getCash() external view returns (uint);
function accrueInterest() public returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint);
function _acceptAdmin() external returns (uint);
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint);
function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint);
function _reduceReserves(uint reduceAmount) external returns (uint);
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint);
}
contract CErc20Storage {
/**
* @notice Underlying asset for this CToken
*/
address public underlying;
}
contract CErc20Interface is CErc20Storage {
/*** User Interface ***/
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint);
/*** Admin Functions ***/
function _addReserves(uint addAmount) external returns (uint);
}
contract CDelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract CDelegatorInterface is CDelegationStorage {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public;
}
contract CDelegateInterface is CDelegationStorage {
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @dev Should revert if any issues arise which make it unfit for delegation
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public;
}
pragma solidity ^0.5.16;
contract ComptrollerErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
COMPTROLLER_MISMATCH,
INSUFFICIENT_SHORTFALL,
INSUFFICIENT_LIQUIDITY,
INVALID_CLOSE_FACTOR,
INVALID_COLLATERAL_FACTOR,
INVALID_LIQUIDATION_INCENTIVE,
MARKET_NOT_ENTERED, // no longer possible
MARKET_NOT_LISTED,
MARKET_ALREADY_LISTED,
MATH_ERROR,
NONZERO_BORROW_BALANCE,
PRICE_ERROR,
REJECTION,
SNAPSHOT_ERROR,
TOO_MANY_ASSETS,
TOO_MUCH_REPAY
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
EXIT_MARKET_BALANCE_OWED,
EXIT_MARKET_REJECTION,
SET_CLOSE_FACTOR_OWNER_CHECK,
SET_CLOSE_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_NO_EXISTS,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
SET_IMPLEMENTATION_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_VALIDATION,
SET_MAX_ASSETS_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
SET_PRICE_ORACLE_OWNER_CHECK,
SUPPORT_MARKET_EXISTS,
SUPPORT_MARKET_OWNER_CHECK,
SET_PAUSE_GUARDIAN_OWNER_CHECK
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
contract TokenErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
BAD_INPUT,
COMPTROLLER_REJECTION,
COMPTROLLER_CALCULATION_ERROR,
INTEREST_RATE_MODEL_ERROR,
INVALID_ACCOUNT_PAIR,
INVALID_CLOSE_AMOUNT_REQUESTED,
INVALID_COLLATERAL_FACTOR,
MATH_ERROR,
MARKET_NOT_FRESH,
MARKET_NOT_LISTED,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_IN_FAILED,
TOKEN_TRANSFER_OUT_FAILED
}
/*
* Note: FailureInfo (but not Error) is kept in alphabetical order
* This is because FailureInfo grows significantly faster, and
* the order of Error has some meaning, while the order of FailureInfo
* is entirely arbitrary.
*/
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,
ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
BORROW_ACCRUE_INTEREST_FAILED,
BORROW_CASH_NOT_AVAILABLE,
BORROW_FRESHNESS_CHECK,
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
BORROW_MARKET_NOT_LISTED,
BORROW_COMPTROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_COMPTROLLER_REJECTION,
LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,
LIQUIDATE_FRESHNESS_CHECK,
LIQUIDATE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_REPAY_BORROW_FRESH_FAILED,
LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,
LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,
LIQUIDATE_SEIZE_COMPTROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_COMPTROLLER_REJECTION,
MINT_EXCHANGE_CALCULATION_FAILED,
MINT_EXCHANGE_RATE_READ_FAILED,
MINT_FRESHNESS_CHECK,
MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_COMPTROLLER_REJECTION,
REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,
REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,
REDEEM_EXCHANGE_RATE_READ_FAILED,
REDEEM_FRESHNESS_CHECK,
REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
REDEEM_TRANSFER_OUT_NOT_POSSIBLE,
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,
REDUCE_RESERVES_ADMIN_CHECK,
REDUCE_RESERVES_CASH_NOT_AVAILABLE,
REDUCE_RESERVES_FRESH_CHECK,
REDUCE_RESERVES_VALIDATION,
REPAY_BEHALF_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_COMPTROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COMPTROLLER_OWNER_CHECK,
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,
SET_INTEREST_RATE_MODEL_FRESH_CHECK,
SET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_MAX_ASSETS_OWNER_CHECK,
SET_ORACLE_MARKET_NOT_LISTED,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,
SET_RESERVE_FACTOR_ADMIN_CHECK,
SET_RESERVE_FACTOR_FRESH_CHECK,
SET_RESERVE_FACTOR_BOUNDS_CHECK,
TRANSFER_COMPTROLLER_REJECTION,
TRANSFER_NOT_ALLOWED,
TRANSFER_NOT_ENOUGH,
TRANSFER_TOO_MUCH,
ADD_RESERVES_ACCRUE_INTEREST_FAILED,
ADD_RESERVES_FRESH_CHECK,
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
pragma solidity ^0.5.16;
import "./CarefulMath.sol";
import "./ExponentialNoError.sol";
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @dev Legacy contract for compatibility reasons with existing contracts that still use MathError
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential is CarefulMath, ExponentialNoError {
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
}
pragma solidity ^0.5.16;
/**
* @title ERC 20 Token Standard Interface
* https://eips.ethereum.org/EIPS/eip-20
*/
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool success);
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool success);
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
pragma solidity ^0.5.16;
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface EIP20NonStandardInterface {
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transferFrom(address src, address dst, uint256 amount) external;
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
pragma solidity ^0.5.16;
/**
* @title Compound's InterestRateModel Interface
* @author Compound
*/
contract InterestRateModel {
/// @notice Indicator that this is an InterestRateModel contract (for inspection)
bool public constant isInterestRateModel = true;
/**
* @notice Calculates the current borrow interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @return The borrow rate per block (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint);
/**
* @notice Calculates the current supply interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per block (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint);
}
pragma solidity ^0.5.16;
/**
* @title Careful Math
* @author Compound
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
pragma solidity ^0.5.16;
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract ExponentialNoError {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return truncate(product);
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return add_(truncate(product), addend);
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
}
| Return the borrow balance of account based on stored data account The address whose balance should be calculated return (error code, the calculated balance or 0 if error code is non-zero)/ Note: we do not assert that the market is up to date / Get borrowBalance and borrowIndex / If borrowBalance = 0 then borrowIndex is likely also 0. Rather than failing the calculation with a division by 0, we immediately return 0 in this case./ | function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
MathError mathErr;
uint principalTimesIndex;
uint result;
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
if (borrowSnapshot.principal == 0) {
return (MathError.NO_ERROR, 0);
}
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, result);
}
| 17,582 |
./partial_match/42/0xce0454371c7e1c1a6c3408E01F7e2CdCd9591c2f/sources/YieldMasterFarm.sol | Update reward variables of the given pool to be up-to-date. | function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 sharesTotal = IStrategy(pool.strat).sharesTotal();
if (sharesTotal == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
if (multiplier <= 0) {
return;
}
uint256 YieldMasterReward =
multiplier.mul(YieldMasterPerBlock).mul(pool.allocPoint).div(
totalAllocPoint
);
YieldMasterToken(YieldMaster).mint(
owner(),
YieldMasterReward.mul(ownerYieldMasterReward).div(1000)
);
YieldMasterToken(YieldMaster).mint(address(this), YieldMasterReward);
pool.accYieldMasterPerShare = pool.accYieldMasterPerShare.add(
YieldMasterReward.mul(1e12).div(sharesTotal)
);
pool.lastRewardBlock = block.number;
}
| 3,375,583 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.11;
pragma experimental ABIEncoderV2;
import "IERC20Upgradeable.sol";
import "SafeMathUpgradeable.sol";
import "AddressUpgradeable.sol";
import "SafeERC20Upgradeable.sol";
import "ISettV4.sol";
import "IController.sol";
import "ICvxLocker.sol";
import "ICVXBribes.sol";
import "IVotiumBribes.sol";
import "IDelegateRegistry.sol";
import "ICurvePool.sol";
import {BaseStrategy} from "BaseStrategy.sol";
/**
* CHANGELOG
* V1.0 Initial Release, can lock
* V1.1 Update to handle bribes which are sent to a multisig
*/
contract MyStrategy is BaseStrategy {
using SafeERC20Upgradeable for IERC20Upgradeable;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
uint256 public constant MAX_BPS = 10_000;
// address public want // Inherited from BaseStrategy, the token the strategy wants, swaps into and tries to grow
address public lpComponent; // Token we provide liquidity with
address public reward; // Token we farm and swap to want / lpComponent
address public constant BADGER_TREE = 0x660802Fc641b154aBA66a62137e71f331B6d787A;
IDelegateRegistry public constant SNAPSHOT =
IDelegateRegistry(0x469788fE6E9E9681C6ebF3bF78e7Fd26Fc015446);
// The initial DELEGATE for the strategy // NOTE we can change it by using manualSetDelegate below
address public constant DELEGATE =
0x14F83fF95D4Ec5E8812DDf42DA1232b0ba1015e6;
bytes32 public constant DELEGATED_SPACE =
0x6376782e65746800000000000000000000000000000000000000000000000000;
ISettV4 public constant CVXCRV_VAULT =
ISettV4(0x2B5455aac8d64C14786c3a29858E43b5945819C0);
// NOTE: At time of publishing, this contract is under audit
ICvxLocker public constant LOCKER = ICvxLocker(0xD18140b4B819b895A3dba5442F959fA44994AF50);
ICVXBribes public constant CVX_EXTRA_REWARDS = ICVXBribes(0x8Ed4bbf39E3080b35DA84a13A0D1A2FDcE1e0602);
IVotiumBribes public constant VOTIUM_BRIBE_CLAIMER = IVotiumBribes(0x378Ba9B73309bE80BF4C2c027aAD799766a7ED5A);
// We hardcode, an upgrade is required to change this as it's a meaningful change
address public constant BRIBES_RECEIVER = 0x6F76C6A1059093E21D8B1C13C4e20D8335e2909F;
bool public withdrawalSafetyCheck = false;
bool public harvestOnRebalance = false;
// If nothing is unlocked, processExpiredLocks will revert
bool public processLocksOnReinvest = false;
bool public processLocksOnRebalance = false;
// Used to signal to the Badger Tree that rewards where sent to it
event TreeDistribution(
address indexed token,
uint256 amount,
uint256 indexed blockNumber,
uint256 timestamp
);
event PerformanceFeeGovernance(
address indexed destination,
address indexed token,
uint256 amount,
uint256 indexed blockNumber,
uint256 timestamp
);
event PerformanceFeeStrategist(
address indexed destination,
address indexed token,
uint256 amount,
uint256 indexed blockNumber,
uint256 timestamp
);
function initialize(
address _governance,
address _strategist,
address _controller,
address _keeper,
address _guardian,
address[3] memory _wantConfig,
uint256[3] memory _feeConfig
) public initializer {
__BaseStrategy_init(
_governance,
_strategist,
_controller,
_keeper,
_guardian
);
/// @dev Add config here
want = _wantConfig[0];
lpComponent = _wantConfig[1];
reward = _wantConfig[2];
performanceFeeGovernance = _feeConfig[0];
performanceFeeStrategist = _feeConfig[1];
withdrawalFee = _feeConfig[2];
IERC20Upgradeable(reward).safeApprove(address(CVXCRV_VAULT), type(uint256).max);
/// @dev do one off approvals here
// Permissions for Locker
IERC20Upgradeable(want).safeApprove(address(LOCKER), type(uint256).max);
// Delegate voting to DELEGATE
SNAPSHOT.setDelegate(DELEGATED_SPACE, DELEGATE);
}
/// ===== Extra Functions =====
/// @dev Change Delegation to another address
function manualSetDelegate(address delegate) external {
_onlyGovernance();
// Set delegate is enough as it will clear previous delegate automatically
SNAPSHOT.setDelegate(DELEGATED_SPACE, delegate);
}
///@dev Should we check if the amount requested is more than what we can return on withdrawal?
function setWithdrawalSafetyCheck(bool newWithdrawalSafetyCheck) external {
_onlyGovernance();
withdrawalSafetyCheck = newWithdrawalSafetyCheck;
}
///@dev Should we harvest before doing manual rebalancing
///@notice you most likely want to skip harvest if everything is unlocked, or there's something wrong and you just want out
function setHarvestOnRebalance(bool newHarvestOnRebalance) external {
_onlyGovernance();
harvestOnRebalance = newHarvestOnRebalance;
}
///@dev Should we processExpiredLocks during reinvest?
function setProcessLocksOnReinvest(bool newProcessLocksOnReinvest) external {
_onlyGovernance();
processLocksOnReinvest = newProcessLocksOnReinvest;
}
///@dev Should we processExpiredLocks during manualRebalance?
function setProcessLocksOnRebalance(bool newProcessLocksOnRebalance)
external
{
_onlyGovernance();
processLocksOnRebalance = newProcessLocksOnRebalance;
}
/// *** Bribe Claiming ***
/// @dev given a token address, claim that as reward from CVX Extra Rewards
/// @notice funds are transfered to the hardcoded address BRIBES_RECEIVER
/// @notice for security reasons, you can't claim a bribe for a protected token
function claimBribeFromConvex (address token) external {
_onlyGovernanceOrStrategist();
// Revert if you try to claim a protected token, this is to avoid rugging
_onlyNotProtectedTokens(token);
// NOTE: If we end up getting bribes in form or protected tokens, we'll have to change
// Claim reward for token
CVX_EXTRA_REWARDS.getReward(address(this), token);
// Send reward to Multisig
uint256 toSend = IERC20Upgradeable(token).balanceOf(address(this));
IERC20Upgradeable(token).safeTransfer(BRIBES_RECEIVER, toSend);
}
/// @dev given a list of token addresses, claim that as reward from CVX Extra Rewards
/// @notice funds are transfered to the hardcoded address BRIBES_RECEIVER
/// @notice for security reasons, you can't claim a bribe for a protected token
function claimBribesFromConvex(address[] calldata tokens) external {
_onlyGovernanceOrStrategist();
// Revert if you try to claim a protected token, this is to avoid rugging
uint256 length = tokens.length;
for(uint i = 0; i < length; i++){
_onlyNotProtectedTokens(tokens[i]);
}
// NOTE: If we end up getting bribes in form or protected tokens, we'll have to change
// Claim reward for tokens
CVX_EXTRA_REWARDS.getRewards(address(this), tokens);
// Send reward to Multisig
for(uint x = 0; x < length; x++){
uint256 toSend = IERC20Upgradeable(tokens[x]).balanceOf(address(this));
IERC20Upgradeable(tokens[x]).safeTransfer(BRIBES_RECEIVER, toSend);
}
}
function claimBribeFromVotium(
address token,
uint256 index,
address account,
uint256 amount,
bytes32[] calldata merkleProof
) external {
_onlyGovernanceOrStrategist();
// Revert if you try to claim a protected token, this is to avoid rugging
_onlyNotProtectedTokens(token);
// NOTE: If we end up getting bribes in form or protected tokens, we'll have to change
VOTIUM_BRIBE_CLAIMER.claim(token, index, account, amount, merkleProof);
uint256 toSend = IERC20Upgradeable(token).balanceOf(address(this));
IERC20Upgradeable(token).safeTransfer(BRIBES_RECEIVER, toSend);
}
function claimBribesFromVotium(
address account,
address[] calldata tokens,
uint256[] calldata indexes,
uint256[] calldata amounts,
bytes32[][] calldata merkleProofs
) external {
_onlyGovernanceOrStrategist();
// Revert if you try to claim a protected token, this is to avoid rugging
uint256 length = tokens.length;
require(length == indexes.length && length == amounts.length && length == merkleProofs.length, "Length Mismatch");
for(uint i = 0; i < length; i++){
_onlyNotProtectedTokens(tokens[i]);
}
// NOTE: If we end up getting bribes in form or protected tokens, we'll have to change
IVotiumBribes.claimParam[] memory request = new IVotiumBribes.claimParam[](length);
for(uint x = 0; x < length; x++){
request[x] = IVotiumBribes.claimParam({
token: tokens[x],
index: indexes[x],
amount: amounts[x],
merkleProof: merkleProofs[x]
});
}
VOTIUM_BRIBE_CLAIMER.claimMulti(account, request);
for(uint i = 0; i < length; i++){
uint256 toSend = IERC20Upgradeable(tokens[i]).balanceOf(address(this));
IERC20Upgradeable(tokens[i]).safeTransfer(BRIBES_RECEIVER, toSend);
}
}
/// ===== View Functions =====
function getBoostPayment() public view returns(uint256){
uint256 maximumBoostPayment = LOCKER.maximumBoostPayment();
require(maximumBoostPayment <= 1500, "over max payment"); //max 15%
return maximumBoostPayment;
}
/// @dev Specify the name of the strategy
function getName() external pure override returns (string memory) {
return "veCVX Voting Strategy";
}
/// @dev Specify the version of the Strategy, for upgrades
function version() external pure returns (string memory) {
return "1.1";
}
/// @dev Balance of want currently held in strategy positions
function balanceOfPool() public view override returns (uint256) {
// Return the balance in locker
return LOCKER.lockedBalanceOf(address(this));
}
/// @dev Returns true if this strategy requires tending
function isTendable() public view override returns (bool) {
return false;
}
// @dev These are the tokens that cannot be moved except by the vault
function getProtectedTokens()
public
view
override
returns (address[] memory)
{
address[] memory protectedTokens = new address[](3);
protectedTokens[0] = want;
protectedTokens[1] = lpComponent;
protectedTokens[2] = reward;
return protectedTokens;
}
/// ===== Internal Core Implementations =====
/// @dev security check to avoid moving tokens that would cause a rugpull, edit based on strat
function _onlyNotProtectedTokens(address _asset) internal override {
address[] memory protectedTokens = getProtectedTokens();
for (uint256 x = 0; x < protectedTokens.length; x++) {
require(
address(protectedTokens[x]) != _asset,
"Asset is protected"
);
}
}
/// @dev invest the amount of want
/// @notice When this function is called, the controller has already sent want to this
/// @notice Just get the current balance and then invest accordingly
function _deposit(uint256 _amount) internal override {
// Lock tokens for 16 weeks, send credit to strat, always use max boost cause why not?
LOCKER.lock(address(this), _amount, getBoostPayment());
}
/// @dev utility function to withdraw all CVX that we can from the lock
function prepareWithdrawAll() external {
manualProcessExpiredLocks();
}
/// @dev utility function to withdraw everything for migration
/// @dev NOTE: You cannot call this unless you have rebalanced to have only CVX left in the vault
function _withdrawAll() internal override {
//NOTE: This probably will always fail unless we have all tokens expired
require(
LOCKER.lockedBalanceOf(address(this)) == 0 &&
LOCKER.balanceOf(address(this)) == 0,
"You have to wait for unlock or have to manually rebalance out of it"
);
// Make sure to call prepareWithdrawAll before _withdrawAll
}
/// @dev withdraw the specified amount of want, liquidate from lpComponent to want, paying off any necessary debt for the conversion
function _withdrawSome(uint256 _amount)
internal
override
returns (uint256)
{
uint256 max = IERC20Upgradeable(want).balanceOf(address(this));
if (withdrawalSafetyCheck) {
require(
max >= _amount.mul(9_980).div(MAX_BPS),
"Withdrawal Safety Check"
); // 20 BP of slippage
}
if (max < _amount) {
return max;
}
return _amount;
}
/// @dev Harvest from strategy mechanics, realizing increase in underlying position
function harvest() public whenNotPaused returns (uint256) {
_onlyAuthorizedActors();
uint256 _beforeReward = IERC20Upgradeable(reward).balanceOf(address(this));
// Get cvxCRV
LOCKER.getReward(address(this), false);
// Rewards Math
uint256 earnedReward =
IERC20Upgradeable(reward).balanceOf(address(this)).sub(_beforeReward);
uint256 cvxCrvToGovernance = earnedReward.mul(performanceFeeGovernance).div(MAX_FEE);
if(cvxCrvToGovernance > 0){
CVXCRV_VAULT.depositFor(IController(controller).rewards(), cvxCrvToGovernance);
emit PerformanceFeeGovernance(IController(controller).rewards(), address(CVXCRV_VAULT), cvxCrvToGovernance, block.number, block.timestamp);
}
uint256 cvxCrvToStrategist = earnedReward.mul(performanceFeeStrategist).div(MAX_FEE);
if(cvxCrvToStrategist > 0){
CVXCRV_VAULT.depositFor(strategist, cvxCrvToStrategist);
emit PerformanceFeeStrategist(strategist, address(CVXCRV_VAULT), cvxCrvToStrategist, block.number, block.timestamp);
}
// Send rest of earned to tree //We send all rest to avoid dust and avoid protecting the token
uint256 cvxCrvToTree = IERC20Upgradeable(reward).balanceOf(address(this));
CVXCRV_VAULT.depositFor(BADGER_TREE, cvxCrvToTree);
emit TreeDistribution(address(CVXCRV_VAULT), cvxCrvToTree, block.number, block.timestamp);
/// @dev Harvest event that every strategy MUST have, see BaseStrategy
emit Harvest(earnedReward, block.number);
/// @dev Harvest must return the amount of want increased
return earnedReward;
}
/// @dev Rebalance, Compound or Pay off debt here
function tend() external whenNotPaused {
revert("no op"); // NOTE: For now tend is replaced by manualRebalance
}
/// MANUAL FUNCTIONS ///
/// @dev manual function to reinvest all CVX that was locked
function reinvest() external whenNotPaused returns (uint256) {
_onlyGovernance();
if (processLocksOnReinvest) {
// Withdraw all we can
LOCKER.processExpiredLocks(false);
}
// Redeposit all into veCVX
uint256 toDeposit = IERC20Upgradeable(want).balanceOf(address(this));
// Redeposit into veCVX
_deposit(toDeposit);
return toDeposit;
}
/// @dev process all locks, to redeem
function manualProcessExpiredLocks() public whenNotPaused {
_onlyGovernance();
LOCKER.processExpiredLocks(false);
// Unlock veCVX that is expired and redeem CVX back to this strat
}
/// @dev Send all available CVX to the Vault
/// @notice you can do this so you can earn again (re-lock), or just to add to the redemption pool
function manualSendCVXToVault() external whenNotPaused {
_onlyGovernance();
uint256 cvxAmount = IERC20Upgradeable(want).balanceOf(address(this));
_transferToVault(cvxAmount);
}
/// @dev use the currently available CVX to lock
/// @notice toLock = 0, lock nothing, deposit in CVX as much as you can
/// @notice toLock = 10_000, lock everything (CVX) you have
function manualRebalance(uint256 toLock) external whenNotPaused {
_onlyGovernance();
require(toLock <= MAX_BPS, "Max is 100%");
if (processLocksOnRebalance) {
// manualRebalance will revert if you have no expired locks
LOCKER.processExpiredLocks(false);
}
if (harvestOnRebalance) {
harvest();
}
// Token that is highly liquid
uint256 balanceOfWant =
IERC20Upgradeable(want).balanceOf(address(this));
// Locked CVX in the locker
uint256 balanceInLock = LOCKER.balanceOf(address(this));
uint256 totalCVXBalance =
balanceOfWant.add(balanceInLock);
// Amount we want to have in lock
uint256 newLockAmount = totalCVXBalance.mul(toLock).div(MAX_BPS);
// We can't unlock enough, no-op
if (newLockAmount <= balanceInLock) {
return;
}
// If we're continuing, then we are going to lock something
uint256 cvxToLock = newLockAmount.sub(balanceInLock);
// We only lock up to the available CVX
uint256 maxCVX = IERC20Upgradeable(want).balanceOf(address(this));
if (cvxToLock > maxCVX) {
// Just lock what we can
LOCKER.lock(address(this), maxCVX, getBoostPayment());
} else {
// Lock proper
LOCKER.lock(address(this), cvxToLock, getBoostPayment());
}
// If anything left, send to vault
uint256 cvxLeft = IERC20Upgradeable(want).balanceOf(address(this));
if(cvxLeft > 0){
_transferToVault(cvxLeft);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount)
external
returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender)
external
view
returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
/**
* @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 in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage
) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) =
target.call{value: weiValue}(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "IERC20Upgradeable.sol";
import "SafeMathUpgradeable.sol";
import "AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
function safeTransfer(
IERC20Upgradeable token,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transfer.selector, to, value)
);
}
function safeTransferFrom(
IERC20Upgradeable token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transferFrom.selector, from, to, value)
);
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, value)
);
}
function safeIncreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
uint256 newAllowance =
token.allowance(address(this), spender).add(value);
_callOptionalReturn(
token,
abi.encodeWithSelector(
token.approve.selector,
spender,
newAllowance
)
);
}
function safeDecreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
uint256 newAllowance =
token.allowance(address(this), spender).sub(
value,
"SafeERC20: decreased allowance below zero"
);
_callOptionalReturn(
token,
abi.encodeWithSelector(
token.approve.selector,
spender,
newAllowance
)
);
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data)
private
{
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata =
address(token).functionCall(
data,
"SafeERC20: low-level call failed"
);
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(
abi.decode(returndata, (bool)),
"SafeERC20: ERC20 operation did not succeed"
);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.11;
pragma experimental ABIEncoderV2;
interface ISettV4 {
function deposit(uint256 _amount) external;
function depositFor(address _recipient, uint256 _amount) external;
function withdraw(uint256 _amount) external;
function getPricePerFullShare() external view returns (uint256);
function balanceOf(address) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0 <0.8.0;
interface IController {
function withdraw(address, uint256) external;
function strategies(address) external view returns (address);
function balanceOf(address) external view returns (uint256);
function earn(address, uint256) external;
function want(address) external view returns (address);
function rewards() external view returns (address);
function vaults(address) external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface ICvxLocker {
function maximumBoostPayment() external view returns (uint256);
function lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) external;
function getReward(address _account, bool _stake) external;
//BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch
function balanceOf(address _user) external view returns (uint256 amount);
// total token balance of an account, including unlocked but not withdrawn tokens
function lockedBalanceOf(address _user)
external
view
returns (uint256 amount);
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(
bool _relock,
uint256 _spendRatio,
address _withdrawTo
) external;
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(bool _relock) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface ICVXBribes {
function getReward(address _account, address _token) external;
function getRewards(address _account, address[] calldata _tokens) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface IVotiumBribes {
struct claimParam {
address token;
uint256 index;
uint256 amount;
bytes32[] merkleProof;
}
function claimMulti(address account, claimParam[] calldata claims) external;
function claim(address token, uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
///@dev Snapshot Delegate registry so we can delegate voting to XYZ
interface IDelegateRegistry {
function setDelegate(bytes32 id, address delegate) external;
function delegation(address, bytes32) external returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface ICurvePool {
function exchange(
int128 i,
int128 j,
uint256 _dx,
uint256 _min_dy
) external returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.11;
import "IERC20Upgradeable.sol";
import "SafeMathUpgradeable.sol";
import "MathUpgradeable.sol";
import "AddressUpgradeable.sol";
import "PausableUpgradeable.sol";
import "SafeERC20Upgradeable.sol";
import "Initializable.sol";
import "IUniswapRouterV2.sol";
import "IController.sol";
import "IStrategy.sol";
import "SettAccessControl.sol";
/*
===== Badger Base Strategy =====
Common base class for all Sett strategies
Changelog
V1.1
- Verify amount unrolled from strategy positions on withdraw() is within a threshold relative to the requested amount as a sanity check
- Add version number which is displayed with baseStrategyVersion(). If a strategy does not implement this function, it can be assumed to be 1.0
V1.2
- Remove idle want handling from base withdraw() function. This should be handled as the strategy sees fit in _withdrawSome()
*/
abstract contract BaseStrategy is PausableUpgradeable, SettAccessControl {
using SafeERC20Upgradeable for IERC20Upgradeable;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
event Withdraw(uint256 amount);
event WithdrawAll(uint256 balance);
event WithdrawOther(address token, uint256 amount);
event SetStrategist(address strategist);
event SetGovernance(address governance);
event SetController(address controller);
event SetWithdrawalFee(uint256 withdrawalFee);
event SetPerformanceFeeStrategist(uint256 performanceFeeStrategist);
event SetPerformanceFeeGovernance(uint256 performanceFeeGovernance);
event Harvest(uint256 harvested, uint256 indexed blockNumber);
event Tend(uint256 tended);
address public want; // Want: Curve.fi renBTC/wBTC (crvRenWBTC) LP token
uint256 public performanceFeeGovernance;
uint256 public performanceFeeStrategist;
uint256 public withdrawalFee;
uint256 public constant MAX_FEE = 10000;
address public constant uniswap =
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // Uniswap Dex
address public controller;
address public guardian;
uint256 public withdrawalMaxDeviationThreshold;
function __BaseStrategy_init(
address _governance,
address _strategist,
address _controller,
address _keeper,
address _guardian
) public initializer whenNotPaused {
__Pausable_init();
governance = _governance;
strategist = _strategist;
keeper = _keeper;
controller = _controller;
guardian = _guardian;
withdrawalMaxDeviationThreshold = 50;
}
// ===== Modifiers =====
function _onlyController() internal view {
require(msg.sender == controller, "onlyController");
}
function _onlyAuthorizedActorsOrController() internal view {
require(
msg.sender == keeper ||
msg.sender == governance ||
msg.sender == controller,
"onlyAuthorizedActorsOrController"
);
}
function _onlyAuthorizedPausers() internal view {
require(
msg.sender == guardian || msg.sender == governance,
"onlyPausers"
);
}
/// ===== View Functions =====
function baseStrategyVersion() public view returns (string memory) {
return "1.2";
}
/// @notice Get the balance of want held idle in the Strategy
function balanceOfWant() public view returns (uint256) {
return IERC20Upgradeable(want).balanceOf(address(this));
}
/// @notice Get the total balance of want realized in the strategy, whether idle or active in Strategy positions.
function balanceOf() public view virtual returns (uint256) {
return balanceOfWant().add(balanceOfPool());
}
function isTendable() public view virtual returns (bool) {
return false;
}
/// ===== Permissioned Actions: Governance =====
function setGuardian(address _guardian) external {
_onlyGovernance();
guardian = _guardian;
}
function setWithdrawalFee(uint256 _withdrawalFee) external {
_onlyGovernance();
require(
_withdrawalFee <= MAX_FEE,
"base-strategy/excessive-withdrawal-fee"
);
withdrawalFee = _withdrawalFee;
}
function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist)
external
{
_onlyGovernance();
require(
_performanceFeeStrategist <= MAX_FEE,
"base-strategy/excessive-strategist-performance-fee"
);
performanceFeeStrategist = _performanceFeeStrategist;
}
function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance)
external
{
_onlyGovernance();
require(
_performanceFeeGovernance <= MAX_FEE,
"base-strategy/excessive-governance-performance-fee"
);
performanceFeeGovernance = _performanceFeeGovernance;
}
function setController(address _controller) external {
_onlyGovernance();
controller = _controller;
}
function setWithdrawalMaxDeviationThreshold(uint256 _threshold) external {
_onlyGovernance();
require(
_threshold <= MAX_FEE,
"base-strategy/excessive-max-deviation-threshold"
);
withdrawalMaxDeviationThreshold = _threshold;
}
function deposit() public virtual whenNotPaused {
_onlyAuthorizedActorsOrController();
uint256 _want = IERC20Upgradeable(want).balanceOf(address(this));
if (_want > 0) {
_deposit(_want);
}
_postDeposit();
}
// ===== Permissioned Actions: Controller =====
/// @notice Controller-only function to Withdraw partial funds, normally used with a vault withdrawal
function withdrawAll()
external
virtual
whenNotPaused
returns (uint256 balance)
{
_onlyController();
_withdrawAll();
_transferToVault(IERC20Upgradeable(want).balanceOf(address(this)));
}
/// @notice Withdraw partial funds from the strategy, unrolling from strategy positions as necessary
/// @notice Processes withdrawal fee if present
/// @dev If it fails to recover sufficient funds (defined by withdrawalMaxDeviationThreshold), the withdrawal should fail so that this unexpected behavior can be investigated
function withdraw(uint256 _amount) external virtual whenNotPaused {
_onlyController();
// Withdraw from strategy positions, typically taking from any idle want first.
_withdrawSome(_amount);
uint256 _postWithdraw =
IERC20Upgradeable(want).balanceOf(address(this));
// Sanity check: Ensure we were able to retrieve sufficent want from strategy positions
// If we end up with less than the amount requested, make sure it does not deviate beyond a maximum threshold
if (_postWithdraw < _amount) {
uint256 diff = _diff(_amount, _postWithdraw);
// Require that difference between expected and actual values is less than the deviation threshold percentage
require(
diff <=
_amount.mul(withdrawalMaxDeviationThreshold).div(MAX_FEE),
"base-strategy/withdraw-exceed-max-deviation-threshold"
);
}
// Return the amount actually withdrawn if less than amount requested
uint256 _toWithdraw = MathUpgradeable.min(_postWithdraw, _amount);
// Process withdrawal fee
uint256 _fee = _processWithdrawalFee(_toWithdraw);
// Transfer remaining to Vault to handle withdrawal
_transferToVault(_toWithdraw.sub(_fee));
}
// NOTE: must exclude any tokens used in the yield
// Controller role - withdraw should return to Controller
function withdrawOther(address _asset)
external
virtual
whenNotPaused
returns (uint256 balance)
{
_onlyController();
_onlyNotProtectedTokens(_asset);
balance = IERC20Upgradeable(_asset).balanceOf(address(this));
IERC20Upgradeable(_asset).safeTransfer(controller, balance);
}
/// ===== Permissioned Actions: Authoized Contract Pausers =====
function pause() external {
_onlyAuthorizedPausers();
_pause();
}
function unpause() external {
_onlyGovernance();
_unpause();
}
/// ===== Internal Helper Functions =====
/// @notice If withdrawal fee is active, take the appropriate amount from the given value and transfer to rewards recipient
/// @return The withdrawal fee that was taken
function _processWithdrawalFee(uint256 _amount) internal returns (uint256) {
if (withdrawalFee == 0) {
return 0;
}
uint256 fee = _amount.mul(withdrawalFee).div(MAX_FEE);
IERC20Upgradeable(want).safeTransfer(
IController(controller).rewards(),
fee
);
return fee;
}
/// @dev Helper function to process an arbitrary fee
/// @dev If the fee is active, transfers a given portion in basis points of the specified value to the recipient
/// @return The fee that was taken
function _processFee(
address token,
uint256 amount,
uint256 feeBps,
address recipient
) internal returns (uint256) {
if (feeBps == 0) {
return 0;
}
uint256 fee = amount.mul(feeBps).div(MAX_FEE);
IERC20Upgradeable(token).safeTransfer(recipient, fee);
return fee;
}
/// @dev Reset approval and approve exact amount
function _safeApproveHelper(
address token,
address recipient,
uint256 amount
) internal {
IERC20Upgradeable(token).safeApprove(recipient, 0);
IERC20Upgradeable(token).safeApprove(recipient, amount);
}
function _transferToVault(uint256 _amount) internal {
address _vault = IController(controller).vaults(address(want));
require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20Upgradeable(want).safeTransfer(_vault, _amount);
}
/// @notice Swap specified balance of given token on Uniswap with given path
function _swap(
address startToken,
uint256 balance,
address[] memory path
) internal {
_safeApproveHelper(startToken, uniswap, balance);
IUniswapRouterV2(uniswap).swapExactTokensForTokens(
balance,
0,
path,
address(this),
now
);
}
function _swapEthIn(uint256 balance, address[] memory path) internal {
IUniswapRouterV2(uniswap).swapExactETHForTokens{value: balance}(
0,
path,
address(this),
now
);
}
function _swapEthOut(
address startToken,
uint256 balance,
address[] memory path
) internal {
_safeApproveHelper(startToken, uniswap, balance);
IUniswapRouterV2(uniswap).swapExactTokensForETH(
balance,
0,
path,
address(this),
now
);
}
/// @notice Add liquidity to uniswap for specified token pair, utilizing the maximum balance possible
function _add_max_liquidity_uniswap(address token0, address token1)
internal
virtual
{
uint256 _token0Balance =
IERC20Upgradeable(token0).balanceOf(address(this));
uint256 _token1Balance =
IERC20Upgradeable(token1).balanceOf(address(this));
_safeApproveHelper(token0, uniswap, _token0Balance);
_safeApproveHelper(token1, uniswap, _token1Balance);
IUniswapRouterV2(uniswap).addLiquidity(
token0,
token1,
_token0Balance,
_token1Balance,
0,
0,
address(this),
block.timestamp
);
}
/// @notice Utility function to diff two numbers, expects higher value in first position
function _diff(uint256 a, uint256 b) internal pure returns (uint256) {
require(a >= b, "diff/expected-higher-number-in-first-position");
return a.sub(b);
}
// ===== Abstract Functions: To be implemented by specific Strategies =====
/// @dev Internal deposit logic to be implemented by Stratgies
function _deposit(uint256 _amount) internal virtual;
function _postDeposit() internal virtual {
//no-op by default
}
/// @notice Specify tokens used in yield process, should not be available to withdraw via withdrawOther()
function _onlyNotProtectedTokens(address _asset) internal virtual;
function getProtectedTokens()
external
view
virtual
returns (address[] memory);
/// @dev Internal logic for strategy migration. Should exit positions as efficiently as possible
function _withdrawAll() internal virtual;
/// @dev Internal logic for partial withdrawals. Should exit positions as efficiently as possible.
/// @dev The withdraw() function shell automatically uses idle want in the strategy before attempting to withdraw more using this
function _withdrawSome(uint256 _amount) internal virtual returns (uint256);
/// @dev Realize returns from positions
/// @dev Returns can be reinvested into positions, or distributed in another fashion
/// @dev Performance fees should also be implemented in this function
/// @dev Override function stub is removed as each strategy can have it's own return signature for STATICCALL
// function harvest() external virtual;
/// @dev User-friendly name for this strategy for purposes of convenient reading
function getName() external pure virtual returns (string memory);
/// @dev Balance of want currently held in strategy positions
function balanceOfPool() public view virtual returns (uint256);
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
/**
* @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: MIT
pragma solidity ^0.6.0;
import "ContextUpgradeable.sol";
import "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.
*/
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 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.6.0;
import "Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
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.4.24 <0.7.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.5.0 <0.8.0;
interface IUniswapRouterV2 {
function factory() external view 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 getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}
// SPDX-License-Identifier: MIT
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0 <0.8.0;
interface IStrategy {
function want() external view returns (address);
function deposit() external;
// NOTE: must exclude any tokens used in the yield
// Controller role - withdraw should return to Controller
function withdrawOther(address) external returns (uint256 balance);
// Controller | Vault role - withdraw should always return to Vault
function withdraw(uint256) external;
// Controller | Vault role - withdraw should always return to Vault
function withdrawAll() external returns (uint256);
function balanceOf() external view returns (uint256);
function getName() external pure returns (string memory);
function setStrategist(address _strategist) external;
function setWithdrawalFee(uint256 _withdrawalFee) external;
function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist)
external;
function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance)
external;
function setGovernance(address _governance) external;
function setController(address _controller) external;
function tend() external;
function harvest() external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.11;
import "Initializable.sol";
/*
Common base for permissioned roles throughout Sett ecosystem
*/
contract SettAccessControl is Initializable {
address public governance;
address public strategist;
address public keeper;
// ===== MODIFIERS =====
function _onlyGovernance() internal view {
require(msg.sender == governance, "onlyGovernance");
}
function _onlyGovernanceOrStrategist() internal view {
require(
msg.sender == strategist || msg.sender == governance,
"onlyGovernanceOrStrategist"
);
}
function _onlyAuthorizedActors() internal view {
require(
msg.sender == keeper || msg.sender == governance,
"onlyAuthorizedActors"
);
}
// ===== PERMISSIONED ACTIONS =====
/// @notice Change strategist address
/// @notice Can only be changed by governance itself
function setStrategist(address _strategist) external {
_onlyGovernance();
strategist = _strategist;
}
/// @notice Change keeper address
/// @notice Can only be changed by governance itself
function setKeeper(address _keeper) external {
_onlyGovernance();
keeper = _keeper;
}
/// @notice Change governance address
/// @notice Can only be changed by governance itself
function setGovernance(address _governance) public {
_onlyGovernance();
governance = _governance;
}
uint256[50] private __gap;
} | given a list of token addresses, claim that as reward from CVX Extra Rewards funds are transfered to the hardcoded address BRIBES_RECEIVER for security reasons, you can't claim a bribe for a protected token Revert if you try to claim a protected token, this is to avoid rugging Send reward to Multisig | function claimBribesFromConvex(address[] calldata tokens) external {
_onlyGovernanceOrStrategist();
uint256 length = tokens.length;
for(uint i = 0; i < length; i++){
_onlyNotProtectedTokens(tokens[i]);
}
for(uint x = 0; x < length; x++){
uint256 toSend = IERC20Upgradeable(tokens[x]).balanceOf(address(this));
IERC20Upgradeable(tokens[x]).safeTransfer(BRIBES_RECEIVER, toSend);
}
}
| 12,249,690 |
// SPDX-License-Identifier: MIT
// File: contracts/true-currencies-new/ProxyStorage.sol
pragma solidity 0.6.10;
/**
* Defines the storage layout of the token implementation contract. Any
* newly declared state variables in future upgrades should be appended
* to the bottom. Never remove state variables from this list, however variables
* can be renamed. Please add _Deprecated to deprecated variables.
*/
contract ProxyStorage {
address public owner;
address public pendingOwner;
bool initialized;
address balances_Deprecated;
address allowances_Deprecated;
uint256 _totalSupply;
bool private paused_Deprecated = false;
address private globalPause_Deprecated;
uint256 public burnMin = 0;
uint256 public burnMax = 0;
address registry_Deprecated;
string name_Deprecated;
string symbol_Deprecated;
uint256[] gasRefundPool_Deprecated;
uint256 private redemptionAddressCount_Deprecated;
uint256 minimumGasPriceForFutureRefunds_Deprecated;
mapping(address => uint256) _balances;
mapping(address => mapping(address => uint256)) _allowances;
mapping(bytes32 => mapping(address => uint256)) attributes_Deprecated;
// reward token storage
mapping(address => address) finOps_Deprecated;
mapping(address => mapping(address => uint256)) finOpBalances_Deprecated;
mapping(address => uint256) finOpSupply_Deprecated;
// true reward allocation
// proportion: 1000 = 100%
struct RewardAllocation {
uint256 proportion;
address finOp;
}
mapping(address => RewardAllocation[]) _rewardDistribution_Deprecated;
uint256 maxRewardProportion_Deprecated = 1000;
mapping(address => bool) isBlacklisted;
mapping(address => bool) public canBurn;
/* Additionally, we have several keccak-based storage locations.
* If you add more keccak-based storage mappings, such as mappings, you must document them here.
* If the length of the keccak input is the same as an existing mapping, it is possible there could be a preimage collision.
* A preimage collision can be used to attack the contract by treating one storage location as another,
* which would always be a critical issue.
* Carefully examine future keccak-based storage to ensure there can be no preimage collisions.
*******************************************************************************************************
** length input usage
*******************************************************************************************************
** 19 "trueXXX.proxy.owner" Proxy Owner
** 27 "trueXXX.pending.proxy.owner" Pending Proxy Owner
** 28 "trueXXX.proxy.implementation" Proxy Implementation
** 32 uint256(11) gasRefundPool_Deprecated
** 64 uint256(address),uint256(14) balanceOf
** 64 uint256(address),keccak256(uint256(address),uint256(15)) allowance
** 64 uint256(address),keccak256(bytes32,uint256(16)) attributes
**/
}
// File: contracts/true-currencies-new/ClaimableOwnable.sol
pragma solidity 0.6.10;
/**
* @title ClamableOwnable
* @dev The ClamableOwnable contract is a copy of Claimable Contract by Zeppelin.
* and provides basic authorization control functions. Inherits storage layout of
* ProxyStorage.
*/
contract ClaimableOwnable is ProxyStorage {
/**
* @dev emitted when ownership is transferred
* @param previousOwner previous owner of this contract
* @param newOwner new owner of this contract
*/
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev sets the original `owner` of the contract to the sender
* at construction. Must then be reinitialized
*/
constructor() public {
owner = msg.sender;
emit OwnershipTransferred(address(0), owner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner, "only Owner");
_;
}
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner, "only pending owner");
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() public onlyPendingOwner {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: contracts/true-currencies-new/ERC20.sol
/**
* @notice This is a copy of openzeppelin ERC20 contract with removed state variables.
* Removing state variables has been necessary due to proxy pattern usage.
* Changes to Openzeppelin ERC20 https://github.com/OpenZeppelin/openzeppelin-contracts/blob/de99bccbfd4ecd19d7369d01b070aa72c64423c9/contracts/token/ERC20/ERC20.sol:
* - Remove state variables _name, _symbol, _decimals
* - Use state variables _balances, _allowances, _totalSupply from ProxyStorage
* - Remove constructor
* - Solidity version changed from ^0.6.0 to 0.6.10
* - Contract made abstract
*
* See also: ClaimableOwnable.sol and ProxyStorage.sol
*/
pragma solidity 0.6.10;
/**
* @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}.
*/
abstract contract ERC20 is ClaimableOwnable, Context, IERC20 {
using SafeMath for uint256;
using Address for address;
/**
* @dev Returns the name of the token.
*/
function name() public virtual pure returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public virtual pure returns (string memory);
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public virtual pure returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev 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].
*/
// solhint-disable-next-line no-empty-blocks
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: contracts/true-currencies-new/ReclaimerToken.sol
pragma solidity 0.6.10;
/**
* @title ReclaimerToken
* @dev ERC20 token which allows owner to reclaim ERC20 tokens
* or ether sent to this contract
*/
abstract contract ReclaimerToken is ERC20 {
/**
* @dev send all eth balance in the contract to another address
* @param _to address to send eth balance to
*/
function reclaimEther(address payable _to) external onlyOwner {
_to.transfer(address(this).balance);
}
/**
* @dev send all token balance of an arbitrary erc20 token
* in the contract to another address
* @param token token to reclaim
* @param _to address to send eth balance to
*/
function reclaimToken(IERC20 token, address _to) external onlyOwner {
uint256 balance = token.balanceOf(address(this));
token.transfer(_to, balance);
}
}
// File: contracts/true-currencies-new/BurnableTokenWithBounds.sol
pragma solidity 0.6.10;
/**
* @title BurnableTokenWithBounds
* @dev Burning functions as redeeming money from the system.
* The platform will keep track of who burns coins,
* and will send them back the equivalent amount of money (rounded down to the nearest cent).
*/
abstract contract BurnableTokenWithBounds is ReclaimerToken {
/**
* @dev Emitted when `value` tokens are burnt from one account (`burner`)
* @param burner address which burned tokens
* @param value amount of tokens burned
*/
event Burn(address indexed burner, uint256 value);
/**
* @dev Emitted when new burn bounds were set
* @param newMin new minimum burn amount
* @param newMax new maximum burn amount
* @notice `newMin` should never be greater than `newMax`
*/
event SetBurnBounds(uint256 newMin, uint256 newMax);
/**
* @dev Destroys `amount` tokens from `msg.sender`, reducing the
* total supply.
* @param amount amount of tokens to burn
*
* Emits a {Transfer} event with `to` set to the zero address.
* Emits a {Burn} event with `burner` set to `msg.sender`
*
* Requirements
*
* - `msg.sender` must have at least `amount` tokens.
*
*/
function burn(uint256 amount) external {
_burn(msg.sender, amount);
}
/**
* @dev Change the minimum and maximum amount that can be burned at once.
* Burning may be disabled by setting both to 0 (this will not be done
* under normal operation, but we can't add checks to disallow it without
* losing a lot of flexibility since burning could also be as good as disabled
* by setting the minimum extremely high, and we don't want to lock
* in any particular cap for the minimum)
* @param _min minimum amount that can be burned at once
* @param _max maximum amount that can be burned at once
*/
function setBurnBounds(uint256 _min, uint256 _max) external onlyOwner {
require(_min <= _max, "BurnableTokenWithBounds: min > max");
burnMin = _min;
burnMax = _max;
emit SetBurnBounds(_min, _max);
}
/**
* @dev Checks if amount is within allowed burn bounds and
* destroys `amount` tokens from `account`, reducing the
* total supply.
* @param account account to burn tokens for
* @param amount amount of tokens to burn
*
* Emits a {Burn} event
*/
function _burn(address account, uint256 amount) internal virtual override {
require(amount >= burnMin, "BurnableTokenWithBounds: below min burn bound");
require(amount <= burnMax, "BurnableTokenWithBounds: exceeds max burn bound");
super._burn(account, amount);
emit Burn(account, amount);
}
}
// File: contracts/true-currencies-new/GasRefund.sol
pragma solidity 0.6.10;
/**
* @title Gas Reclaim Legacy
*
* Note: this contract does not affect any of the token logic. It merely
* exists so the TokenController (owner) can reclaim the sponsored gas
*
* Previously TrueCurrency has a feature called "gas boost" which allowed
* us to sponsor gas by setting non-empty storage slots to 1.
* We are depricating this feature, but there is a bunch of gas saved
* from years of sponsoring gas. This contract is meant to allow the owner
* to take advantage of this leftover gas. Once all the slots are used,
* this contract can be removed from TrueCurrency.
*
* Utilitzes the gas refund mechanism in EVM. Each time an non-empty
* storage slot is set to 0, evm will refund 15,000 to the sender.
* Also utilized the refund for selfdestruct, see gasRefund39
*
*/
abstract contract GasRefund {
/**
* @dev Refund 15,000 gas per slot.
* @param amount number of slots to free
*/
function gasRefund15(uint256 amount) internal {
// refund gas
assembly {
// get number of free slots
let offset := sload(0xfffff)
// make sure there are enough slots
if lt(offset, amount) {
amount := offset
}
if eq(amount, 0) {
stop()
}
let location := add(offset, 0xfffff)
let end := sub(location, amount)
// loop until amount is reached
// i = storage location
for {
} gt(location, end) {
location := sub(location, 1)
} {
// set storage location to zero
// this refunds 15,000 gas
sstore(location, 0)
}
// store new number of free slots
sstore(0xfffff, sub(offset, amount))
}
}
/**
* @dev use smart contract self-destruct to refund gas
* will refund 39,000 * amount gas
*/
function gasRefund39(uint256 amount) internal {
assembly {
// get amount of gas slots
let offset := sload(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
// make sure there are enough slots
if lt(offset, amount) {
amount := offset
}
if eq(amount, 0) {
stop()
}
// first sheep pointer
let location := sub(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, offset)
// last sheep pointer
let end := add(location, amount)
for {
} lt(location, end) {
location := add(location, 1)
} {
// load sheep address
let sheep := sload(location)
// call selfdestruct on sheep
pop(call(gas(), sheep, 0, 0, 0, 0, 0))
// clear sheep address
sstore(location, 0)
}
sstore(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, sub(offset, amount))
}
}
/**
* @dev Return the remaining sponsored gas slots
*/
function remainingGasRefundPool() public view returns (uint256 length) {
assembly {
length := sload(0xfffff)
}
}
/**
* @dev Return the remaining sheep slots
*/
function remainingSheepRefundPool() public view returns (uint256 length) {
assembly {
length := sload(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
}
}
}
// File: contracts/true-currencies-new/TrueCurrency.sol
pragma solidity 0.6.10;
/**
* @title TrueCurrency
* @dev TrueCurrency is an ERC20 with blacklist & redemption addresses
*
* TrueCurrency is a compliant stablecoin with blacklist and redemption
* addresses. Only the owner can blacklist accounts. Redemption addresses
* are assigned automatically to the first 0x100000 addresses. Sending
* tokens to the redemption address will trigger a burn operation. Only
* the owner can mint or blacklist accounts.
*
* This contract is owned by the TokenController, which manages token
* minting & admin functionality. See TokenController.sol
*
* See also: BurnableTokenWithBounds.sol
*
* ~~~~ Features ~~~~
*
* Redemption Addresses
* - The first 0x100000 addresses are redemption addresses
* - Tokens sent to redemption addresses are burned
* - Redemptions are tracked off-chain
* - Cannot mint tokens to redemption addresses
*
* Blacklist
* - Owner can blacklist accounts in accordance with local regulatory bodies
* - Only a court order will merit a blacklist; blacklisting is extremely rare
*
* Burn Bounds & CanBurn
* - Owner can set min & max burn amounts
* - Only accounts flagged in canBurn are allowed to burn tokens
* - canBurn prevents tokens from being sent to the incorrect address
*
* Reclaimer Token
* - ERC20 Tokens and Ether sent to this contract can be reclaimed by the owner
*/
abstract contract TrueCurrency is BurnableTokenWithBounds, GasRefund {
uint256 constant CENT = 10**16;
uint256 constant REDEMPTION_ADDRESS_COUNT = 0x100000;
/**
* @dev Emitted when account blacklist status changes
*/
event Blacklisted(address indexed account, bool isBlacklisted);
/**
* @dev Emitted when `value` tokens are minted for `to`
* @param to address to mint tokens for
* @param value amount of tokens to be minted
*/
event Mint(address indexed to, uint256 value);
/**
* @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
* @param account address to mint tokens for
* @param amount amount of tokens to be minted
*
* Emits a {Mint} event
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` cannot be blacklisted.
* - `account` cannot be a redemption address.
*/
function mint(address account, uint256 amount) external onlyOwner {
require(!isBlacklisted[account], "TrueCurrency: account is blacklisted");
require(!isRedemptionAddress(account), "TrueCurrency: account is a redemption address");
_mint(account, amount);
emit Mint(account, amount);
}
/**
* @dev Set blacklisted status for the account.
* @param account address to set blacklist flag for
* @param _isBlacklisted blacklist flag value
*
* Requirements:
*
* - `msg.sender` should be owner.
*/
function setBlacklisted(address account, bool _isBlacklisted) external onlyOwner {
require(uint256(account) >= REDEMPTION_ADDRESS_COUNT, "TrueCurrency: blacklisting of redemption address is not allowed");
isBlacklisted[account] = _isBlacklisted;
emit Blacklisted(account, _isBlacklisted);
}
/**
* @dev Set canBurn status for the account.
* @param account address to set canBurn flag for
* @param _canBurn canBurn flag value
*
* Requirements:
*
* - `msg.sender` should be owner.
*/
function setCanBurn(address account, bool _canBurn) external onlyOwner {
canBurn[account] = _canBurn;
}
/**
* @dev Check if neither account is blacklisted before performing transfer
* If transfer recipient is a redemption address, burns tokens
* @notice Transfer to redemption address will burn tokens with a 1 cent precision
* @param sender address of sender
* @param recipient address of recipient
* @param amount amount of tokens to transfer
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual override {
require(!isBlacklisted[sender], "TrueCurrency: sender is blacklisted");
require(!isBlacklisted[recipient], "TrueCurrency: recipient is blacklisted");
if (isRedemptionAddress(recipient)) {
super._transfer(sender, recipient, amount.sub(amount.mod(CENT)));
_burn(recipient, amount.sub(amount.mod(CENT)));
} else {
super._transfer(sender, recipient, amount);
}
}
/**
* @dev Requere neither accounts to be blacklisted before approval
* @param owner address of owner giving approval
* @param spender address of spender to approve for
* @param amount amount of tokens to approve
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal override {
require(!isBlacklisted[owner], "TrueCurrency: tokens owner is blacklisted");
require(!isBlacklisted[spender] || amount == 0, "TrueCurrency: tokens spender is blacklisted");
super._approve(owner, spender, amount);
}
/**
* @dev Check if tokens can be burned at address before burning
* @param account account to burn tokens from
* @param amount amount of tokens to burn
*/
function _burn(address account, uint256 amount) internal override {
require(canBurn[account], "TrueCurrency: cannot burn from this address");
super._burn(account, amount);
}
/**
* @dev First 0x100000-1 addresses (0x0000000000000000000000000000000000000001 to 0x00000000000000000000000000000000000fffff)
* are the redemption addresses.
* @param account address to check is a redemption address
*
* All transfers to redemption address will trigger token burn.
*
* @notice For transfer to succeed, canBurn must be true for redemption address
*
* @return is `account` a redemption address
*/
function isRedemptionAddress(address account) internal pure returns (bool) {
return uint256(account) < REDEMPTION_ADDRESS_COUNT && uint256(account) != 0;
}
/**
* @dev reclaim gas from legacy gas refund #1
* will refund 15,000 * amount gas to sender (minus exection cost)
* If gas pool is empty, refund 39,000 * amount gas by calling selfdestruct
*/
function refundGas(uint256 amount) external onlyOwner {
if (remainingGasRefundPool() > 0) {
gasRefund15(amount);
} else {
gasRefund39(amount.div(3));
}
}
}
// File: contracts/true-currencies-new/TrueGBP.sol
pragma solidity 0.6.10;
/**
* @title TrueGBP
* @dev This is the top-level ERC20 contract, but most of the interesting functionality is
* inherited - see the documentation on the corresponding contracts.
*/
contract TrueGBP is TrueCurrency {
uint8 constant DECIMALS = 18;
uint8 constant ROUNDING = 2;
function decimals() public override pure returns (uint8) {
return DECIMALS;
}
function rounding() public pure returns (uint8) {
return ROUNDING;
}
function name() public override pure returns (string memory) {
return "TrueGBP";
}
function symbol() public override pure returns (string memory) {
return "TGBP";
}
} | use smart contract self-destruct to refund gas will refund 39,000 amount gas/ get amount of gas slots make sure there are enough slots load sheep address call selfdestruct on sheep clear sheep address | function gasRefund39(uint256 amount) internal {
assembly {
let offset := sload(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
if lt(offset, amount) {
amount := offset
}
if eq(amount, 0) {
stop()
}
for {
location := add(location, 1)
let sheep := sload(location)
pop(call(gas(), sheep, 0, 0, 0, 0, 0))
sstore(location, 0)
}
sstore(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, sub(offset, amount))
}
}
| 59,292 |
//Address: 0x872f634ce643a9b5a4d9bcfa0714382267839fcc
//Contract name: JaroCoinCrowdsale
//Balance: 3 wei
//Verification Date: 5/30/2018
//Transacion Count: 1
// CODE STARTS HERE
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) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev The constructor sets the original owner of the contract to the sender account.
*/
constructor() public {
setOwner(msg.sender);
}
/**
* @dev Sets a new owner address
*/
function setOwner(address newOwner) internal {
owner = newOwner;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
setOwner(newOwner);
}
}
contract ERC820Registry {
function getManager(address addr) public view returns(address);
function setManager(address addr, address newManager) public;
function getInterfaceImplementer(address addr, bytes32 iHash) public constant returns (address);
function setInterfaceImplementer(address addr, bytes32 iHash, address implementer) public;
}
contract ERC820Implementer {
ERC820Registry erc820Registry = ERC820Registry(0x991a1bcb077599290d7305493c9A630c20f8b798);
function setInterfaceImplementation(string ifaceLabel, address impl) internal {
bytes32 ifaceHash = keccak256(ifaceLabel);
erc820Registry.setInterfaceImplementer(this, ifaceHash, impl);
}
function interfaceAddr(address addr, string ifaceLabel) internal constant returns(address) {
bytes32 ifaceHash = keccak256(ifaceLabel);
return erc820Registry.getInterfaceImplementer(addr, ifaceHash);
}
function delegateManagement(address newManager) internal {
erc820Registry.setManager(this, newManager);
}
}
interface ERC777TokensSender {
function tokensToSend(address operator, address from, address to, uint amount, bytes userData,bytes operatorData) external;
}
interface ERC777TokensRecipient {
function tokensReceived(address operator, address from, address to, uint amount, bytes userData, bytes operatorData) external;
}
contract JaroCoinToken is Ownable, ERC820Implementer {
using SafeMath for uint256;
string public constant name = "JaroCoin";
string public constant symbol = "JARO";
uint8 public constant decimals = 18;
uint256 public constant granularity = 1e10; // Token has 8 digits after comma
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => bool)) public isOperatorFor;
mapping (address => mapping (uint256 => bool)) private usedNonces;
event Transfer(address indexed from, address indexed to, uint256 value);
event Sent(address indexed operator, address indexed from, address indexed to, uint256 amount, bytes userData, bytes operatorData);
event Minted(address indexed operator, address indexed to, uint256 amount, bytes operatorData);
event Burned(address indexed operator, address indexed from, uint256 amount, bytes userData, bytes operatorData);
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
event Approval(address indexed owner, address indexed spender, uint256 value);
uint256 public totalSupply = 0;
uint256 public constant maxSupply = 21000000e18;
// ------- ERC777/ERC965 Implementation ----------
/**
* @notice Send `_amount` of tokens to address `_to` passing `_userData` to the recipient
* @param _to The address of the recipient
* @param _amount The number of tokens to be sent
* @param _userData Data generated by the user to be sent to the recipient
*/
function send(address _to, uint256 _amount, bytes _userData) public {
doSend(msg.sender, _to, _amount, _userData, msg.sender, "", true);
}
/**
* @dev transfer token for a specified address via cheque
* @param _to The address to transfer to
* @param _amount The amount to be transferred
* @param _userData The data to be executed
* @param _nonce Unique nonce to avoid double spendings
*/
function sendByCheque(address _to, uint256 _amount, bytes _userData, uint256 _nonce, uint8 v, bytes32 r, bytes32 s) public {
require(_to != address(this));
// Check if signature is valid, get signer's address and mark this cheque as used.
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 hash = keccak256(prefix, keccak256(_to, _amount, _userData, _nonce));
// bytes32 hash = keccak256(_to, _amount, _userData, _nonce);
address signer = ecrecover(hash, v, r, s);
require (signer != 0);
require (!usedNonces[signer][_nonce]);
usedNonces[signer][_nonce] = true;
// Transfer tokens
doSend(signer, _to, _amount, _userData, signer, "", true);
}
/**
* @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens.
* @param _operator The operator that wants to be Authorized
*/
function authorizeOperator(address _operator) public {
require(_operator != msg.sender);
isOperatorFor[_operator][msg.sender] = true;
emit AuthorizedOperator(_operator, msg.sender);
}
/**
* @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens.
* @param _operator The operator that wants to be Revoked
*/
function revokeOperator(address _operator) public {
require(_operator != msg.sender);
isOperatorFor[_operator][msg.sender] = false;
emit RevokedOperator(_operator, msg.sender);
}
/**
* @notice Send `_amount` of tokens on behalf of the address `from` to the address `to`.
* @param _from The address holding the tokens being sent
* @param _to The address of the recipient
* @param _amount The number of tokens to be sent
* @param _userData Data generated by the user to be sent to the recipient
* @param _operatorData Data generated by the operator to be sent to the recipient
*/
function operatorSend(address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData) public {
require(isOperatorFor[msg.sender][_from]);
doSend(_from, _to, _amount, _userData, msg.sender, _operatorData, true);
}
/* -- Helper Functions -- */
/**
* @notice Internal function that ensures `_amount` is multiple of the granularity
* @param _amount The quantity that want's to be checked
*/
function requireMultiple(uint256 _amount) internal pure {
require(_amount.div(granularity).mul(granularity) == _amount);
}
/**
* @notice Check whether an address is a regular address or not.
* @param _addr Address of the contract that has to be checked
* @return `true` if `_addr` is a regular address (not a contract)
*/
function isRegularAddress(address _addr) internal constant returns(bool) {
if (_addr == 0) { return false; }
uint size;
assembly { size := extcodesize(_addr) } // solhint-disable-line no-inline-assembly
return size == 0;
}
/**
* @notice Helper function that checks for ERC777TokensSender on the sender and calls it.
* May throw according to `_preventLocking`
* @param _from The address holding the tokens being sent
* @param _to The address of the recipient
* @param _amount The amount of tokens to be sent
* @param _userData Data generated by the user to be passed to the recipient
* @param _operatorData Data generated by the operator to be passed to the recipient
* implementing `ERC777TokensSender`.
* ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer
* functions SHOULD set this parameter to `false`.
*/
function callSender(
address _operator,
address _from,
address _to,
uint256 _amount,
bytes _userData,
bytes _operatorData
) private {
address senderImplementation = interfaceAddr(_from, "ERC777TokensSender");
if (senderImplementation != 0) {
ERC777TokensSender(senderImplementation).tokensToSend(
_operator, _from, _to, _amount, _userData, _operatorData);
}
}
/**
* @notice Helper function that checks for ERC777TokensRecipient on the recipient and calls it.
* May throw according to `_preventLocking`
* @param _from The address holding the tokens being sent
* @param _to The address of the recipient
* @param _amount The number of tokens to be sent
* @param _userData Data generated by the user to be passed to the recipient
* @param _operatorData Data generated by the operator to be passed to the recipient
* @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not
* implementing `ERC777TokensRecipient`.
* ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer
* functions SHOULD set this parameter to `false`.
*/
function callRecipient(
address _operator,
address _from,
address _to,
uint256 _amount,
bytes _userData,
bytes _operatorData,
bool _preventLocking
) private {
address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient");
if (recipientImplementation != 0) {
ERC777TokensRecipient(recipientImplementation).tokensReceived(
_operator, _from, _to, _amount, _userData, _operatorData);
} else if (_preventLocking) {
require(isRegularAddress(_to));
}
}
/**
* @notice Helper function actually performing the sending of tokens.
* @param _from The address holding the tokens being sent
* @param _to The address of the recipient
* @param _amount The number of tokens to be sent
* @param _userData Data generated by the user to be passed to the recipient
* @param _operatorData Data generated by the operator to be passed to the recipient
* @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not
* implementing `erc777_tokenHolder`.
* ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer
* functions SHOULD set this parameter to `false`.
*/
function doSend(
address _from,
address _to,
uint256 _amount,
bytes _userData,
address _operator,
bytes _operatorData,
bool _preventLocking
)
private
{
requireMultiple(_amount);
callSender(_operator, _from, _to, _amount, _userData, _operatorData);
require(_to != 0x0); // forbid sending to 0x0 (=burning)
require(balanceOf[_from] >= _amount); // ensure enough funds
balanceOf[_from] = balanceOf[_from].sub(_amount);
balanceOf[_to] = balanceOf[_to].add(_amount);
callRecipient(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking);
emit Sent(_operator, _from, _to, _amount, _userData, _operatorData);
emit Transfer(_from, _to, _amount);
}
// ------- ERC20 Implementation ----------
/**
* @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) {
doSend(msg.sender, _to, _value, "", msg.sender, "", false);
return true;
}
/**
* @dev Transfer tokens from one address to another. Technically this is not ERC20 transferFrom but more ERC777 operatorSend.
* @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(isOperatorFor[msg.sender][_from]);
doSend(_from, _to, _value, "", msg.sender, "", true);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Originally in ERC20 this function to check the amount of tokens that an owner allowed to a spender.
*
* Function was added purly for backward compatibility with ERC20. Use operator logic from ERC777 instead.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A returning uint256 balanceOf _spender if it's active operator and 0 if not.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
if (isOperatorFor[_spender][_owner]) {
return balanceOf[_owner];
} else {
return 0;
}
}
/**
* @dev Approve the passed address to spend tokens on behalf of msg.sender.
*
* This function is more authorizeOperator and revokeOperator from ERC777 that Approve from ERC20.
* Approve concept has several issues (e.g. https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729),
* so I prefer to use operator concept. If you want to revoke approval, just put 0 into _value.
* @param _spender The address which will spend the funds.
* @param _value Fake value to be compatible with ERC20 requirements.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
require(_spender != msg.sender);
if (_value > 0) {
// Authorizing operator
isOperatorFor[_spender][msg.sender] = true;
emit AuthorizedOperator(_spender, msg.sender);
} else {
// Revoking operator
isOperatorFor[_spender][msg.sender] = false;
emit RevokedOperator(_spender, msg.sender);
}
emit Approval(msg.sender, _spender, _value);
return true;
}
// ------- Minting and burning ----------
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @param _operatorData Data that will be passed to the recipient as a first transfer.
*/
function mint(address _to, uint256 _amount, bytes _operatorData) public onlyOwner {
require (totalSupply.add(_amount) <= maxSupply);
requireMultiple(_amount);
totalSupply = totalSupply.add(_amount);
balanceOf[_to] = balanceOf[_to].add(_amount);
callRecipient(msg.sender, 0x0, _to, _amount, "", _operatorData, true);
emit Minted(msg.sender, _to, _amount, _operatorData);
emit Transfer(0x0, _to, _amount);
}
/**
* @dev Function to burn sender's tokens
* @param _amount The amount of tokens to burn.
* @return A boolean that indicates if the operation was successful.
*/
function burn(uint256 _amount, bytes _userData) public {
require (_amount > 0);
require (balanceOf[msg.sender] >= _amount);
requireMultiple(_amount);
callSender(msg.sender, msg.sender, 0x0, _amount, _userData, "");
totalSupply = totalSupply.sub(_amount);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_amount);
emit Burned(msg.sender, msg.sender, _amount, _userData, "");
emit Transfer(msg.sender, 0x0, _amount);
}
}
contract JaroSleep is ERC820Implementer, ERC777TokensRecipient {
using SafeMath for uint256;
uint256 public lastBurn; // Time of last sleep token burn
uint256 public dailyTime; // Tokens to burn per day
JaroCoinToken public token;
event ReceivedTokens(address operator, address from, address to, uint amount, bytes userData, bytes operatorData);
constructor(address _token, uint256 _dailyTime) public {
setInterfaceImplementation("ERC777TokensRecipient", this);
token = JaroCoinToken(_token);
lastBurn = getNow();
dailyTime = _dailyTime;
}
// Reject any ethers send to this address
function () external payable {
revert();
}
function burnTokens() public returns (uint256) {
uint256 sec = getNow().sub(lastBurn);
uint256 tokensToBurn = 0;
// // TODO convert into uint64 for saving gas purposes
if (sec >= 1 days) {
uint256 d = sec.div(86400);
tokensToBurn = d.mul(dailyTime);
token.burn(tokensToBurn, "");
lastBurn = lastBurn.add(d.mul(86400));
}
return tokensToBurn;
}
// Function needed for automated testing purposes
function getNow() internal view returns (uint256) {
return now;
}
// ERC777 tokens receiver callback
function tokensReceived(address operator, address from, address to, uint amount, bytes userData, bytes operatorData) external {
emit ReceivedTokens(operator, from, to, amount, userData, operatorData);
}
}
contract PersonalTime is Ownable, ERC820Implementer, ERC777TokensRecipient {
using SafeMath for uint256;
uint256 public lastBurn; // Time of last sleep token burn
uint256 public dailyTime; // Tokens to burn per day
uint256 public debt = 0; // Debt which will be not minted during next sale period
uint256 public protect = 0; // Tokens which were transfered in favor of future days
JaroCoinToken public token;
event ReceivedTokens(address operator, address from, address to, uint amount, bytes userData, bytes operatorData);
constructor(address _token, uint256 _dailyTime) public {
setInterfaceImplementation("ERC777TokensRecipient", this);
token = JaroCoinToken(_token);
lastBurn = getNow();
dailyTime = _dailyTime;
}
// Reject any ethers send to this address
function () external payable {
revert();
}
function burnTokens() public returns (uint256) {
uint256 sec = getNow().sub(lastBurn);
uint256 tokensToBurn = 0;
// // TODO convert into uint64 for saving gas purposes
if (sec >= 1 days) {
uint256 d = sec.div(86400);
tokensToBurn = d.mul(dailyTime);
if (protect >= tokensToBurn) {
protect = protect.sub(tokensToBurn);
} else {
token.burn(tokensToBurn.sub(protect), "");
protect = 0;
}
lastBurn = lastBurn.add(d.mul(86400));
}
return tokensToBurn;
}
function transfer(address _to, uint256 _amount) public onlyOwner {
protect = protect.add(_amount);
debt = debt.add(_amount);
token.transfer(_to, _amount);
}
// Function needed for automated testing purposes
function getNow() internal view returns (uint256) {
return now;
}
// ERC777 tokens receiver callback
function tokensReceived(address operator, address from, address to, uint amount, bytes userData, bytes operatorData) external {
require(msg.sender == address(token));
debt = (debt >= amount ? debt.sub(amount) : 0);
emit ReceivedTokens(operator, from, to, amount, userData, operatorData);
}
}
contract JaroCoinCrowdsale is Ownable {
using SafeMath for uint256;
address public constant WALLET = 0xefF42c79c0aBea9958432DC82FebC4d65f3d24A3;
// digits of precision for exchange rate
uint8 public constant EXCHANGE_RATE_DECIMALS = 8;
// Max tokens which can be in circulation
uint256 public constant MAX_AMOUNT = 21000000e18; // 21 000 000
uint256 public satoshiRaised; // Amount of raised funds in satoshi
uint256 public rate; // number of tokens buyer gets per satoshi
uint256 public conversionRate; // 17e10 wei per satoshi => 0.056 ETH/BTC
JaroCoinToken public token;
JaroSleep public sleepContract;
PersonalTime public familyContract;
PersonalTime public personalContract;
uint256 public tokensToMint; // Amount of tokens left to mint in this sale
uint256 public saleStartTime; // Start time of recent token sale
// Indicator of token sale activity.
bool public isActive = false;
bool internal initialized = false;
address public exchangeRateOracle;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event SaleActivated(uint256 startTime, uint256 amount);
event SaleClosed();
modifier canMint() {
require (isActive);
require (getNow() > saleStartTime);
_;
}
function initialize(address _owner, address _token, address _familyOwner, address _personalOwner) public {
require (!initialized);
token = JaroCoinToken(_token);
sleepContract = createJaroSleep(_token, 34560e18); // 9.6 hours per day
familyContract = createPersonalTime(_token, 21600e18); // 6 hours per day
personalContract = createPersonalTime(_token, 12960e18); // 3.6 hours per day
familyContract.transferOwnership(_familyOwner);
personalContract.transferOwnership(_personalOwner);
rate = 100000e10;
conversionRate = 17e10;
satoshiRaised = 0;
setOwner(_owner);
initialized = true;
}
// fallback function can be used to buy tokens
function () external canMint payable {
_buyTokens(msg.sender, msg.value, 0);
}
function coupon(uint256 _timeStamp, uint16 _bonus, uint8 v, bytes32 r, bytes32 s) external canMint payable {
require(_timeStamp >= getNow());
// Check if signature is valid, get signer's address and mark this cheque as used.
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 hash = keccak256(prefix, keccak256(_timeStamp, _bonus));
address signer = ecrecover(hash, v, r, s);
require(signer == owner);
_buyTokens(msg.sender, msg.value, _bonus);
}
function buyTokens(address _beneficiary) public canMint payable {
_buyTokens(_beneficiary, msg.value, 0);
}
function _buyTokens(address _beneficiary, uint256 _value, uint16 _bonus) internal {
require (_beneficiary != address(0));
require (_value > 0);
uint256 weiAmount = _value;
uint256 satoshiAmount = weiAmount.div(conversionRate);
uint256 tokens = satoshiAmount.mul(rate).mul(_bonus + 100).div(100);
// Mint tokens and refund not used ethers in case when max amount reached during this minting
uint256 excess = appendContribution(_beneficiary, tokens);
uint256 refund = (excess > 0 ? excess.mul(100).div(100+_bonus).mul(conversionRate).div(rate) : 0);
weiAmount = weiAmount.sub(refund);
satoshiRaised = satoshiRaised.add(satoshiAmount);
// if hard cap reached, no more tokens to mint, refund sender not used ethers
if (refund > 0) {
msg.sender.transfer(refund);
}
emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens.sub(excess));
// Send ethers into WALLET
WALLET.transfer(weiAmount);
}
function appendContribution(address _beneficiary, uint256 _tokens) internal returns (uint256) {
if (_tokens >= tokensToMint) {
mint(_beneficiary, tokensToMint);
uint256 excededTokens = _tokens.sub(tokensToMint);
_closeSale(); // Last tokens minted, lets close token sale
return excededTokens;
}
tokensToMint = tokensToMint.sub(_tokens);
mint(_beneficiary, _tokens);
return 0;
}
/**
* Owner can start new token sale, to mint missing tokens by using this function,
* but not more often than once per month.
* @param _startTime start time for new token sale.
*/
function startSale(uint256 _startTime) public onlyOwner {
require (!isActive);
require (_startTime > getNow());
require (saleStartTime == 0 || _startTime.sub(saleStartTime) > 30 days); // Minimum one month between token sales
// Burn unburned sleep, family and personal time.
sleepContract.burnTokens();
uint256 sleepTokens = token.balanceOf(address(sleepContract));
familyContract.burnTokens();
uint256 familyTokens = token.balanceOf(familyContract).add(familyContract.debt());
personalContract.burnTokens();
uint256 personalTokens = token.balanceOf(personalContract).add(personalContract.debt());
uint256 missingSleep = MAX_AMOUNT.div(100).mul(40).sub(sleepTokens); // sleep and stuff takes 40% of Jaro time
uint256 missingFamily = MAX_AMOUNT.div(100).mul(25).sub(familyTokens); // 25% for family
uint256 missingPersonal = MAX_AMOUNT.div(100).mul(15).sub(personalTokens); // 15% is Jaro personal time
mint(address(sleepContract), missingSleep);
mint(address(familyContract), missingFamily);
mint(address(personalContract), missingPersonal);
tokensToMint = MAX_AMOUNT.sub(token.totalSupply());
saleStartTime = _startTime;
isActive = true;
emit SaleActivated(_startTime, tokensToMint);
}
function _closeSale() internal {
tokensToMint = 0;
isActive = false;
emit SaleClosed();
}
function closeSale() public onlyOwner {
_closeSale();
}
function setExchangeRateOracle(address _exchangeRateOracle) public onlyOwner {
require(_exchangeRateOracle != address(0));
exchangeRateOracle = _exchangeRateOracle;
}
function setExchangeRate(uint256 _exchangeRate) public {
require(msg.sender == exchangeRateOracle || msg.sender == owner);
require(_exchangeRate > 0);
uint256 one = 1e18;
conversionRate = one.div(_exchangeRate);
}
function mint(address _beneficiary, uint256 _amount) internal {
if (_amount > 0) {
token.mint(_beneficiary, _amount, "");
}
}
// This function created for easier testing purposes
function createJaroSleep(address _token, uint256 _dailyTime) internal returns (JaroSleep) {
return new JaroSleep(_token, _dailyTime);
}
function createPersonalTime(address _token, uint256 _dailyTime) internal returns (PersonalTime) {
return new PersonalTime(_token, _dailyTime);
}
// This function created for easier testing purposes
function getNow() internal view returns (uint256) {
return now;
}
}
| Function to burn sender's tokens _amount The amount of tokens to burn. return A boolean that indicates if the operation was successful./ | function burn(uint256 _amount, bytes _userData) public {
require (_amount > 0);
require (balanceOf[msg.sender] >= _amount);
requireMultiple(_amount);
callSender(msg.sender, msg.sender, 0x0, _amount, _userData, "");
totalSupply = totalSupply.sub(_amount);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_amount);
emit Burned(msg.sender, msg.sender, _amount, _userData, "");
emit Transfer(msg.sender, 0x0, _amount);
}
| 7,316,323 |
pragma solidity ^0.4.24;
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns(address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns(bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
function safeTransfer(
IERC20 token,
address to,
uint256 value
)
internal
{
require(token.transfer(to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
)
internal
{
require(token.transferFrom(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'
require((value == 0) || (token.allowance(msg.sender, spender) == 0));
require(token.approve(spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
)
internal
{
uint256 newAllowance = token.allowance(address(this), spender).add(value);
require(token.approve(spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
)
internal
{
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
require(token.approve(spender, newAllowance));
}
}
// File: openzeppelin-solidity/contracts/drafts/TokenVesting.sol
/* solium-disable security/no-block-members */
pragma solidity ^0.4.24;
/**
* @title TokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
*/
contract TokenVesting is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
event TokensReleased(address token, uint256 amount);
event TokenVestingRevoked(address token);
// beneficiary of tokens after they are released
address private _beneficiary;
uint256 private _cliff;
uint256 private _start;
uint256 private _duration;
bool private _revocable;
mapping (address => uint256) private _released;
mapping (address => bool) private _revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* beneficiary, gradually in a linear fashion until start + duration. By then all
* of the balance will have vested.
* @param beneficiary address of the beneficiary to whom vested tokens are transferred
* @param cliffDuration duration in seconds of the cliff in which tokens will begin to vest
* @param start the time (as Unix time) at which point vesting starts
* @param duration duration in seconds of the period in which the tokens will vest
* @param revocable whether the vesting is revocable or not
*/
constructor(
address beneficiary,
uint256 start,
uint256 cliffDuration,
uint256 duration,
bool revocable
)
public
{
require(beneficiary != address(0));
require(cliffDuration <= duration);
require(duration > 0);
require(start.add(duration) > block.timestamp);
_beneficiary = beneficiary;
_revocable = revocable;
_duration = duration;
_cliff = start.add(cliffDuration);
_start = start;
}
/**
* @return the beneficiary of the tokens.
*/
function beneficiary() public view returns(address) {
return _beneficiary;
}
/**
* @return the cliff time of the token vesting.
*/
function cliff() public view returns(uint256) {
return _cliff;
}
/**
* @return the start time of the token vesting.
*/
function start() public view returns(uint256) {
return _start;
}
/**
* @return the duration of the token vesting.
*/
function duration() public view returns(uint256) {
return _duration;
}
/**
* @return true if the vesting is revocable.
*/
function revocable() public view returns(bool) {
return _revocable;
}
/**
* @return the amount of the token released.
*/
function released(address token) public view returns(uint256) {
return _released[token];
}
/**
* @return true if the token is revoked.
*/
function revoked(address token) public view returns(bool) {
return _revoked[token];
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(IERC20 token) public {
uint256 unreleased = _releasableAmount(token);
require(unreleased > 0);
_released[token] = _released[token].add(unreleased);
token.safeTransfer(_beneficiary, unreleased);
emit TokensReleased(token, unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(IERC20 token) public onlyOwner {
require(_revocable);
require(!_revoked[token]);
uint256 balance = token.balanceOf(address(this));
uint256 unreleased = _releasableAmount(token);
uint256 refund = balance.sub(unreleased);
_revoked[token] = true;
token.safeTransfer(owner(), refund);
emit TokenVestingRevoked(token);
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function _releasableAmount(IERC20 token) private view returns (uint256) {
return _vestedAmount(token).sub(_released[token]);
}
/**
* @dev Calculates the amount that has already vested.
* @param token ERC20 token which is being vested
*/
function _vestedAmount(IERC20 token) private view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(_released[token]);
if (block.timestamp < _cliff) {
return 0;
} else if (block.timestamp >= _start.add(_duration) || _revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(_start)).div(_duration);
}
}
}
// File: contracts/TokenVestingFactory.sol
/**
* Factory for TokenVesting contracts.
*/
contract TokenVestingFactory is Ownable {
/**
* Emitted when a new TokenVested contract is created.
*/
event Created(TokenVesting vesting);
/**
* Creates a new TokenVesting contract. Note that only the
* contract owner may call this method.
*
* Based on
* https://medium.com/hussy-io/factory-method-pattern-for-token-vesting-smart-contracts-cae2b0361aed
*
* @param _beneficiary the address that will receive vested tokens.
* @param _startTime unix timestamp when contract term starts.
* @param _cliffSeconds number of seconds after `_startTime` before
* vested tokens can be released.
* @param _vestingSeconds number of seconds that it will take for
* tokens to vest completely. Must be greater than `_cliffSeconds`;
* see link above for more information.
* @param _revocable whether contract owner may revoke the
* TokenVesting contract.
*
* @return TokenVesting contract. The message sender becomes the
* owner of the resulting contract.
*/
function create(
address _beneficiary,
uint256 _startTime,
uint256 _cliffSeconds,
uint256 _vestingSeconds,
bool _revocable
) onlyOwner public returns (TokenVesting) {
TokenVesting vesting = new TokenVesting(
_beneficiary,
_startTime,
_cliffSeconds,
_vestingSeconds,
_revocable
);
vesting.transferOwnership(msg.sender);
emit Created(vesting);
return vesting;
}
} | Allows the owner to revoke the vesting. Tokens already vested remain in the contract, the rest are returned to the owner. token ERC20 token which is being vested/ | function revoke(IERC20 token) public onlyOwner {
require(_revocable);
require(!_revoked[token]);
uint256 balance = token.balanceOf(address(this));
uint256 unreleased = _releasableAmount(token);
uint256 refund = balance.sub(unreleased);
_revoked[token] = true;
token.safeTransfer(owner(), refund);
emit TokenVestingRevoked(token);
}
| 5,345,676 |
// 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;
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// 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 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;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount)
external
returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender)
external
view
returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* 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 {}
}
// 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);
}
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/token/ERC20/SafeERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using 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"
);
}
}
}
// 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/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
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/introspection/ERC165Checker.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Library used to query support of an interface declared via {IERC165}.
*
* Note that these functions return the actual result of the query: they do not
* `revert` if an interface is not supported. It is up to the caller to decide
* what to do in these cases.
*/
library ERC165Checker {
// As per the EIP-165 spec, no interface should ever match 0xffffffff
bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Returns true if `account` supports the {IERC165} interface,
*/
function supportsERC165(address account) internal view returns (bool) {
// Any contract that implements ERC165 must explicitly indicate support of
// InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
return
_supportsERC165Interface(account, _INTERFACE_ID_ERC165) &&
!_supportsERC165Interface(account, _INTERFACE_ID_INVALID);
}
/**
* @dev Returns true if `account` supports the interface defined by
* `interfaceId`. Support for {IERC165} itself is queried automatically.
*
* See {IERC165-supportsInterface}.
*/
function supportsInterface(address account, bytes4 interfaceId)
internal
view
returns (bool)
{
// query support of both ERC165 as per the spec and support of _interfaceId
return
supportsERC165(account) &&
_supportsERC165Interface(account, interfaceId);
}
/**
* @dev Returns true if `account` supports all the interfaces defined in
* `interfaceIds`. Support for {IERC165} itself is queried automatically.
*
* Batch-querying can lead to gas savings by skipping repeated checks for
* {IERC165} support.
*
* See {IERC165-supportsInterface}.
*/
function supportsAllInterfaces(
address account,
bytes4[] memory interfaceIds
) internal view returns (bool) {
// query support of ERC165 itself
if (!supportsERC165(account)) {
return false;
}
// query support of each interface in _interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
if (!_supportsERC165Interface(account, interfaceIds[i])) {
return false;
}
}
// all interfaces supported
return true;
}
/**
* @notice Query if a contract implements an interface, does not check ERC165 support
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return true if the contract at account indicates support of the interface with
* identifier interfaceId, false otherwise
* @dev Assumes that account contains a contract that supports ERC165, otherwise
* the behavior of this method is undefined. This precondition can be checked
* with {supportsERC165}.
* Interface identification is specified in ERC-165.
*/
function _supportsERC165Interface(address account, bytes4 interfaceId)
private
view
returns (bool)
{
// success determines whether the staticcall succeeded and result determines
// whether the contract at account indicates support of _interfaceId
(bool success, bool result) =
_callERC165SupportsInterface(account, interfaceId);
return (success && result);
}
/**
* @notice Calls the function with selector 0x01ffc9a7 (ERC165) and suppresses throw
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return success true if the STATICCALL succeeded, false otherwise
* @return result true if the STATICCALL succeeded and the contract at account
* indicates support of the interface with identifier interfaceId, false otherwise
*/
function _callERC165SupportsInterface(address account, bytes4 interfaceId)
private
view
returns (bool, bool)
{
bytes memory encodedParams =
abi.encodeWithSelector(_INTERFACE_ID_ERC165, interfaceId);
(bool success, bytes memory result) =
account.staticcall{gas: 30000}(encodedParams);
if (result.length < 32) return (false, false);
return (success, abi.decode(result, (bool)));
}
}
// File: contracts/token/ERC20OnApprove.sol
pragma solidity >=0.6.0 <0.8.0;
abstract contract OnApprove is ERC165 {
constructor() public {
_registerInterface(OnApprove(this).onApprove.selector);
}
function onApprove(
address owner,
address spender,
uint256 amount,
bytes calldata data
) external virtual returns (bool);
}
abstract contract ERC20OnApprove is ERC20 {
function approveAndCall(
address spender,
uint256 amount,
bytes calldata data
) external returns (bool) {
require(approve(spender, amount));
_callOnApprove(msg.sender, spender, amount, data);
return true;
}
function _callOnApprove(
address owner,
address spender,
uint256 amount,
bytes memory data
) internal {
bytes4 onApproveSelector = OnApprove(spender).onApprove.selector;
require(
ERC165Checker.supportsInterface(spender, onApproveSelector),
"ERC20OnApprove: spender doesn't support onApprove"
);
(bool ok, bytes memory res) =
spender.call(
abi.encodeWithSelector(
onApproveSelector,
owner,
spender,
amount,
data
)
);
// check if low-level call reverted or not
require(ok, string(res));
assembly {
ok := mload(add(res, 0x20))
}
// check if OnApprove.onApprove returns true or false
require(ok, "ERC20OnApprove: failed to call onApprove");
}
}
// File: contracts/lib/ds-hub.sol
pragma solidity >=0.6.0 <0.8.0;
interface DSAuthority {
function canCall(
address src,
address dst,
bytes4 sig
) external view returns (bool);
}
contract DSAuthEvents {
event LogSetAuthority(address indexed authority);
event LogSetOwner(address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
constructor() public {
owner = msg.sender;
emit LogSetOwner(msg.sender);
}
function setOwner(address owner_) public auth {
owner = owner_;
emit LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_) public auth {
authority = authority_;
emit LogSetAuthority(address(authority));
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig), "ds-auth-unauthorized");
_;
}
function isAuthorized(address src, bytes4 sig)
internal
view
returns (bool)
{
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, address(this), sig);
}
}
}
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint256 wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
uint256 wad;
assembly {
foo := calldataload(4)
bar := calldataload(36)
wad := callvalue()
}
_;
emit LogNote(msg.sig, msg.sender, foo, bar, wad, msg.data);
}
}
contract DSMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x <= y ? x : y;
}
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x >= y ? x : y;
}
function imin(int256 x, int256 y) internal pure returns (int256 z) {
return x <= y ? x : y;
}
function imax(int256 x, int256 y) internal pure returns (int256 z) {
return x >= y ? x : y;
}
uint256 constant WAD = 10**18;
uint256 constant RAY = 10**27;
//rounds to zero if x*y < WAD / 2
function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
//rounds to zero if x*y < WAD / 2
function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
//rounds to zero if x*y < WAD / 2
function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, WAD), y / 2) / y;
}
//rounds to zero if x*y < RAY / 2
function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, RAY), y / 2) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
contract DSThing is DSAuth, DSNote, DSMath {
function S(string memory s) internal pure returns (bytes4) {
return bytes4(keccak256(abi.encodePacked(s)));
}
}
contract DSValue is DSThing {
bool has;
bytes32 val;
function peek() public view returns (bytes32, bool) {
return (val, has);
}
function read() public view returns (bytes32) {
bytes32 wut;
bool haz;
(wut, haz) = peek();
require(haz, "haz-not");
return wut;
}
function poke(bytes32 wut) public note auth {
val = wut;
has = true;
}
function void() public note auth {
// unset the value
has = false;
}
}
// File: contracts/timelock/NonLinearTimeLock.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev before each step end time, beneficiary can claim tokens.
*/
contract NonLinearTimeLock is DSMath, Ownable, OnApprove {
using SafeMath for uint256;
using SafeERC20 for ERC20;
bool public initialized;
ERC20 public token;
address public beneficiary;
uint256 public initialBalance;
uint256 public claimed;
uint256 public startTime;
uint256 public endTime;
uint256 public lastStep;
uint256 public nSteps;
uint256[] public stepEndTimes;
uint256[] public accStepRatio;
event Claimed(address indexed beneficiary, uint256 amount);
constructor(ERC20 token_, address beneficiary_) public {
require(beneficiary_ != address(0), "zero-value");
require(token_.decimals() == 18, "invalid-decimal");
token = token_;
beneficiary = beneficiary_;
}
function init(
uint256 startTime_,
uint256[] memory stepEndTimes_,
uint256[] memory stepRatio_
) external onlyOwner {
require(!initialized, "no-re-init");
require(
stepEndTimes_.length == stepRatio_.length,
"invalid-array-length"
);
uint256 n = stepEndTimes_.length;
uint256[] memory accStepRatio_ = new uint256[](n);
uint256 accRatio;
for (uint256 i = 0; i < n; i++) {
accRatio += stepRatio_[i];
accStepRatio_[i] = accRatio;
}
require(accRatio == WAD, "invalid-acc-ratio");
for (uint256 i = 1; i < n; i++) {
require(stepEndTimes_[i - 1] < stepEndTimes_[i], "unsorted-times");
}
initialized = true;
initialBalance = token.balanceOf(address(this));
startTime = startTime_;
endTime = stepEndTimes_[n - 1];
stepEndTimes = stepEndTimes_;
accStepRatio = accStepRatio_;
nSteps = stepRatio_.length;
}
function onApprove(
address owner,
address spender,
uint256 amount,
bytes calldata data
) external override returns (bool) {
require(spender == address(this), "invalid-approval");
require(msg.sender == address(token), "invalid-token");
_addDeposit(owner, amount);
data;
return true;
}
// append more deposits
function addDeposit(uint256 amount) external {
_addDeposit(msg.sender, amount);
}
function _addDeposit(address owner, uint256 amount) internal {
require(initialized, "no-init");
initialBalance = initialBalance.add(amount);
token.safeTransferFrom(owner, address(this), amount);
}
/**
* @dev claim locked tokens. `owner` can call this for usability, and it's safe
* becuase owner must be Swapper which is not capable to transfer locker's ownership.
*/
function claim() external {
require(msg.sender == beneficiary || msg.sender == owner(), "no-auth");
uint256 amount = claimable();
require(amount > 0, "invalid-amount");
claimed = claimed.add(amount);
token.safeTransfer(beneficiary, amount);
emit Claimed(beneficiary, amount);
}
/**
* @dev get claimable tokens now
*/
function claimable() public view returns (uint256) {
return claimableAt(block.timestamp);
}
/**
* @dev get claimable tokens at `timestamp`
*/
function claimableAt(uint256 timestamp) public view returns (uint256) {
require(block.timestamp <= timestamp, "invalid-timestamp");
if (timestamp < startTime) return 0;
if (timestamp >= endTime) return initialBalance.sub(claimed);
uint256 step = getStepAt(timestamp);
uint256 accRatio = accStepRatio[step];
return wmul(initialBalance, accRatio).sub(claimed);
}
/**
* @dev get current step
*/
function getStep() public view returns (uint256) {
return getStepAt(block.timestamp);
}
/**
* @dev get step at `timestamp`
*/
function getStepAt(uint256 timestamp) public view returns (uint256) {
require(timestamp >= startTime, "not-started");
uint256 n = nSteps;
if (timestamp >= stepEndTimes[n - 1]) {
return n - 1;
}
if (timestamp <= stepEndTimes[0]) {
return 0;
}
uint256 lo = 1;
uint256 hi = n - 1;
uint256 md;
while (lo < hi) {
md = (hi + lo + 1) / 2;
if (timestamp < stepEndTimes[md - 1]) {
hi = md - 1;
} else {
lo = md;
}
}
return lo;
}
}
// File: @openzeppelin/contracts/utils/Pausable.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @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());
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20Pausable.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev ERC20 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC20Pausable is ERC20, Pausable {
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(!paused(), "ERC20Pausable: token transfer while paused");
}
}
// 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(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index)
internal
view
returns (address)
{
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index)
internal
view
returns (uint256)
{
return uint256(_at(set._inner, index));
}
}
// File: @openzeppelin/contracts/access/AccessControl.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(
bytes32 indexed role,
bytes32 indexed previousAdminRole,
bytes32 indexed newAdminRole
);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(
bytes32 indexed role,
address indexed account,
address indexed sender
);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(
bytes32 indexed role,
address indexed account,
address indexed sender
);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index)
public
view
returns (address)
{
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(
hasRole(_roles[role].adminRole, _msgSender()),
"AccessControl: sender must be an admin to grant"
);
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(
hasRole(_roles[role].adminRole, _msgSender()),
"AccessControl: sender must be an admin to revoke"
);
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(
account == _msgSender(),
"AccessControl: can only renounce roles for self"
);
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20Burnable.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
using SafeMath for uint256;
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance =
allowance(account, _msgSender()).sub(
amount,
"ERC20: burn amount exceeds allowance"
);
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
}
// File: @openzeppelin/contracts/presets/ERC20PresetMinterPauser.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev {ERC20} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a minter role that allows for token minting (creation)
* - a pauser role that allows to stop all token transfers
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* The account that deploys the contract will be granted the minter and pauser
* roles, as well as the default admin role, which will let it grant both minter
* and pauser roles to other accounts.
*/
contract ERC20PresetMinterPauser is
Context,
AccessControl,
ERC20Burnable,
ERC20Pausable
{
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the
* account that deploys the contract.
*
* See {ERC20-constructor}.
*/
constructor(string memory name, string memory symbol)
public
ERC20(name, symbol)
{
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) public virtual {
require(
hasRole(MINTER_ROLE, _msgSender()),
"ERC20PresetMinterPauser: must have minter role to mint"
);
_mint(to, amount);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public virtual {
require(
hasRole(PAUSER_ROLE, _msgSender()),
"ERC20PresetMinterPauser: must have pauser role to pause"
);
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public virtual {
require(
hasRole(PAUSER_ROLE, _msgSender()),
"ERC20PresetMinterPauser: must have pauser role to unpause"
);
_unpause();
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override(ERC20, ERC20Pausable) {
super._beforeTokenTransfer(from, to, amount);
}
}
// File: contracts/token/Token.sol
pragma solidity >=0.6.0 <0.8.0;
contract Token is ERC20PresetMinterPauser, ERC20OnApprove {
bytes32 public constant MINTER_ADMIN_ROLE = keccak256("MINTER_ADMIN_ROLE");
bytes32 public constant PAUSER_ADMIN_ROLE = keccak256("PAUSER_ADMIN_ROLE");
constructor(
string memory name_,
string memory symbol_,
uint256 initialSupply_
) public ERC20PresetMinterPauser(name_, symbol_) {
_mint(_msgSender(), initialSupply_);
_setRoleAdmin(MINTER_ROLE, MINTER_ADMIN_ROLE);
_setRoleAdmin(PAUSER_ROLE, PAUSER_ADMIN_ROLE);
_setupRole(MINTER_ADMIN_ROLE, _msgSender());
_setupRole(PAUSER_ADMIN_ROLE, _msgSender());
}
/**
* @dev change DEFAULT_ADMIN_ROLE to `account`
*/
function changeAdminRole(address account) external {
changeRole(DEFAULT_ADMIN_ROLE, account);
}
/**
* @dev grant and revoke `role` to `account`
*/
function changeRole(bytes32 role, address account) public {
grantRole(role, account);
revokeRole(role, _msgSender());
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal override(ERC20, ERC20PresetMinterPauser) {
super._beforeTokenTransfer(from, to, amount);
}
}
// File: contracts/swapper/NonLinearTimeLockSwapper.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev `deposit` source token and `claim` target token from NonLinearTimeLock contract.
*/
contract NonLinearTimeLockSwapper is Ownable, DSMath, OnApprove {
using SafeERC20 for IERC20;
// swap data for each source token, i.e., tCHA, mCHA
struct Data {
uint128 rate; // convertion rate from source token to target token
uint128 startTime;
uint256[] stepEndTimes;
uint256[] stepRatio;
}
IERC20 public token; // target token, i.e., CHA
address public tokenWallet; // address who supply target token
// time lock data for each source token
mapping(address => Data) public datas;
// time lock of beneficiary for each source token
// sourceToken => beneficiary => NonLinearTimeLock
mapping(address => mapping(address => NonLinearTimeLock)) public locks;
modifier onlyValidAddress(address account) {
require(account != address(0), "zero-address");
_;
}
event Deposited(
address indexed sourceToken,
address indexed beneficiary,
address indexed lock,
uint256 sourceTokenAmount,
uint256 targetTokenAmount
);
constructor(IERC20 token_, address tokenWallet_)
public
onlyValidAddress(address(token_))
onlyValidAddress(tokenWallet_)
{
token = token_;
tokenWallet = tokenWallet_;
}
//////////////////////////////////////////
//
// token wallet
//
//////////////////////////////////////////
function setTokenWallet(address tokenWallet_)
external
onlyOwner
onlyValidAddress(tokenWallet_)
{
tokenWallet = tokenWallet_;
}
//////////////////////////////////////////
//
// NonLinearTimeLock data
//
//////////////////////////////////////////
function register(
address sourceToken,
uint128 rate,
uint128 startTime,
uint256[] memory stepEndTimes,
uint256[] memory stepRatio
) external onlyOwner {
require(!isRegistered(sourceToken), "duplicate-register");
require(rate > 0, "invalid-rate");
require(
stepEndTimes.length == stepRatio.length,
"invalid-array-length"
);
uint256 n = stepEndTimes.length;
uint256 accRatio;
for (uint256 i = 0; i < n; i++) {
accRatio = add(accRatio, stepRatio[i]);
}
require(accRatio == WAD, "invalid-acc-ratio");
for (uint256 i = 1; i < n; i++) {
require(stepEndTimes[i - 1] < stepEndTimes[i], "unsorted-times");
}
datas[sourceToken] = Data({
rate: rate,
startTime: startTime,
stepEndTimes: stepEndTimes,
stepRatio: stepRatio
});
}
function isRegistered(address sourceToken) public view returns (bool) {
return datas[sourceToken].startTime > 0;
}
function getStepEndTimes(address sourceToken)
external
view
returns (uint256[] memory)
{
return datas[sourceToken].stepEndTimes;
}
function getStepRatio(address sourceToken)
external
view
returns (uint256[] memory)
{
return datas[sourceToken].stepRatio;
}
//////////////////////////////////////////
//
// source token deposit
//
//////////////////////////////////////////
function onApprove(
address owner,
address spender,
uint256 amount,
bytes calldata data
) external override returns (bool) {
require(spender == address(this), "invalid-approval");
deposit(msg.sender, owner, amount);
data;
return true;
}
// deposit sender's token
function deposit(
address sourceToken,
address beneficiary,
uint256 amount
) public onlyValidAddress(beneficiary) {
require(isRegistered(sourceToken), "unregistered-source-token");
require(amount > 0, "invalid-amount");
require(
msg.sender == address(sourceToken) || msg.sender == beneficiary,
"no-auth"
);
Data storage data = datas[sourceToken];
uint256 tokenAmount = wmul(amount, data.rate);
// process first deposit
if (address(locks[sourceToken][beneficiary]) == address(0)) {
NonLinearTimeLock lock =
new NonLinearTimeLock(ERC20(address(token)), beneficiary);
locks[sourceToken][beneficiary] = lock;
// get source token
IERC20(sourceToken).safeTransferFrom(
beneficiary,
address(this),
amount
);
// transfer target token and initialize lock
token.safeTransferFrom(tokenWallet, address(lock), tokenAmount);
lock.init(data.startTime, data.stepEndTimes, data.stepRatio);
emit Deposited(
sourceToken,
beneficiary,
address(lock),
amount,
tokenAmount
);
return;
}
// process subsequent deposit
NonLinearTimeLock lock = locks[sourceToken][beneficiary];
// get source token
IERC20(sourceToken).safeTransferFrom(
beneficiary,
address(this),
amount
);
// get target token from token wallet
token.safeTransferFrom(tokenWallet, address(this), tokenAmount);
// update initial balance of lock
bytes memory d;
Token(address(token)).approveAndCall(address(lock), tokenAmount, d);
emit Deposited(
sourceToken,
beneficiary,
address(lock),
amount,
tokenAmount
);
}
//////////////////////////////////////////
//
// NonLinearTimeLock contract instance helper functions
//
//////////////////////////////////////////
modifier onlyDeposit(address sourceToken, address account) {
require(
address(locks[sourceToken][account]) != address(0),
"no-deposit"
);
_;
}
function claim(address sourceToken)
public
onlyDeposit(sourceToken, msg.sender)
{
locks[sourceToken][msg.sender].claim();
}
function claimTokens(address[] calldata sourceTokens) external {
for (uint256 i = 0; i < sourceTokens.length; i++) {
claim(sourceTokens[i]);
}
}
function initialBalance(address sourceToken, address beneficiary)
external
view
onlyDeposit(sourceToken, beneficiary)
returns (uint256)
{
return locks[sourceToken][beneficiary].initialBalance();
}
function claimable(address sourceToken, address beneficiary)
external
view
onlyDeposit(sourceToken, beneficiary)
returns (uint256)
{
return locks[sourceToken][beneficiary].claimable();
}
function claimableAt(
address sourceToken,
address beneficiary,
uint256 timestamp
) external view onlyDeposit(sourceToken, beneficiary) returns (uint256) {
return locks[sourceToken][beneficiary].claimableAt(timestamp);
}
function claimed(address sourceToken, address beneficiary)
external
view
onlyDeposit(sourceToken, beneficiary)
returns (uint256)
{
return locks[sourceToken][beneficiary].claimed();
}
} | get claimable tokens at `timestamp`/ | function claimableAt(uint256 timestamp) public view returns (uint256) {
require(block.timestamp <= timestamp, "invalid-timestamp");
if (timestamp < startTime) return 0;
if (timestamp >= endTime) return initialBalance.sub(claimed);
uint256 step = getStepAt(timestamp);
uint256 accRatio = accStepRatio[step];
return wmul(initialBalance, accRatio).sub(claimed);
}
| 14,521,787 |
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "./YoloInterfaces.sol";
/**
Manages the state of the PLayers in the Yolo Games Universe.
*/
contract YoloRegistry is Ownable, Pausable {
event YoloGamertagUpdate(address indexed account, string gamertag);
event YoloClantagUpdate(address indexed account, string clantag);
event YoloProfilePicUpdate(address indexed account, string pfp);
struct Player {
string gamertag;
string clantag;
string pfp;
}
mapping (address => string) public gamertags;
mapping (address => string) public clantags;
mapping (address => string) public pfps;
mapping (string => address) public gamertagToPlayer;
uint public gamertagFee = 50 ether;
uint public clantagFee = 50 ether;
uint public pfpFee = 100 ether;
uint16 public gamertagMaxLength = 80;
uint16 public clantagMaxLength = 8;
IYoloDice public diceV1;
IYoloChips public chips;
constructor(address _diceV1, address _chips) {
diceV1 = IYoloDice(_diceV1);
chips = IYoloChips(_chips);
}
// Pausable.
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
// Setters.
function setDiceV1(address _diceV1) external onlyOwner {
diceV1 = IYoloDice(_diceV1);
}
function setChips(address _chips) external onlyOwner {
chips = IYoloChips(_chips);
}
function setGamertagFee(uint256 _fee) external onlyOwner {
gamertagFee = _fee;
}
function setClantagFee(uint256 _fee) external onlyOwner {
clantagFee = _fee;
}
function setPfpFee(uint256 _fee) external onlyOwner {
pfpFee = _fee;
}
function setGamertagMaxLength(uint16 _length) external onlyOwner {
gamertagMaxLength = _length;
}
function setClantagMaxLength(uint16 _length) external onlyOwner {
clantagMaxLength = _length;
}
function setMultiGamertags(string[] memory _gamertags, address[] memory _addresses) external onlyOwner {
for (uint256 idx = 0; idx < _gamertags.length; idx++) {
// Max length.
require(bytes(_gamertags[idx]).length <= gamertagMaxLength, "Yolo Registry: Gamertag too long");
// Ensure unique.
require(!_isGamertagTaken(_gamertags[idx]), "Yolo Registry: Gamertag is taken");
_setGamertagFor(_gamertags[idx], _addresses[idx]);
}
}
// Dashboard functionality.
/// @notice Returns token IDs of V1 Dice owned by the address.
function getV1Dice(address _address) public view returns (uint256[] memory) {
uint balance = diceV1.balanceOf(_address);
uint256[] memory diceIds = new uint256[](balance);
for (uint256 idx = 0; idx < balance; idx++) {
diceIds[idx] = diceV1.tokenOfOwnerByIndex(_address, idx);
}
return diceIds;
}
/// @notice Returns the profile of the given address.
function getProfile(address _address) public view returns (Player memory) {
return Player(getGamertag(_address), getClantag(_address), getPfp(_address));
}
/// @notice Returns the full profile for the player with the given gamertag.
function getProfileForTag(string memory _gamertag) public view returns (Player memory) {
address playerAddress = gamertagToPlayer[_gamertag];
if (playerAddress == address(0x0)) {
return Player("", "", "");
}
return Player(
getGamertag(playerAddress),
getClantag(playerAddress),
getPfp(playerAddress)
);
}
function getGamertag(address _address) public view returns (string memory) {
return gamertags[_address];
}
function setGamertag(string memory _gamertag) public whenNotPaused {
// Max length.
require(bytes(_gamertag).length <= gamertagMaxLength, "Yolo Registry: Gamertag too long");
// Ensure unique.
require(!_isGamertagTaken(_gamertag), "Yolo Registry: Gamertag is taken");
chips.spend(msg.sender, gamertagFee);
_setGamertagFor(_gamertag, msg.sender);
}
function getClantag(address _address) public view returns (string memory) {
return clantags[_address];
}
function setClantag(string memory _clantag) public whenNotPaused {
// Max length.
require(bytes(_clantag).length <= clantagMaxLength, "Yolo Registry: Clantag too long");
chips.spend(msg.sender, clantagFee);
clantags[msg.sender] = _clantag;
emit YoloClantagUpdate(msg.sender, _clantag);
}
function getPfp(address _address) public view returns (string memory) {
return pfps[_address];
}
function setPfp(string memory _pfp) public whenNotPaused {
chips.spend(msg.sender, pfpFee);
pfps[msg.sender] = _pfp;
emit YoloProfilePicUpdate(msg.sender, _pfp);
}
// Helpers.
function _setGamertagFor(string memory _gamertag, address _address) internal {
// Free up old gamertag.
string memory previous = gamertags[_address];
if (bytes(previous).length > 0) {
gamertagToPlayer[previous] = address(0x0);
}
// Set new gamertag.
gamertags[_address] = _gamertag;
gamertagToPlayer[_gamertag] = _address;
emit YoloGamertagUpdate(_address, _gamertag);
}
function _isGamertagTaken(string memory _gamertag) internal view returns (bool) {
return gamertagToPlayer[_gamertag] != address(0x0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
interface IYoloDice {
/// @notice IERC721, returns owner of token.
function ownerOf(uint256 tokenId) external view returns (address);
/// @notice IERC721, returns number of tokens owned.
function balanceOf(address owner) external view returns (uint256);
/// @notice IERC721, returns total number of tokens created.
function totalSupply() external view returns (uint256);
/// @notice IERC721Enumerable, returns token ID.
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
}
interface IYoloChips {
/// @notice IERC20, returns number of tokens owned.
function balanceOf(address account) external view returns (uint256);
/// @notice Burns chips from whitelisted contracts.
function spend(address account, uint256 amount) external;
/// @notice Performs accounting before properties are transferred.
function updateOwnership(address _from, address _to) external;
}
interface IYoloBoardDeed {
/// @notice IERC721, returns number of tokens owned.
function balanceOf(address owner) external view returns (uint256);
/// @notice IERC721Enumerable, returns token ID.
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/// @notice Returns yield of the given token.
function yieldRate(uint256 tokenId) external view returns (uint256);
}
// 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;
}
} | Max length. Ensure unique. | function setMultiGamertags(string[] memory _gamertags, address[] memory _addresses) external onlyOwner {
for (uint256 idx = 0; idx < _gamertags.length; idx++) {
require(bytes(_gamertags[idx]).length <= gamertagMaxLength, "Yolo Registry: Gamertag too long");
require(!_isGamertagTaken(_gamertags[idx]), "Yolo Registry: Gamertag is taken");
_setGamertagFor(_gamertags[idx], _addresses[idx]);
}
}
| 12,040,046 |
./partial_match/4/0xAe91bcdd1b0a1793509bF3866673DB4884b73829/sources/CErc20Delegate.sol | require(msg.sender == admin, "only admin may initialize the market"); | function initialize( string memory name_) public {
name = name_;
}
| 8,503,793 |
pragma solidity >=0.6;
/** @title Arbitrator
* Arbitrator abstract contract.
* When developing arbitrator contracts we need to:
* -Define the functions for dispute creation (createDispute) and appeal (appeal). Don't forget to store the arbitrated contract and the disputeID (which should be unique, may nbDisputes).
* -Define the functions for cost display (arbitrationCost and appealCost).
* -Allow giving rulings. For this a function must call arbitrable.rule(disputeID, ruling).
*/
interface IArbitrator {
enum DisputeStatus {Waiting, Appealable, Solved}
/** @dev To be emitted when a dispute is created.
* @param _disputeID ID of the dispute.
* @param _arbitrable The contract which created the dispute.
*/
event DisputeCreation(uint indexed _disputeID, IArbitrable indexed _arbitrable);
/** @dev To be emitted when a dispute can be appealed.
* @param _disputeID ID of the dispute.
* @param _arbitrable The contract which created the dispute.
*/
event AppealPossible(uint indexed _disputeID, IArbitrable indexed _arbitrable);
/** @dev To be emitted when the current ruling is appealed.
* @param _disputeID ID of the dispute.
* @param _arbitrable The contract which created the dispute.
*/
event AppealDecision(uint indexed _disputeID, IArbitrable indexed _arbitrable);
/** @dev Create a dispute. Must be called by the arbitrable contract.
* Must be paid at least arbitrationCost(_extraData).
* @param _choices Amount of choices the arbitrator can make in this dispute.
* @param _extraData Can be used to give additional info on the dispute to be created.
* @return disputeID ID of the dispute created.
*/
function createDispute(uint _choices, bytes calldata _extraData) external payable returns(uint disputeID);
/** @dev Compute the cost of arbitration. It is recommended not to increase it often, as it can be highly time and gas consuming for the arbitrated contracts to cope with fee augmentation.
* @param _extraData Can be used to give additional info on the dispute to be created.
* @return cost Amount to be paid.
*/
function arbitrationCost(bytes calldata _extraData) external view returns(uint cost);
/** @dev Appeal a ruling. Note that it has to be called before the arbitrator contract calls rule.
* @param _disputeID ID of the dispute to be appealed.
* @param _extraData Can be used to give extra info on the appeal.
*/
function appeal(uint _disputeID, bytes calldata _extraData) external payable;
/** @dev Compute the cost of appeal. It is recommended not to increase it often, as it can be higly time and gas consuming for the arbitrated contracts to cope with fee augmentation.
* @param _disputeID ID of the dispute to be appealed.
* @param _extraData Can be used to give additional info on the dispute to be created.
* @return cost Amount to be paid.
*/
function appealCost(uint _disputeID, bytes calldata _extraData) external view returns(uint cost);
/** @dev Compute the start and end of the dispute's current or next appeal period, if possible. If not known or appeal is impossible: should return (0, 0).
* @param _disputeID ID of the dispute.
* @return start The start of the period.
* @return end The end of the period.
*/
function appealPeriod(uint _disputeID) external view returns(uint start, uint end);
/** @dev Return the status of a dispute.
* @param _disputeID ID of the dispute to rule.
* @return status The status of the dispute.
*/
function disputeStatus(uint _disputeID) external view returns(DisputeStatus status);
/** @dev Return the current ruling of a dispute. This is useful for parties to know if they should appeal.
* @param _disputeID ID of the dispute.
* @return ruling The ruling which has been given or the one which will be given if there is no appeal.
*/
function currentRuling(uint _disputeID) external view returns(uint ruling);
}
/** @title IArbitrable
* Arbitrable interface.
* When developing arbitrable contracts, we need to:
* -Define the action taken when a ruling is received by the contract.
* -Allow dispute creation. For this a function must call arbitrator.createDispute.value(_fee)(_choices,_extraData);
*/
interface IArbitrable {
/** @dev To be raised when a ruling is given.
* @param _arbitrator The arbitrator giving the ruling.
* @param _disputeID ID of the dispute in the Arbitrator contract.
* @param _ruling The ruling which was given.
*/
event Ruling(IArbitrator indexed _arbitrator, uint indexed _disputeID, uint _ruling);
/** @dev Give a ruling for a dispute. Must be called by the arbitrator.
* The purpose of this function is to ensure that the address calling it has the right to rule on the contract.
* @param _disputeID ID of the dispute in the Arbitrator contract.
* @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision".
*/
function rule(uint _disputeID, uint _ruling) external;
}
/**
* @title CappedMath
* @dev Math operations with caps for under and overflow.
*/
library CappedMath {
uint constant private UINT_MAX = 2**256 - 1;
/**
* @dev Adds two unsigned integers, returns 2^256 - 1 on overflow.
*/
function addCap(uint _a, uint _b) internal pure returns (uint) {
uint c = _a + _b;
return c >= _a ? c : UINT_MAX;
}
/**
* @dev Subtracts two integers, returns 0 on underflow.
*/
function subCap(uint _a, uint _b) internal pure returns (uint) {
if (_b > _a)
return 0;
else
return _a - _b;
}
/**
* @dev Multiplies two unsigned integers, returns 2^256 - 1 on overflow.
*/
function mulCap(uint _a, uint _b) internal pure returns (uint) {
// Gas optimization: this is cheaper than requiring '_a' not being zero, but the
// benefit is lost if '_b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0)
return 0;
uint c = _a * _b;
return c / _a == _b ? c : UINT_MAX;
}
}
/**
* @title Interface that is implemented on resolve.kleros.io
* Sets a standard arbitrable contract implementation to provide a general purpose user interface.
*/
interface IDisputeResolver is IArbitrable, IEvidence {
/** @dev To be raised inside fundAppeal function.
* @param localDisputeID The dispute id as in arbitrable contract.
* @param round Round code of the appeal. Starts from 0.
* @param ruling Indicates the ruling option which got the contribution.
* @param contributor Caller of fundAppeal function.
* @param amount Contribution amount.
*/
event Contribution(uint indexed localDisputeID, uint indexed round, uint ruling, address indexed contributor, uint amount);
/** @dev To be raised inside withdrawFeesAndRewards function.
* @param localDisputeID The dispute id as in arbitrable contract.
* @param round Round code of the appeal. Starts from 0.
* @param ruling Indicates the ruling option which got the contribution.
* @param contributor Caller of fundAppeal function.
* @param reward Total amount of deposits reimbursed plus rewards. This amount will be sent to contributor as an effect of calling withdrawFeesAndRewards function.
*/
event Withdrawal(uint indexed localDisputeID, uint indexed round, uint ruling, address indexed contributor, uint reward);
/** @dev Maps external (arbitrator side) dispute id to local (arbitrable) dispute id.
* @param _externalDisputeID Dispute id as in arbitrator side.
* @return localDisputeID Dispute id as in arbitrable contract.
*/
function externalIDtoLocalID(uint _externalDisputeID) external returns (uint localDisputeID);
/** @dev Returns number of possible ruling options. Valid rulings are [0, return value].
* @param _localDisputeID Dispute id as in arbitrable contract.
*/
function numberOfRulingOptions(uint _localDisputeID) external view returns (uint numberOfRulingOptions);
/** @dev Allows to submit evidence for a given dispute.
* @param _localDisputeID Index of the dispute in disputes array.
* @param _evidenceURI Link to evidence.
*/
function submitEvidence(uint _localDisputeID, string calldata _evidenceURI) external;
/** @dev TRUSTED. Manages contributions and calls appeal function of the specified arbitrator to appeal a dispute. This function lets appeals be crowdfunded.
Note that we don’t need to check that msg.value is enough to pay arbitration fees as it’s the responsibility of the arbitrator contract.
* @param _localDisputeID Index of the dispute in disputes array.
* @param _ruling The side to which the caller wants to contribute.
*/
function fundAppeal(uint _localDisputeID, uint _ruling) external payable returns (bool fullyFunded);
/** @dev Returns stake multipliers.
* @return winner Winners stake multiplier.
* @return loser Losers stake multiplier.
* @return shared Multiplier when it's tied.
* @return divisor Multiplier divisor.
*/
function getMultipliers() external view returns(uint winner, uint loser, uint shared, uint divisor);
/** @dev Allows to withdraw any reimbursable fees or rewards after the dispute gets solved.
* @param _localDisputeID Index of the dispute in disputes array.
* @param _contributor The address to withdraw its rewards.
* @param _roundNumber The number of the round caller wants to withdraw from.
* @param _ruling A ruling option that the caller wannts to withdraw fees and rewards related to it.
*/
function withdrawFeesAndRewards(uint _localDisputeID, address payable _contributor, uint _roundNumber, uint _ruling) external returns (uint reward);
/** @dev Allows to withdraw any reimbursable fees or rewards after the dispute gets solved. For multiple ruling options at once.
* @param _localDisputeID Index of the dispute in disputes array.
* @param _contributor The address to withdraw its rewards.
* @param _roundNumber The number of the round caller wants to withdraw from.
* @param _contributedTo Rulings that received contributions from contributor.
*/
function withdrawFeesAndRewardsForMultipleRulings(uint _localDisputeID, address payable _contributor, uint _roundNumber, uint[] memory _contributedTo) external;
/** @dev Allows to withdraw any rewards or reimbursable fees after the dispute gets resolved. For multiple rulings options and for all rounds at once.
* @param _localDisputeID Index of the dispute in disputes array.
* @param _contributor The address to withdraw its rewards.
* @param _contributedTo Rulings that received contributions from contributor.
*/
function withdrawFeesAndRewardsForAllRounds(uint _localDisputeID, address payable _contributor, uint[] memory _contributedTo) external;
}
/**
* @title ArbitrableProxy
* A general purpose arbitrable contract. Supports non-binary rulings.
*/
contract ArbitrableProxy is IDisputeResolver {
string public constant VERSION = '1.0.0';
using CappedMath for uint; // Operations bounded between 0 and 2**256 - 1.
event Contribution(uint indexed localDisputeID, uint indexed round, uint ruling, address indexed contributor, uint amount);
event Withdrawal(uint indexed localDisputeID, uint indexed round, uint ruling, address indexed contributor, uint reward);
event SideFunded(uint indexed localDisputeID, uint indexed round, uint indexed ruling);
struct Round {
mapping(uint => uint) paidFees; // Tracks the fees paid by each side in this round.
mapping(uint => bool) hasPaid; // True when the side has fully paid its fee. False otherwise.
mapping(address => mapping(uint => uint)) contributions; // Maps contributors to their contributions for each side.
uint256 feeRewards; // Sum of reimbursable appeal fees available to the parties that made contributions to the side that ultimately wins a dispute.
uint[] fundedSides; // Stores the sides that are fully funded.
uint appealFee; // Fee paid for appeal. Not constant even if the arbitrator is not changing because arbitrator can change this fee.
}
struct DisputeStruct {
bytes arbitratorExtraData;
bool isRuled;
uint ruling;
uint disputeIDOnArbitratorSide;
uint numberOfChoices;
}
address public governor = msg.sender;
IArbitrator public arbitrator;
// The required fee stake that a party must pay depends on who won the previous round and is proportional to the arbitration cost such that the fee stake for a round is stake multiplier * arbitration cost for that round.
// Multipliers are in basis points.
uint public winnerStakeMultiplier; // Multiplier for calculating the fee stake paid by the party that won the previous round.
uint public loserStakeMultiplier; // Multiplier for calculating the fee stake paid by the party that lost the previous round.
uint public sharedStakeMultiplier; // Multiplier for calculating the fee stake that must be paid in the case where there isn't a winner and loser (e.g. when it's the first round or the arbitrator ruled "refused to rule"/"could not rule").
uint public constant MULTIPLIER_DIVISOR = 10000; // Divisor parameter for multipliers.
DisputeStruct[] public disputes;
mapping(uint => uint) public override externalIDtoLocalID; // Maps external (arbitrator side) dispute ids to local dispute ids.
mapping(uint => Round[]) public disputeIDtoRoundArray; // Maps dispute ids round arrays.
/** @dev Constructor
* @param _arbitrator Target global arbitrator for any disputes.
* @param _winnerStakeMultiplier Multiplier of the arbitration cost that the winner has to pay as fee stake for a round in basis points.
* @param _loserStakeMultiplier Multiplier of the arbitration cost that the loser has to pay as fee stake for a round in basis points.
* @param _sharedStakeMultiplier Multiplier of the arbitration cost that each party must pay as fee stake for a round when there isn't a winner/loser in the previous round (e.g. when it's the first round or the arbitrator refused to or did not rule). In basis points.
*/
constructor(IArbitrator _arbitrator, uint _winnerStakeMultiplier, uint _loserStakeMultiplier, uint _sharedStakeMultiplier) public {
arbitrator = _arbitrator;
winnerStakeMultiplier = _winnerStakeMultiplier;
loserStakeMultiplier = _loserStakeMultiplier;
sharedStakeMultiplier = _sharedStakeMultiplier;
}
/** @dev TRUSTED. Calls createDispute function of the specified arbitrator to create a dispute.
Note that we don’t need to check that msg.value is enough to pay arbitration fees as it’s the responsibility of the arbitrator contract.
* @param _arbitratorExtraData Extra data for the arbitrator of prospective dispute.
* @param _metaevidenceURI Link to metaevidence of prospective dispute.
* @param _numberOfChoices Number of currentRuling options.
* @return disputeID Dispute id (on arbitrator side) of the dispute created.
*/
function createDispute(bytes calldata _arbitratorExtraData, string calldata _metaevidenceURI, uint _numberOfChoices) external payable returns(uint disputeID) {
disputeID = arbitrator.createDispute.value(msg.value)(_numberOfChoices, _arbitratorExtraData);
disputes.push(DisputeStruct({
arbitratorExtraData: _arbitratorExtraData,
isRuled: false,
ruling: 0,
disputeIDOnArbitratorSide: disputeID,
numberOfChoices: _numberOfChoices
}));
uint localDisputeID = disputes.length - 1;
externalIDtoLocalID[disputeID] = localDisputeID;
disputeIDtoRoundArray[localDisputeID].push(
Round({
feeRewards: 0,
fundedSides: new uint[](0),
appealFee: 0
})
);
emit MetaEvidence(localDisputeID, _metaevidenceURI);
emit Dispute(arbitrator, disputeID, localDisputeID, localDisputeID);
}
/** @dev Returns number of possible currentRuling options. Valid rulings are [0, return value].
* @param _localDisputeID Dispute id as in arbitrable contract.
*/
function numberOfRulingOptions(uint _localDisputeID) external view override returns (uint numberOfRulingOptions){
numberOfRulingOptions = disputes[_localDisputeID].numberOfChoices;
}
/** @dev TRUSTED. Manages contributions and calls appeal function of the specified arbitrator to appeal a dispute. This function lets appeals be crowdfunded.
Note that we don’t need to check that msg.value is enough to pay arbitration fees as it’s the responsibility of the arbitrator contract.
* @param _localDisputeID Index of the dispute in disputes array.
* @param _ruling The side to which the caller wants to contribute.
* @param fullyFunded Whether _ruling was fully funded after the call.
*/
function fundAppeal(uint _localDisputeID, uint _ruling) external override payable returns (bool fullyFunded){
DisputeStruct storage dispute = disputes[_localDisputeID];
require(_ruling <= dispute.numberOfChoices && _ruling != 0, "There is no such side to fund.");
(uint appealPeriodStart, uint appealPeriodEnd) = arbitrator.appealPeriod(dispute.disputeIDOnArbitratorSide);
require(now >= appealPeriodStart && now < appealPeriodEnd, "Funding must be made within the appeal period.");
uint winner = arbitrator.currentRuling(dispute.disputeIDOnArbitratorSide);
uint multiplier;
if (winner == _ruling){
multiplier = winnerStakeMultiplier;
} else if (winner == 0){
multiplier = sharedStakeMultiplier;
} else {
multiplier = loserStakeMultiplier;
require((_ruling==winner) || (now-appealPeriodStart < (appealPeriodEnd-appealPeriodStart)/2), "The loser must contribute during the first half of the appeal period.");
}
uint appealCost = arbitrator.appealCost(dispute.disputeIDOnArbitratorSide, dispute.arbitratorExtraData);
uint totalCost = appealCost.addCap(appealCost.mulCap(multiplier) / MULTIPLIER_DIVISOR);
Round[] storage rounds = disputeIDtoRoundArray[_localDisputeID];
Round storage lastRound = disputeIDtoRoundArray[_localDisputeID][rounds.length - 1];
require(!lastRound.hasPaid[_ruling], "Appeal fee has already been paid.");
require(msg.value > 0, "Can't contribute zero");
uint contribution = totalCost.subCap(lastRound.paidFees[_ruling]) > msg.value ? msg.value : totalCost.subCap(lastRound.paidFees[_ruling]);
emit Contribution(_localDisputeID, rounds.length - 1, _ruling, msg.sender, contribution);
lastRound.contributions[msg.sender][uint(_ruling)] += contribution;
lastRound.paidFees[uint(_ruling)] += contribution;
if (lastRound.paidFees[_ruling] >= totalCost) {
lastRound.feeRewards += lastRound.paidFees[_ruling];
lastRound.fundedSides.push(_ruling);
lastRound.hasPaid[_ruling] = true;
emit SideFunded(_localDisputeID, rounds.length - 1, _ruling);
}
if (lastRound.fundedSides.length > 1) {
// At least two sides are fully funded.
rounds.push(Round({
feeRewards: 0,
fundedSides: new uint[](0),
appealFee: 0
}));
lastRound.feeRewards = lastRound.feeRewards.subCap(appealCost);
lastRound.appealFee = appealCost;
arbitrator.appeal.value(appealCost)(dispute.disputeIDOnArbitratorSide, dispute.arbitratorExtraData);
}
msg.sender.transfer(msg.value.subCap(contribution)); // Sending extra value back to contributor.
return lastRound.hasPaid[_ruling];
}
/** @dev Allows to withdraw any reimbursable fees or rewards after the dispute gets solved.
* @param _localDisputeID Index of the dispute in disputes array.
* @param _contributor The address to withdraw its rewards.
* @param _roundNumber The number of the round caller wants to withdraw from.
* @param _ruling A currentRuling option that the caller wannts to withdraw fees and rewards related to it.
* @return reward Reward amount that is to be withdrawn. Might be zero if arguments are not qualifying for a reward or reimbursement, or it might be withdrawn already.
*/
function withdrawFeesAndRewards(uint _localDisputeID, address payable _contributor, uint _roundNumber, uint _ruling) public override returns (uint reward) {
DisputeStruct storage dispute = disputes[_localDisputeID];
Round storage round = disputeIDtoRoundArray[_localDisputeID][_roundNumber];
uint8 currentRuling = uint8(dispute.ruling);
require(dispute.isRuled, "The dispute should be solved");
uint reward;
if (!round.hasPaid[_ruling]) {
// Allow to reimburse if funding was unsuccessful.
reward = round.contributions[_contributor][_ruling];
_contributor.send(reward); // User is responsible for accepting the reward.
} else if (currentRuling == 0 || !round.hasPaid[currentRuling]) {
// Reimburse unspent fees proportionally if there is no winner and loser.
reward = round.appealFee > 0 // Means appeal took place.
? (round.contributions[_contributor][_ruling] * round.feeRewards) / (round.feeRewards + round.appealFee)
: 0;
_contributor.send(reward); // User is responsible for accepting the reward.
} else if(currentRuling == _ruling) {
// Reward the winner.
reward = round.paidFees[currentRuling] > 0
? (round.contributions[_contributor][_ruling] * round.feeRewards) / round.paidFees[currentRuling]
: 0;
_contributor.send(reward); // User is responsible for accepting the reward.
}
round.contributions[_contributor][currentRuling] = 0;
emit Withdrawal(_localDisputeID, _roundNumber, _ruling, _contributor, reward);
}
/** @dev Allows to withdraw any reimbursable fees or rewards after the dispute gets solved. For multiple currentRuling options at once.
* @param _localDisputeID Index of the dispute in disputes array.
* @param _contributor The address to withdraw its rewards.
* @param _roundNumber The number of the round caller wants to withdraw from.
* @param _contributedTo Rulings that received contributions from contributor.
*/
function withdrawFeesAndRewardsForMultipleRulings(uint _localDisputeID, address payable _contributor, uint _roundNumber, uint[] memory _contributedTo) public override {
Round storage round = disputeIDtoRoundArray[_localDisputeID][_roundNumber];
for (uint contributionNumber = 0; contributionNumber < _contributedTo.length; contributionNumber++) {
withdrawFeesAndRewards(_localDisputeID, _contributor, _roundNumber, _contributedTo[contributionNumber]);
}
}
/** @dev Allows to withdraw any rewards or reimbursable fees after the dispute gets resolved. For multiple rulings options and for all rounds at once.
* @param _localDisputeID Index of the dispute in disputes array.
* @param _contributor The address to withdraw its rewards.
* @param _contributedTo Rulings that received contributions from contributor.
*/
function withdrawFeesAndRewardsForAllRounds(uint _localDisputeID, address payable _contributor, uint[] memory _contributedTo) external override {
for (uint roundNumber = 0; roundNumber < disputeIDtoRoundArray[_localDisputeID].length; roundNumber++) {
withdrawFeesAndRewardsForMultipleRulings(_localDisputeID, _contributor, roundNumber, _contributedTo);
}
}
/** @dev To be called by the arbitrator of the dispute, to declare winning side.
* @param _externalDisputeID ID of the dispute in arbitrator contract.
* @param _ruling The currentRuling choice of the arbitration.
*/
function rule(uint _externalDisputeID, uint _ruling) external override {
uint _localDisputeID = externalIDtoLocalID[_externalDisputeID];
DisputeStruct storage dispute = disputes[_localDisputeID];
require(msg.sender == address(arbitrator), "Only the arbitrator can execute this.");
require(_ruling <= dispute.numberOfChoices, "Invalid ruling.");
require(dispute.isRuled == false, "This dispute has been ruled already.");
dispute.isRuled = true;
dispute.ruling = _ruling;
Round[] storage rounds = disputeIDtoRoundArray[_localDisputeID];
Round storage lastRound = disputeIDtoRoundArray[_localDisputeID][rounds.length - 1];
// If one side paid its fees, the currentRuling is in its favor. Note that if any other side had also paid, an appeal would have been created.
if (lastRound.fundedSides.length == 1) {
dispute.ruling = lastRound.fundedSides[0];
}
emit Ruling(IArbitrator(msg.sender), _externalDisputeID, uint(dispute.ruling));
}
/** @dev Allows to submit evidence for a given dispute.
* @param _localDisputeID Index of the dispute in disputes array.
* @param _evidenceURI Link to evidence.
*/
function submitEvidence(uint _localDisputeID, string calldata _evidenceURI) external override {
DisputeStruct storage dispute = disputes[_localDisputeID];
require(dispute.isRuled == false, "Cannot submit evidence to a resolved dispute.");
emit Evidence(arbitrator, _localDisputeID, msg.sender, _evidenceURI);
}
/** @dev Changes the proportion of appeal fees that must be paid when there is no winner or loser.
* @param _sharedStakeMultiplier The new tie multiplier value respect to MULTIPLIER_DIVISOR.
*/
function changeSharedStakeMultiplier(uint _sharedStakeMultiplier) external {
require(msg.sender == governor, "Only the governor can execute this.");
sharedStakeMultiplier = _sharedStakeMultiplier;
}
/** @dev Changes the proportion of appeal fees that must be paid by winner.
* @param _winnerStakeMultiplier The new winner multiplier value respect to MULTIPLIER_DIVISOR.
*/
function changeWinnerStakeMultiplier(uint _winnerStakeMultiplier) external {
require(msg.sender == governor, "Only the governor can execute this.");
winnerStakeMultiplier = _winnerStakeMultiplier;
}
/** @dev Changes the proportion of appeal fees that must be paid by loser.
* @param _loserStakeMultiplier The new loser multiplier value respect to MULTIPLIER_DIVISOR.
*/
function changeLoserStakeMultiplier(uint _loserStakeMultiplier) external {
require(msg.sender == governor, "Only the governor can execute this.");
loserStakeMultiplier = _loserStakeMultiplier;
}
/** @dev Gets the information of a round of a dispute.
* @param _localDisputeID ID of the dispute.
* @param _round The round to be queried.
*/
function getRoundInfo(uint _localDisputeID, uint _round)
external
view
returns (
bool appealed,
uint[] memory paidFees,
bool[] memory hasPaid,
uint feeRewards,
uint[] memory fundedSides,
uint appealFee
)
{
Round storage round = disputeIDtoRoundArray[_localDisputeID][_round];
fundedSides = round.fundedSides;
paidFees = new uint[](round.fundedSides.length);
hasPaid = new bool[](round.fundedSides.length);
for (uint i = 0; i < round.fundedSides.length; i++) {
paidFees[i] = round.paidFees[round.fundedSides[i]];
hasPaid[i] = round.hasPaid[round.fundedSides[i]];
}
appealed = _round != (disputeIDtoRoundArray[_localDisputeID].length - 1);
feeRewards = round.feeRewards;
appealFee = round.appealFee;
}
/** @dev Gets the information of a round of a dispute.
* @param _localDisputeID ID of the dispute.
* @param _round The round to be queried.
*/
function getContributions(
uint _localDisputeID,
uint _round,
address _contributor
) public view returns(
uint[] memory fundedSides,
uint[] memory contributions
)
{
Round storage round = disputeIDtoRoundArray[_localDisputeID][_round];
fundedSides = round.fundedSides;
contributions = new uint[](round.fundedSides.length);
for (uint i = 0; i < contributions.length; i++) {
contributions[i] = round.contributions[_contributor][fundedSides[i]];
}
}
/** @dev Gets the crowdfunding information of a last round of a dispute.
* @param _localDisputeID ID of the dispute.
* @param _contributor Address of crowdfunding participant to get details of.
*/
function crowdfundingStatus(
uint _localDisputeID,
address _contributor
) public view returns(
uint[] memory paidFees,
bool[] memory hasPaid,
uint feeRewards,
uint[] memory contributions,
uint[] memory fundedSides
)
{
Round[] storage rounds = disputeIDtoRoundArray[_localDisputeID];
Round storage round = disputeIDtoRoundArray[_localDisputeID][rounds.length -1];
fundedSides = round.fundedSides;
contributions = new uint[](round.fundedSides.length);
paidFees = new uint[](round.fundedSides.length);
hasPaid = new bool[](round.fundedSides.length);
feeRewards = round.feeRewards;
for (uint i = 0; i < round.fundedSides.length; i++) {
paidFees[i] = round.paidFees[round.fundedSides[i]];
hasPaid[i] = round.hasPaid[round.fundedSides[i]];
contributions[i] = round.contributions[_contributor][fundedSides[i]];
}
}
/** @dev Returns stake multipliers.
* @return winner Winners stake multiplier.
* @return loser Losers stake multiplier.
* @return shared Multiplier when it's tied.
* @return divisor Multiplier divisor.
*/
function getMultipliers() external override view returns(uint winner, uint loser, uint shared, uint divisor){
return (winnerStakeMultiplier, loserStakeMultiplier, sharedStakeMultiplier, MULTIPLIER_DIVISOR);
}
/** @dev Proxy getter for arbitration cost.
* @param _arbitratorExtraData Extra data for arbitration cost calculation. See arbitrator for details.
* @return arbitrationFee Arbitration cost of the arbitrator of this contract.
*/
function getArbitrationCost(bytes calldata _arbitratorExtraData) external view returns (uint arbitrationFee) {
arbitrationFee = arbitrator.arbitrationCost(_arbitratorExtraData);
}
/** @dev Returns active disputes.
* @param _cursor Starting point for search.
* @param _count Number of items to return.
* @return openDisputes Dispute identifiers of open disputes, as in arbitrator.
* @return hasMore Whether the search was exhausted (has no more) or not (has more).
*/
function getOpenDisputes(uint _cursor, uint _count) external view returns (uint[] memory openDisputes, bool hasMore)
{
uint noOfOpenDisputes = 0;
for (uint i = 0; i < disputes.length; i++) {
if(disputes[i].isRuled == false){
noOfOpenDisputes++;
}
}
openDisputes = new uint[](noOfOpenDisputes);
uint count = 0;
hasMore = true;
uint i;
for (i = _cursor; i < disputes.length && (count < _count || 0 == _count); i++) {
if(disputes[i].isRuled == false){
openDisputes[count++] = disputes[i].disputeIDOnArbitratorSide;
}
}
if(i == disputes.length) hasMore = false;
}
}
| Returns active disputes. _cursor Starting point for search. _count Number of items to return. return openDisputes Dispute identifiers of open disputes, as in arbitrator. return hasMore Whether the search was exhausted (has no more) or not (has more)./ | function getOpenDisputes(uint _cursor, uint _count) external view returns (uint[] memory openDisputes, bool hasMore)
{
uint noOfOpenDisputes = 0;
for (uint i = 0; i < disputes.length; i++) {
if(disputes[i].isRuled == false){
noOfOpenDisputes++;
}
}
openDisputes = new uint[](noOfOpenDisputes);
uint count = 0;
hasMore = true;
uint i;
for (i = _cursor; i < disputes.length && (count < _count || 0 == _count); i++) {
if(disputes[i].isRuled == false){
openDisputes[count++] = disputes[i].disputeIDOnArbitratorSide;
}
}
if(i == disputes.length) hasMore = false;
}
| 15,866,545 |
./partial_match/1/0x6B83c4f3a6729Fb7D5e19b720092162DF439f567/sources/src/VeFxsVotingDelegation.sol | The ```delegate``` function delegates votes from signer to ```delegatee``` delegatee Address to delegate to nonce Nonce of signed message expiry Expiry time of message v Recovery ID r Output of an ECDSA signature s Output of an ECDSA signature Revert if signature is expired Increment nonce and check against incremented value | function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
if (block.timestamp > expiry) revert IVeFxsVotingDelegation.SignatureExpired();
address signer = ECDSA.recover(
_hashTypedDataV4(keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry))),
v,
r,
s
);
if (nonce != $nonces[signer]++) revert IVeFxsVotingDelegation.InvalidSignatureNonce();
_delegate(signer, delegatee);
}
| 4,454,510 |
/**
*Submitted for verification at Etherscan.io on 2021-05-10
*/
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
pragma solidity ^0.4.23;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 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 Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overriden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropiate to concatenate
* behavior.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
ERC20 public token;
// Address where funds are collected
address public wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 public rate;
// Amount of wei raised
uint256 public weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
/**
* @param _rate Number of token units a buyer gets per wei
* @param _wallet Address where collected funds will be forwarded to
* @param _token Address of the token being sold
*/
constructor(uint256 _rate, address _wallet, ERC20 _token) public {
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
rate = _rate;
wallet = _wallet;
token = _token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(
msg.sender,
_beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
token.transfer(_beneficiary, _tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
_deliverTokens(_beneficiary, _tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param _beneficiary Address receiving the tokens
* @param _weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(
address _beneficiary,
uint256 _weiAmount
)
internal
{
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
return _weiAmount.mul(rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event 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 TimedCrowdsale
* @dev Crowdsale accepting contributions only within a time frame.
*/
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
// solium-disable-next-line security/no-block-members
require(block.timestamp >= openingTime && block.timestamp <= closingTime);
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param _openingTime Crowdsale opening time
* @param _closingTime Crowdsale closing time
*/
constructor(uint256 _openingTime, uint256 _closingTime) public {
// solium-disable-next-line security/no-block-members
require(_openingTime >= block.timestamp);
require(_closingTime >= _openingTime);
openingTime = _openingTime;
closingTime = _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
// solium-disable-next-line security/no-block-members
return block.timestamp > closingTime;
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
onlyWhileOpen
{
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
/**
* @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;
}
}
/**
* @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;
}
}
contract FreezableToken is StandardToken {
// freezing chains
mapping (bytes32 => uint64) internal chains;
// freezing amounts for each chain
mapping (bytes32 => uint) internal freezings;
// total freezing balance per address
mapping (address => uint) internal freezingBalance;
event Freezed(address indexed to, uint64 release, uint amount);
event Released(address indexed owner, uint amount);
/**
* @dev Gets the balance of the specified address include freezing tokens.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner) + freezingBalance[_owner];
}
/**
* @dev Gets the balance of the specified address without freezing tokens.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function actualBalanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner);
}
function freezingBalanceOf(address _owner) public view returns (uint256 balance) {
return freezingBalance[_owner];
}
/**
* @dev gets freezing count
* @param _addr Address of freeze tokens owner.
*/
function freezingCount(address _addr) public view returns (uint count) {
uint64 release = chains[toKey(_addr, 0)];
while (release != 0) {
count++;
release = chains[toKey(_addr, release)];
}
}
/**
* @dev gets freezing end date and freezing balance for the freezing portion specified by index.
* @param _addr Address of freeze tokens owner.
* @param _index Freezing portion index. It ordered by release date descending.
*/
function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) {
for (uint i = 0; i < _index + 1; i++) {
_release = chains[toKey(_addr, _release)];
if (_release == 0) {
return;
}
}
_balance = freezings[toKey(_addr, _release)];
}
/**
* @dev freeze your tokens to the specified address.
* Be careful, gas usage is not deterministic,
* and depends on how many freezes _to address already has.
* @param _to Address to which token will be freeze.
* @param _amount Amount of token to freeze.
* @param _until Release date, must be in future.
*/
function freezeTo(address _to, uint _amount, uint64 _until) public {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Transfer(msg.sender, _to, _amount);
emit Freezed(_to, _until, _amount);
}
/**
* @dev release first available freezing tokens.
*/
function releaseOnce() public {
bytes32 headKey = toKey(msg.sender, 0);
uint64 head = chains[headKey];
require(head != 0);
require(uint64(block.timestamp) > head);
bytes32 currentKey = toKey(msg.sender, head);
uint64 next = chains[currentKey];
uint amount = freezings[currentKey];
delete freezings[currentKey];
balances[msg.sender] = balances[msg.sender].add(amount);
freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount);
if (next == 0) {
delete chains[headKey];
} else {
chains[headKey] = next;
delete chains[currentKey];
}
emit Released(msg.sender, amount);
}
/**
* @dev release all available for release freezing tokens. Gas usage is not deterministic!
* @return how many tokens was released
*/
function releaseAll() public returns (uint tokens) {
uint release;
uint balance;
(release, balance) = getFreezing(msg.sender, 0);
while (release != 0 && block.timestamp > release) {
releaseOnce();
tokens += balance;
(release, balance) = getFreezing(msg.sender, 0);
}
}
function toKey(address _addr, uint _release) internal pure returns (bytes32 result) {
// WISH masc to increase entropy
result = 0x5749534800000000000000000000000000000000000000000000000000000000;
assembly {
result := or(result, mul(_addr, 0x10000000000000000))
result := or(result, and(_release, 0xffffffffffffffff))
}
}
function freeze(address _to, uint64 _until) internal {
require(_until > block.timestamp);
bytes32 key = toKey(_to, _until);
bytes32 parentKey = toKey(_to, uint64(0));
uint64 next = chains[parentKey];
if (next == 0) {
chains[parentKey] = _until;
return;
}
bytes32 nextKey = toKey(_to, next);
uint parent;
while (next != 0 && _until > next) {
parent = next;
parentKey = nextKey;
next = chains[nextKey];
nextKey = toKey(_to, next);
}
if (_until == next) {
return;
}
if (next != 0) {
chains[key] = next;
}
chains[parentKey] = _until;
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
/**
* @title 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();
}
}
contract FreezableMintableToken is FreezableToken, MintableToken {
/**
* @dev Mint the specified amount of token to the specified address and freeze it until the specified date.
* Be careful, gas usage is not deterministic,
* and depends on how many freezes _to address already has.
* @param _to Address to which token will be freeze.
* @param _amount Amount of token to mint and freeze.
* @param _until Release date, must be in future.
* @return A boolean that indicates if the operation was successful.
*/
function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner canMint returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Mint(_to, _amount);
emit Freezed(_to, _until, _amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
}
contract Consts {
uint public constant TOKEN_DECIMALS = 18;
uint8 public constant TOKEN_DECIMALS_UINT8 = 18;
uint public constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS;
string public constant TOKEN_NAME = "Quarashi";
string public constant TOKEN_SYMBOL = "QUA";
bool public constant PAUSED = false;
address public constant TARGET_USER = 0x9ce181Ec2d5b7f5fB504BbF7851C269DC6ee8c14;
uint public constant START_TIME = 1620585780;
bool public constant CONTINUE_MINTING = true;
}
/**
* @title FinalizableCrowdsale
* @dev Extension of Crowdsale where an owner can do extra work
* after finishing.
*/
contract FinalizableCrowdsale is TimedCrowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
require(hasClosed());
finalization();
emit Finalized();
isFinalized = true;
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal {
}
}
/**
* @title CappedCrowdsale
* @dev Crowdsale with a limit for total contributions.
*/
contract CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public cap;
/**
* @dev Constructor, takes maximum amount of wei accepted in the crowdsale.
* @param _cap Max amount of wei to be contributed
*/
constructor(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
/**
* @dev Checks whether the cap has been reached.
* @return Whether the cap was reached
*/
function capReached() public view returns (bool) {
return weiRaised >= cap;
}
/**
* @dev Extend parent behavior requiring purchase to respect the funding cap.
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
super._preValidatePurchase(_beneficiary, _weiAmount);
require(weiRaised.add(_weiAmount) <= cap);
}
}
/**
* @title MintedCrowdsale
* @dev Extension of Crowdsale contract whose tokens are minted in each purchase.
* Token ownership should be transferred to MintedCrowdsale for minting.
*/
contract MintedCrowdsale is Crowdsale {
/**
* @dev Overrides delivery by minting tokens upon purchase.
* @param _beneficiary Token purchaser
* @param _tokenAmount Number of tokens to be minted
*/
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
require(MintableToken(token).mint(_beneficiary, _tokenAmount));
}
}
contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable
{
function name() public pure returns (string _name) {
return TOKEN_NAME;
}
function symbol() public pure returns (string _symbol) {
return TOKEN_SYMBOL;
}
function decimals() public pure returns (uint8 _decimals) {
return TOKEN_DECIMALS_UINT8;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transfer(_to, _value);
}
}
contract MainCrowdsale is Consts, FinalizableCrowdsale, MintedCrowdsale, CappedCrowdsale {
function hasStarted() public view returns (bool) {
return now >= openingTime;
}
function startTime() public view returns (uint256) {
return openingTime;
}
function endTime() public view returns (uint256) {
return closingTime;
}
function hasClosed() public view returns (bool) {
return super.hasClosed() || capReached();
}
function hasEnded() public view returns (bool) {
return hasClosed();
}
function finalization() internal {
super.finalization();
if (PAUSED) {
MainToken(token).unpause();
}
if (!CONTINUE_MINTING) {
require(MintableToken(token).finishMinting());
}
Ownable(token).transferOwnership(TARGET_USER);
}
/**
* @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).div(1 ether);
}
}
contract TemplateCrowdsale is Consts, MainCrowdsale
{
event Initialized();
event TimesChanged(uint startTime, uint endTime, uint oldStartTime, uint oldEndTime);
bool public initialized = false;
constructor(MintableToken _token) public
Crowdsale(10000000 * TOKEN_DECIMAL_MULTIPLIER, 0x18d72133aEE69ecc6834146770282cB10BbB21ab, _token)
TimedCrowdsale(START_TIME > now ? START_TIME : now, 1623339834)
CappedCrowdsale(40000000000000000000)
{
}
function init() public onlyOwner {
require(!initialized);
initialized = true;
if (PAUSED) {
MainToken(token).pause();
}
address[4] memory addresses = [address(0x819a040d48a774a5b3a121bb08dac29ff355ff4e),address(0x2786faf1c49fde5bfa46332a31647f6954425578),address(0x3cc38fdde61a9fb67b4218f1e6d46c6b97a8f193),address(0x66520de7ac01f3de999395efb540cf7b9aaf4ebd)];
uint[4] memory amounts = [uint(200000000000000000000000000),uint(170000000000000000000000000),uint(150000000000000000000000000),uint(80000000000000000000000000)];
uint64[4] memory freezes = [uint64(0),uint64(0),uint64(0),uint64(1638309601)];
for (uint i = 0; i < addresses.length; i++) {
if (freezes[i] == 0) {
MainToken(token).mint(addresses[i], amounts[i]);
} else {
MainToken(token).mintAndFreeze(addresses[i], amounts[i], freezes[i]);
}
}
transferOwnership(TARGET_USER);
emit Initialized();
}
/**
* @dev override hasClosed to add minimal value logic
* @return true if remained to achieve less than minimal
*/
function hasClosed() public view returns (bool) {
bool remainValue = cap.sub(weiRaised) < 100000000000000000;
return super.hasClosed() || remainValue;
}
function setStartTime(uint _startTime) public onlyOwner {
// only if CS was not started
require(now < openingTime);
// only move time to future
require(_startTime > openingTime);
require(_startTime < closingTime);
emit TimesChanged(_startTime, closingTime, openingTime, closingTime);
openingTime = _startTime;
}
function setEndTime(uint _endTime) public onlyOwner {
// only if CS was not ended
require(now < closingTime);
// only if new end time in future
require(now < _endTime);
require(_endTime > openingTime);
emit TimesChanged(openingTime, _endTime, openingTime, closingTime);
closingTime = _endTime;
}
function setTimes(uint _startTime, uint _endTime) public onlyOwner {
require(_endTime > _startTime);
uint oldStartTime = openingTime;
uint oldEndTime = closingTime;
bool changed = false;
if (_startTime != oldStartTime) {
require(_startTime > now);
// only if CS was not started
require(now < oldStartTime);
// only move time to future
require(_startTime > oldStartTime);
openingTime = _startTime;
changed = true;
}
if (_endTime != oldEndTime) {
// only if CS was not ended
require(now < oldEndTime);
// end time in future
require(now < _endTime);
closingTime = _endTime;
changed = true;
}
if (changed) {
emit TimesChanged(openingTime, _endTime, openingTime, closingTime);
}
}
/**
* @dev override purchase validation to add extra value logic.
* @return true if sended more than minimal value
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
require(msg.value >= 100000000000000000);
require(msg.value <= 30000000000000000000);
super._preValidatePurchase(_beneficiary, _weiAmount);
}
} | override purchase validation to add extra value logic. return true if sended more than minimal value/ | function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
require(msg.value >= 100000000000000000);
require(msg.value <= 30000000000000000000);
super._preValidatePurchase(_beneficiary, _weiAmount);
}
| 10,575,482 |
./full_match/137/0x3F7a4089a864Af7980B3632Af5bA10A2b54Ce35A/sources/contracts/Contract.sol | Check that there are at least two players in the game Generate two random numbers to determine which players will participate in the battle Ensure that the two random numbers are different | function startBattle() public {
require(players.length >= 2, "There must be at least two players to start a battle");
uint player1Index = generateRandomNumber(players.length);
uint player2Index = generateRandomNumber(players.length);
while (player1Index == player2Index) {
player2Index = generateRandomNumber(players.length);
}
Player memory player2 = players[player2Index];
uint player2Strength = player2.rarityTrait + battleStrength;
if (player1Strength > player2Strength) {
winner = player1.owner;
winner = player2.owner;
}
uint256(keccak256(abi.encodePacked(block.timestamp, player1.owner, player2.owner))),
player1.owner,
player2.owner,
winner,
player1Strength,
player2Strength,
battleStrength
);
}
| 4,671,112 |
pragma solidity ^0.4.17;
// File: contracts/iERC20Token.sol
// Abstract contract for the full ERC 20 Token standard
// https://github.com/ConsenSys/Tokens
// https://github.com/ethereum/EIPs/issues/20
pragma solidity ^0.4.17;
/// @title iERC20Token contract
contract iERC20Token {
// FIELDS
uint256 public totalSupply = 0;
bytes32 public name;// token name, e.g, pounds for fiat UK pounds.
uint8 public decimals;// How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
bytes32 public symbol;// An identifier: eg SBX.
// NON-CONSTANT METHODS
/// @dev send `_value` tokens to `_to` address/wallet from `msg.sender`.
/// @param _to The address of the recipient.
/// @param _value The amount of token to be transferred.
/// @return Whether the transfer was successful or not.
function transfer(address _to, uint256 _value) public returns (bool success);
/// @dev send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
/// @dev `msg.sender` approves `_spender` to spend `_value` tokens.
/// @param _spender The address of the account able to transfer the tokens.
/// @param _value The amount of tokens to be approved for transfer.
/// @return Whether the approval was successful or not.
function approve(address _spender, uint256 _value) public returns (bool success);
// CONSTANT METHODS
/** @dev Checks the balance of an address without changing the state of the blockchain.
* @param _owner The address to check.
* @return balance An unsigned integer representing the token balance of the address.
*/
function balanceOf(address _owner) public view returns (uint256 balance);
/** @dev Checks for the balance of the tokens of that which the owner had approved another address owner to spend.
* @param _owner The address of the token owner.
* @param _spender The address of the allowed spender.
* @return remaining An unsigned integer representing the remaining approved tokens.
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
// EVENTS
// An event triggered when a transfer of tokens is made from a _from address to a _to address.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
// An event triggered when an owner of tokens successfully approves another address to spend a specified amount of tokens.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
// File: contracts/CurrencyToken.sol
/// @title CurrencyToken contract
contract CurrencyToken {
address public server; // Address, which the platform website uses.
address public populous; // Address of the Populous bank contract.
uint256 public totalSupply;
bytes32 public name;// token name, e.g, pounds for fiat UK pounds.
uint8 public decimals;// How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
bytes32 public symbol;// An identifier: eg SBX.
uint256 constant private MAX_UINT256 = 2**256 - 1;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowed;
//EVENTS
// An event triggered when a transfer of tokens is made from a _from address to a _to address.
event Transfer(
address indexed _from,
address indexed _to,
uint256 _value
);
// An event triggered when an owner of tokens successfully approves another address to spend a specified amount of tokens.
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value
);
event EventMintTokens(bytes32 currency, address owner, uint amount);
event EventDestroyTokens(bytes32 currency, address owner, uint amount);
// MODIFIERS
modifier onlyServer {
require(isServer(msg.sender) == true);
_;
}
modifier onlyServerOrOnlyPopulous {
require(isServer(msg.sender) == true || isPopulous(msg.sender) == true);
_;
}
modifier onlyPopulous {
require(isPopulous(msg.sender) == true);
_;
}
// NON-CONSTANT METHODS
/** @dev Creates a new currency/token.
* param _decimalUnits The decimal units/places the token can have.
* param _tokenSymbol The token's symbol, e.g., GBP.
* param _decimalUnits The tokens decimal unites/precision
* param _amount The amount of tokens to create upon deployment
* param _owner The owner of the tokens created upon deployment
* param _server The server/admin address
*/
function CurrencyToken ()
public
{
populous = server = 0xf8B3d742B245Ec366288160488A12e7A2f1D720D;
symbol = name = 0x55534443; // Set the name for display purposes
decimals = 6; // Amount of decimals for display purposes
balances[server] = safeAdd(balances[server], 10000000000000000);
totalSupply = safeAdd(totalSupply, 10000000000000000);
}
// ERC20
/** @dev Mints a specified amount of tokens
* @param owner The token owner.
* @param amount The amount of tokens to create.
*/
function mint(uint amount, address owner) public onlyServerOrOnlyPopulous returns (bool success) {
balances[owner] = safeAdd(balances[owner], amount);
totalSupply = safeAdd(totalSupply, amount);
emit EventMintTokens(symbol, owner, amount);
return true;
}
/** @dev Destroys a specified amount of tokens
* @dev The method uses a modifier from withAccessManager contract to only permit populous to use it.
* @dev The method uses SafeMath to carry out safe token deductions/subtraction.
* @param amount The amount of tokens to create.
*/
function destroyTokens(uint amount) public onlyServerOrOnlyPopulous returns (bool success) {
require(balances[msg.sender] >= amount);
balances[msg.sender] = safeSub(balances[msg.sender], amount);
totalSupply = safeSub(totalSupply, amount);
emit EventDestroyTokens(symbol, populous, amount);
return true;
}
/** @dev Destroys a specified amount of tokens, from a user.
* @dev The method uses a modifier from withAccessManager contract to only permit populous to use it.
* @dev The method uses SafeMath to carry out safe token deductions/subtraction.
* @param amount The amount of tokens to create.
*/
function destroyTokensFrom(uint amount, address from) public onlyServerOrOnlyPopulous returns (bool success) {
require(balances[from] >= amount);
balances[from] = safeSub(balances[from], amount);
totalSupply = safeSub(totalSupply, amount);
emit EventDestroyTokens(symbol, from, amount);
return true;
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && allowance >= _value);
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
// ACCESS MANAGER
/** @dev Checks a given address to determine whether it is populous address.
* @param sender The address to be checked.
* @return bool returns true or false is the address corresponds to populous or not.
*/
function isPopulous(address sender) public view returns (bool) {
return sender == populous;
}
/** @dev Changes the populous contract address.
* @dev The method requires the message sender to be the set server.
* @param _populous The address to be set as populous.
*/
function changePopulous(address _populous) public {
require(isServer(msg.sender) == true);
populous = _populous;
}
// CONSTANT METHODS
/** @dev Checks a given address to determine whether it is the server.
* @param sender The address to be checked.
* @return bool returns true or false is the address corresponds to the server or not.
*/
function isServer(address sender) public view returns (bool) {
return sender == server;
}
/** @dev Changes the server address that is set by the constructor.
* @dev The method requires the message sender to be the set server.
* @param _server The new address to be set as the server.
*/
function changeServer(address _server) public {
require(isServer(msg.sender) == true);
server = _server;
}
// SAFE MATH
/** @dev Safely multiplies two unsigned/non-negative integers.
* @dev Ensures that one of both numbers can be derived from dividing the product by the other.
* @param a The first number.
* @param b The second number.
* @return uint The expected result.
*/
function safeMul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
/** @dev Safely subtracts one number from another
* @dev Ensures that the number to subtract is lower.
* @param a The first number.
* @param b The second number.
* @return uint The expected result.
*/
function safeSub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
/** @dev Safely adds two unsigned/non-negative integers.
* @dev Ensures that the sum of both numbers is greater or equal to one of both.
* @param a The first number.
* @param b The second number.
* @return uint The expected result.
*/
function safeAdd(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c>=a && c>=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;
}
}
// File: contracts/AccessManager.sol
/// @title AccessManager contract
contract AccessManager {
// FIELDS
// fields that can be changed by constructor and functions
address public server; // Address, which the platform website uses.
address public populous; // Address of the Populous bank contract.
// NON-CONSTANT METHODS
/** @dev Constructor that sets the server when contract is deployed.
* @param _server The address to set as the server.
*/
function AccessManager(address _server) public {
server = _server;
//guardian = _guardian;
}
/** @dev Changes the server address that is set by the constructor.
* @dev The method requires the message sender to be the set server.
* @param _server The new address to be set as the server.
*/
function changeServer(address _server) public {
require(isServer(msg.sender) == true);
server = _server;
}
/** @dev Changes the guardian address that is set by the constructor.
* @dev The method requires the message sender to be the set guardian.
*/
/* function changeGuardian(address _guardian) public {
require(isGuardian(msg.sender) == true);
guardian = _guardian;
} */
/** @dev Changes the populous contract address.
* @dev The method requires the message sender to be the set server.
* @param _populous The address to be set as populous.
*/
function changePopulous(address _populous) public {
require(isServer(msg.sender) == true);
populous = _populous;
}
// CONSTANT METHODS
/** @dev Checks a given address to determine whether it is the server.
* @param sender The address to be checked.
* @return bool returns true or false is the address corresponds to the server or not.
*/
function isServer(address sender) public view returns (bool) {
return sender == server;
}
/** @dev Checks a given address to determine whether it is the guardian.
* @param sender The address to be checked.
* @return bool returns true or false is the address corresponds to the guardian or not.
*/
/* function isGuardian(address sender) public view returns (bool) {
return sender == guardian;
} */
/** @dev Checks a given address to determine whether it is populous address.
* @param sender The address to be checked.
* @return bool returns true or false is the address corresponds to populous or not.
*/
function isPopulous(address sender) public view returns (bool) {
return sender == populous;
}
}
// File: contracts/withAccessManager.sol
/// @title withAccessManager contract
contract withAccessManager {
// FIELDS
AccessManager public AM;
// MODIFIERS
// This modifier uses the isServer method in the AccessManager contract AM to determine
// whether the msg.sender address is server.
modifier onlyServer {
require(AM.isServer(msg.sender) == true);
_;
}
modifier onlyServerOrOnlyPopulous {
require(AM.isServer(msg.sender) == true || AM.isPopulous(msg.sender) == true);
_;
}
// This modifier uses the isGuardian method in the AccessManager contract AM to determine
// whether the msg.sender address is guardian.
/* modifier onlyGuardian {
require(AM.isGuardian(msg.sender) == true);
_;
} */
// This modifier uses the isPopulous method in the AccessManager contract AM to determine
// whether the msg.sender address is populous.
modifier onlyPopulous {
require(AM.isPopulous(msg.sender) == true);
_;
}
// NON-CONSTANT METHODS
/** @dev Sets the AccessManager contract address while deploying this contract`.
* @param _accessManager The address to set.
*/
function withAccessManager(address _accessManager) public {
AM = AccessManager(_accessManager);
}
/** @dev Updates the AccessManager contract address if msg.sender is guardian.
* @param _accessManager The address to set.
*/
function updateAccessManager(address _accessManager) public onlyServer {
AM = AccessManager(_accessManager);
}
}
// File: contracts/ERC1155SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library ERC1155SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// File: contracts/Address.sol
/**
* Utility library of inline functions on addresses
*/
library Address {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
// File: contracts/IERC1155.sol
/// @dev Note: the ERC-165 identifier for this interface is 0xf23a6e61.
interface IERC1155TokenReceiver {
/// @notice Handle the receipt of an ERC1155 type
/// @dev The 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 _id The identifier of the item being transferred
/// @param _value The amount of the item being transferred
/// @param _data Additional data with no specified format
/// @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
/// unless throwing
function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes _data) external returns(bytes4);
}
interface IERC1155 {
event Approval(address indexed _owner, address indexed _spender, uint256 indexed _id, uint256 _oldValue, uint256 _value);
event Transfer(address _spender, address indexed _from, address indexed _to, uint256 indexed _id, uint256 _value);
function transferFrom(address _from, address _to, uint256 _id, uint256 _value) external;
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes _data) external;
function approve(address _spender, uint256 _id, uint256 _currentValue, uint256 _value) external;
function balanceOf(uint256 _id, address _owner) external view returns (uint256);
function allowance(uint256 _id, address _owner, address _spender) external view returns (uint256);
}
interface IERC1155Extended {
function transfer(address _to, uint256 _id, uint256 _value) external;
function safeTransfer(address _to, uint256 _id, uint256 _value, bytes _data) external;
}
interface IERC1155BatchTransfer {
function batchTransferFrom(address _from, address _to, uint256[] _ids, uint256[] _values) external;
function safeBatchTransferFrom(address _from, address _to, uint256[] _ids, uint256[] _values, bytes _data) external;
function batchApprove(address _spender, uint256[] _ids, uint256[] _currentValues, uint256[] _values) external;
}
interface IERC1155BatchTransferExtended {
function batchTransfer(address _to, uint256[] _ids, uint256[] _values) external;
function safeBatchTransfer(address _to, uint256[] _ids, uint256[] _values, bytes _data) external;
}
interface IERC1155Operators {
event OperatorApproval(address indexed _owner, address indexed _operator, uint256 indexed _id, bool _approved);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
function setApproval(address _operator, uint256[] _ids, bool _approved) external;
function isApproved(address _owner, address _operator, uint256 _id) external view returns (bool);
function setApprovalForAll(address _operator, bool _approved) external;
function isApprovedForAll(address _owner, address _operator) external view returns (bool isOperator);
}
interface IERC1155Views {
function totalSupply(uint256 _id) external view returns (uint256);
function name(uint256 _id) external view returns (string);
function symbol(uint256 _id) external view returns (string);
function decimals(uint256 _id) external view returns (uint8);
function uri(uint256 _id) external view returns (string);
}
// File: contracts/ERC1155.sol
contract ERC1155 is IERC1155, IERC1155Extended, IERC1155BatchTransfer, IERC1155BatchTransferExtended {
using ERC1155SafeMath for uint256;
using Address for address;
// Variables
struct Items {
string name;
uint256 totalSupply;
mapping (address => uint256) balances;
}
mapping (uint256 => uint8) public decimals;
mapping (uint256 => string) public symbols;
mapping (uint256 => mapping(address => mapping(address => uint256))) public allowances;
mapping (uint256 => Items) public items;
mapping (uint256 => string) public metadataURIs;
bytes4 constant private ERC1155_RECEIVED = 0xf23a6e61;
/////////////////////////////////////////// IERC1155 //////////////////////////////////////////////
// Events
event Approval(address indexed _owner, address indexed _spender, uint256 indexed _id, uint256 _oldValue, uint256 _value);
event Transfer(address _spender, address indexed _from, address indexed _to, uint256 indexed _id, uint256 _value);
function transferFrom(address _from, address _to, uint256 _id, uint256 _value) external {
if(_from != msg.sender) {
//require(allowances[_id][_from][msg.sender] >= _value);
allowances[_id][_from][msg.sender] = allowances[_id][_from][msg.sender].sub(_value);
}
items[_id].balances[_from] = items[_id].balances[_from].sub(_value);
items[_id].balances[_to] = _value.add(items[_id].balances[_to]);
Transfer(msg.sender, _from, _to, _id, _value);
}
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes _data) external {
//this.transferFrom(_from, _to, _id, _value);
// solium-disable-next-line arg-overflow
require(_checkAndCallSafeTransfer(_from, _to, _id, _value, _data));
if(_from != msg.sender) {
//require(allowances[_id][_from][msg.sender] >= _value);
allowances[_id][_from][msg.sender] = allowances[_id][_from][msg.sender].sub(_value);
}
items[_id].balances[_from] = items[_id].balances[_from].sub(_value);
items[_id].balances[_to] = _value.add(items[_id].balances[_to]);
Transfer(msg.sender, _from, _to, _id, _value);
}
function approve(address _spender, uint256 _id, uint256 _currentValue, uint256 _value) external {
// if the allowance isn't 0, it can only be updated to 0 to prevent an allowance change immediately after withdrawal
require(_value == 0 || allowances[_id][msg.sender][_spender] == _currentValue);
allowances[_id][msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _id, _currentValue, _value);
}
function balanceOf(uint256 _id, address _owner) external view returns (uint256) {
return items[_id].balances[_owner];
}
function allowance(uint256 _id, address _owner, address _spender) external view returns (uint256) {
return allowances[_id][_owner][_spender];
}
/////////////////////////////////////// IERC1155Extended //////////////////////////////////////////
function transfer(address _to, uint256 _id, uint256 _value) external {
// Not needed. SafeMath will do the same check on .sub(_value)
//require(_value <= items[_id].balances[msg.sender]);
items[_id].balances[msg.sender] = items[_id].balances[msg.sender].sub(_value);
items[_id].balances[_to] = _value.add(items[_id].balances[_to]);
Transfer(msg.sender, msg.sender, _to, _id, _value);
}
function safeTransfer(address _to, uint256 _id, uint256 _value, bytes _data) external {
//this.transfer(_to, _id, _value);
// solium-disable-next-line arg-overflow
require(_checkAndCallSafeTransfer(msg.sender, _to, _id, _value, _data));
items[_id].balances[msg.sender] = items[_id].balances[msg.sender].sub(_value);
items[_id].balances[_to] = _value.add(items[_id].balances[_to]);
Transfer(msg.sender, msg.sender, _to, _id, _value);
}
//////////////////////////////////// IERC1155BatchTransfer ////////////////////////////////////////
function batchTransferFrom(address _from, address _to, uint256[] _ids, uint256[] _values) external {
uint256 _id;
uint256 _value;
if(_from == msg.sender) {
for (uint256 i = 0; i < _ids.length; ++i) {
_id = _ids[i];
_value = _values[i];
items[_id].balances[_from] = items[_id].balances[_from].sub(_value);
items[_id].balances[_to] = _value.add(items[_id].balances[_to]);
Transfer(msg.sender, _from, _to, _id, _value);
}
}
else {
for (i = 0; i < _ids.length; ++i) {
_id = _ids[i];
_value = _values[i];
allowances[_id][_from][msg.sender] = allowances[_id][_from][msg.sender].sub(_value);
items[_id].balances[_from] = items[_id].balances[_from].sub(_value);
items[_id].balances[_to] = _value.add(items[_id].balances[_to]);
Transfer(msg.sender, _from, _to, _id, _value);
}
}
}
function safeBatchTransferFrom(address _from, address _to, uint256[] _ids, uint256[] _values, bytes _data) external {
//this.batchTransferFrom(_from, _to, _ids, _values);
for (uint256 i = 0; i < _ids.length; ++i) {
// solium-disable-next-line arg-overflow
require(_checkAndCallSafeTransfer(_from, _to, _ids[i], _values[i], _data));
}
uint256 _id;
uint256 _value;
if(_from == msg.sender) {
for (i = 0; i < _ids.length; ++i) {
_id = _ids[i];
_value = _values[i];
items[_id].balances[_from] = items[_id].balances[_from].sub(_value);
items[_id].balances[_to] = _value.add(items[_id].balances[_to]);
Transfer(msg.sender, _from, _to, _id, _value);
}
}
else {
for (i = 0; i < _ids.length; ++i) {
_id = _ids[i];
_value = _values[i];
allowances[_id][_from][msg.sender] = allowances[_id][_from][msg.sender].sub(_value);
items[_id].balances[_from] = items[_id].balances[_from].sub(_value);
items[_id].balances[_to] = _value.add(items[_id].balances[_to]);
Transfer(msg.sender, _from, _to, _id, _value);
}
}
}
function batchApprove(address _spender, uint256[] _ids, uint256[] _currentValues, uint256[] _values) external {
uint256 _id;
uint256 _value;
for (uint256 i = 0; i < _ids.length; ++i) {
_id = _ids[i];
_value = _values[i];
require(_value == 0 || allowances[_id][msg.sender][_spender] == _currentValues[i]);
allowances[_id][msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _id, _currentValues[i], _value);
}
}
//////////////////////////////// IERC1155BatchTransferExtended ////////////////////////////////////
function batchTransfer(address _to, uint256[] _ids, uint256[] _values) external {
uint256 _id;
uint256 _value;
for (uint256 i = 0; i < _ids.length; ++i) {
_id = _ids[i];
_value = _values[i];
items[_id].balances[msg.sender] = items[_id].balances[msg.sender].sub(_value);
items[_id].balances[_to] = _value.add(items[_id].balances[_to]);
Transfer(msg.sender, msg.sender, _to, _id, _value);
}
}
function safeBatchTransfer(address _to, uint256[] _ids, uint256[] _values, bytes _data) external {
//this.batchTransfer(_to, _ids, _values);
for (uint256 i = 0; i < _ids.length; ++i) {
// solium-disable-next-line arg-overflow
require(_checkAndCallSafeTransfer(msg.sender, _to, _ids[i], _values[i], _data));
}
uint256 _id;
uint256 _value;
for (i = 0; i < _ids.length; ++i) {
_id = _ids[i];
_value = _values[i];
items[_id].balances[msg.sender] = items[_id].balances[msg.sender].sub(_value);
items[_id].balances[_to] = _value.add(items[_id].balances[_to]);
Transfer(msg.sender, msg.sender, _to, _id, _value);
}
}
//////////////////////////////// IERC1155BatchTransferExtended ////////////////////////////////////
// Optional meta data view Functions
// consider multi-lingual support for name?
function name(uint256 _id) external view returns (string) {
return items[_id].name;
}
function symbol(uint256 _id) external view returns (string) {
return symbols[_id];
}
function decimals(uint256 _id) external view returns (uint8) {
return decimals[_id];
}
function totalSupply(uint256 _id) external view returns (uint256) {
return items[_id].totalSupply;
}
function uri(uint256 _id) external view returns (string) {
return metadataURIs[_id];
}
////////////////////////////////////////// OPTIONALS //////////////////////////////////////////////
function multicastTransfer(address[] _to, uint256[] _ids, uint256[] _values) external {
for (uint256 i = 0; i < _to.length; ++i) {
uint256 _id = _ids[i];
uint256 _value = _values[i];
address _dst = _to[i];
items[_id].balances[msg.sender] = items[_id].balances[msg.sender].sub(_value);
items[_id].balances[_dst] = _value.add(items[_id].balances[_dst]);
Transfer(msg.sender, msg.sender, _dst, _id, _value);
}
}
function safeMulticastTransfer(address[] _to, uint256[] _ids, uint256[] _values, bytes _data) external {
//this.multicastTransfer(_to, _ids, _values);
for (uint256 i = 0; i < _ids.length; ++i) {
// solium-disable-next-line arg-overflow
require(_checkAndCallSafeTransfer(msg.sender, _to[i], _ids[i], _values[i], _data));
}
for (i = 0; i < _to.length; ++i) {
uint256 _id = _ids[i];
uint256 _value = _values[i];
address _dst = _to[i];
items[_id].balances[msg.sender] = items[_id].balances[msg.sender].sub(_value);
items[_id].balances[_dst] = _value.add(items[_id].balances[_dst]);
Transfer(msg.sender, msg.sender, _dst, _id, _value);
}
}
////////////////////////////////////////// INTERNAL //////////////////////////////////////////////
function _checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _id,
uint256 _value,
bytes _data
)
internal
returns (bool)
{
if (!_to.isContract()) {
return true;
}
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received(
msg.sender, _from, _id, _value, _data);
return (retval == ERC1155_RECEIVED);
}
}
// File: contracts/ERC165.sol
/**
* @title ERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
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.
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool);
}
// File: contracts/ERC721Basic.sol
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Basic is ERC165 {
bytes4 internal constant InterfaceId_ERC721 = 0x80ac58cd;
/*
* 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_ERC721Exists = 0x4f558e79;
/*
* 0x4f558e79 ===
* bytes4(keccak256('exists(uint256)'))
*/
bytes4 internal constant InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
bytes4 internal constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/**
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
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) 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;
}
// File: contracts/DepositContract.sol
/// @title DepositContract contract
contract DepositContract is withAccessManager {
bytes32 public clientId; // client ID.
uint256 public version = 2;
// EVENTS
event EtherTransfer(address to, uint256 value);
// NON-CONSTANT METHODS
/** @dev Constructor that sets the _clientID when the contract is deployed.
* @dev The method also sets the manager to the msg.sender.
* @param _clientId A string of fixed length representing the client ID.
*/
function DepositContract(bytes32 _clientId, address accessManager) public withAccessManager(accessManager) {
clientId = _clientId;
}
/** @dev Transfers an amount '_value' of tokens from msg.sender to '_to' address/wallet.
* @param populousTokenContract The address of the ERC20 token contract which implements the transfer method.
* @param _value the amount of tokens to transfer.
* @param _to The address/wallet to send to.
* @return success boolean true or false indicating whether the transfer was successful or not.
*/
function transfer(address populousTokenContract, address _to, uint256 _value) public
onlyServerOrOnlyPopulous returns (bool success)
{
return iERC20Token(populousTokenContract).transfer(_to, _value);
}
/** @dev This function will transfer iERC1155 tokens
*/
function transferERC1155(address _erc1155Token, address _to, uint256 _id, uint256 _value)
public onlyServerOrOnlyPopulous returns (bool success) {
ERC1155(_erc1155Token).safeTransfer(_to, _id, _value, "");
return true;
}
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer` if the recipient is a smart contract. This function MAY throw to revert and reject the
* transfer. Return of other than the magic value (0x150b7a02) 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) {
return 0x150b7a02;
}
/// @notice Handle the receipt of an ERC1155 type
/// @dev The 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 _id The identifier of the item being transferred
/// @param _value The amount of the item being transferred
/// @param _data Additional data with no specified format
/// @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
/// unless throwing
function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes _data) public returns(bytes4) {
return 0xf23a6e61;
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
*
* Requires the msg sender to be the owner, approved, or operator
* @param erc721Token address of the erc721 token to target
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function transferERC721(
address erc721Token,
address _to,
uint256 _tokenId
)
public onlyServerOrOnlyPopulous returns (bool success)
{
// solium-disable-next-line arg-overflow
ERC721Basic(erc721Token).safeTransferFrom(this, _to, _tokenId, "");
return true;
}
/** @dev Transfers ether from this contract to a specified wallet/address
* @param _to An address implementing to send ether to.
* @param _value The amount of ether to send in wei.
* @return bool Successful or unsuccessful transfer
*/
function transferEther(address _to, uint256 _value) public
onlyServerOrOnlyPopulous returns (bool success)
{
require(this.balance >= _value);
require(_to.send(_value) == true);
EtherTransfer(_to, _value);
return true;
}
// payable function to allow this contract receive ether - for version 3
//function () public payable {}
// CONSTANT METHODS
/** @dev Returns the ether or token balance of the current contract instance using the ERC20 balanceOf method.
* @param populousTokenContract An address implementing the ERC20 token standard.
* @return uint An unsigned integer representing the returned token balance.
*/
function balanceOf(address populousTokenContract) public view returns (uint256) {
// ether
if (populousTokenContract == address(0)) {
return address(this).balance;
} else {
// erc20
return iERC20Token(populousTokenContract).balanceOf(this);
}
}
/**
* @dev Gets the balance of the specified address
* @param erc721Token address to erc721 token to target
* @return uint256 representing the amount owned by the passed address
*/
function balanceOfERC721(address erc721Token) public view returns (uint256) {
return ERC721Basic(erc721Token).balanceOf(this);
// returns ownedTokensCount[_owner];
}
/**
* @dev Gets the balance of the specified address
* @param _id the token id
* @param erc1155Token address to erc1155 token to target
* @return uint256 representing the amount owned by the passed address
*/
function balanceOfERC1155(address erc1155Token, uint256 _id) external view returns (uint256) {
return ERC1155(erc1155Token).balanceOf(_id, this);
}
/** @dev Gets the version of this deposit contract
* @return uint256 version
*/
function getVersion() public view returns (uint256) {
return version;
}
// CONSTANT FUNCTIONS
/** @dev This function gets the client ID or deposit contract owner
* returns _clientId
*/
function getClientId() public view returns (bytes32 _clientId) {
return clientId;
}
}
// File: contracts/SafeMath.sol
/// @title Overflow aware uint math functions.
/// @notice Inspired by https://github.com/MakerDAO/maker-otc/blob/master/contracts/simple_market.sol
library SafeMath {
/** @dev Safely multiplies two unsigned/non-negative integers.
* @dev Ensures that one of both numbers can be derived from dividing the product by the other.
* @param a The first number.
* @param b The second number.
* @return uint The expected result.
*/
function safeMul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
/** @dev Safely subtracts one number from another
* @dev Ensures that the number to subtract is lower.
* @param a The first number.
* @param b The second number.
* @return uint The expected result.
*/
function safeSub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
/** @dev Safely adds two unsigned/non-negative integers.
* @dev Ensures that the sum of both numbers is greater or equal to one of both.
* @param a The first number.
* @param b The second number.
* @return uint The expected result.
*/
function safeAdd(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c>=a && c>=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;
}
}
// File: contracts/iDataManager.sol
/// @title DataManager contract
contract iDataManager {
// FIELDS
uint256 public version;
// currency symbol => currency erc20 contract address
mapping(bytes32 => address) public currencyAddresses;
// currency address => currency symbol
mapping(address => bytes32) public currencySymbols;
// clientId => depositAddress
mapping(bytes32 => address) public depositAddresses;
// depositAddress => clientId
mapping(address => bytes32) public depositClientIds;
// blockchainActionId => boolean
mapping(bytes32 => bool) public actionStatus;
// blockchainActionData
struct actionData {
bytes32 currency;
uint amount;
bytes32 accountId;
address to;
uint pptFee;
}
// blockchainActionId => actionData
mapping(bytes32 => actionData) public blockchainActionIdData;
//actionId => invoiceId
mapping(bytes32 => bytes32) public actionIdToInvoiceId;
// invoice provider company data
struct providerCompany {
//bool isEnabled;
bytes32 companyNumber;
bytes32 companyName;
bytes2 countryCode;
}
// companyCode => companyNumber => providerId
mapping(bytes2 => mapping(bytes32 => bytes32)) public providerData;
// providedId => providerCompany
mapping(bytes32 => providerCompany) public providerCompanyData;
// crowdsale invoiceDetails
struct _invoiceDetails {
bytes2 invoiceCountryCode;
bytes32 invoiceCompanyNumber;
bytes32 invoiceCompanyName;
bytes32 invoiceNumber;
}
// crowdsale invoiceData
struct invoiceData {
bytes32 providerUserId;
bytes32 invoiceCompanyName;
}
// country code => company number => invoice number => invoice data
mapping(bytes2 => mapping(bytes32 => mapping(bytes32 => invoiceData))) public invoices;
// NON-CONSTANT METHODS
/** @dev Adds a new deposit smart contract address linked to a client id
* @param _depositAddress the deposit smart contract address
* @param _clientId the client id
* @return success true/false denoting successful function call
*/
function setDepositAddress(bytes32 _blockchainActionId, address _depositAddress, bytes32 _clientId) public returns (bool success);
/** @dev Adds a new currency sumbol and smart contract address
* @param _currencyAddress the currency smart contract address
* @param _currencySymbol the currency symbol
* @return success true/false denoting successful function call
*/
function setCurrency(bytes32 _blockchainActionId, address _currencyAddress, bytes32 _currencySymbol) public returns (bool success);
/** @dev Updates a currency sumbol and smart contract address
* @param _currencyAddress the currency smart contract address
* @param _currencySymbol the currency symbol
* @return success true/false denoting successful function call
*/
function _setCurrency(bytes32 _blockchainActionId, address _currencyAddress, bytes32 _currencySymbol) public returns (bool success);
/** @dev set blockchain action data in struct
* @param _blockchainActionId the blockchain action id
* @param currency the token currency symbol
* @param accountId the clientId
* @param to the blockchain address or smart contract address used in the transaction
* @param amount the amount of tokens in the transaction
* @return success true/false denoting successful function call
*/
function setBlockchainActionData(
bytes32 _blockchainActionId, bytes32 currency,
uint amount, bytes32 accountId, address to, uint pptFee)
public
returns (bool success);
/** @dev upgrade deposit address
* @param _blockchainActionId the blockchain action id
* @param _clientId the client id
* @param _depositContract the deposit contract address for the client
* @return success true/false denoting successful function call
*/
function upgradeDepositAddress(bytes32 _blockchainActionId, bytes32 _clientId, address _depositContract) public returns (bool success);
/** @dev Updates a deposit address for client id
* @param _blockchainActionId the blockchain action id
* @param _clientId the client id
* @param _depositContract the deposit contract address for the client
* @return success true/false denoting successful function call
*/
function _setDepositAddress(bytes32 _blockchainActionId, bytes32 _clientId, address _depositContract) public returns (bool success);
/** @dev Add a new invoice to the platform
* @param _providerUserId the providers user id
* @param _invoiceCountryCode the country code of the provider
* @param _invoiceCompanyNumber the providers company number
* @param _invoiceCompanyName the providers company name
* @param _invoiceNumber the invoice number
* @return success true or false if function call is successful
*/
function setInvoice(
bytes32 _blockchainActionId, bytes32 _providerUserId, bytes2 _invoiceCountryCode,
bytes32 _invoiceCompanyNumber, bytes32 _invoiceCompanyName, bytes32 _invoiceNumber)
public returns (bool success);
/** @dev Add a new invoice provider to the platform
* @param _blockchainActionId the blockchain action id
* @param _userId the user id of the provider
* @param _companyNumber the providers company number
* @param _companyName the providers company name
* @param _countryCode the providers country code
* @return success true or false if function call is successful
*/
function setProvider(
bytes32 _blockchainActionId, bytes32 _userId, bytes32 _companyNumber,
bytes32 _companyName, bytes2 _countryCode)
public returns (bool success);
/** @dev Update an added invoice provider to the platform
* @param _blockchainActionId the blockchain action id
* @param _userId the user id of the provider
* @param _companyNumber the providers company number
* @param _companyName the providers company name
* @param _countryCode the providers country code
* @return success true or false if function call is successful
*/
function _setProvider(
bytes32 _blockchainActionId, bytes32 _userId, bytes32 _companyNumber,
bytes32 _companyName, bytes2 _countryCode)
public returns (bool success);
// CONSTANT METHODS
/** @dev Gets a deposit address with the client id
* @return clientDepositAddress The client's deposit address
*/
function getDepositAddress(bytes32 _clientId) public view returns (address clientDepositAddress);
/** @dev Gets a client id linked to a deposit address
* @return depositClientId The client id
*/
function getClientIdWithDepositAddress(address _depositContract) public view returns (bytes32 depositClientId);
/** @dev Gets a currency smart contract address
* @return currencyAddress The currency address
*/
function getCurrency(bytes32 _currencySymbol) public view returns (address currencyAddress);
/** @dev Gets a currency symbol given it's smart contract address
* @return currencySymbol The currency symbol
*/
function getCurrencySymbol(address _currencyAddress) public view returns (bytes32 currencySymbol);
/** @dev Gets details of a currency given it's smart contract address
* @return _symbol The currency symbol
* @return _name The currency name
* @return _decimals The currency decimal places/precision
*/
function getCurrencyDetails(address _currencyAddress) public view returns (bytes32 _symbol, bytes32 _name, uint8 _decimals);
/** @dev Get the blockchain action Id Data for a blockchain Action id
* @param _blockchainActionId the blockchain action id
* @return bytes32 currency
* @return uint amount
* @return bytes32 accountId
* @return address to
*/
function getBlockchainActionIdData(bytes32 _blockchainActionId) public view returns (bytes32 _currency, uint _amount, bytes32 _accountId, address _to);
/** @dev Get the bool status of a blockchain Action id
* @param _blockchainActionId the blockchain action id
* @return bool actionStatus
*/
function getActionStatus(bytes32 _blockchainActionId) public view returns (bool _blockchainActionStatus);
/** @dev Gets the details of an invoice with the country code, company number and invocie number.
* @param _invoiceCountryCode The country code.
* @param _invoiceCompanyNumber The company number.
* @param _invoiceNumber The invoice number
* @return providerUserId The invoice provider user Id
* @return invoiceCompanyName the invoice company name
*/
function getInvoice(bytes2 _invoiceCountryCode, bytes32 _invoiceCompanyNumber, bytes32 _invoiceNumber)
public
view
returns (bytes32 providerUserId, bytes32 invoiceCompanyName);
/** @dev Gets the details of an invoice provider with the country code and company number.
* @param _providerCountryCode The country code.
* @param _providerCompanyNumber The company number.
* @return isEnabled The boolean value true/false indicating whether invoice provider is enabled or not
* @return providerId The invoice provider user Id
* @return companyName the invoice company name
*/
function getProviderByCountryCodeCompanyNumber(bytes2 _providerCountryCode, bytes32 _providerCompanyNumber)
public
view
returns (bytes32 providerId, bytes32 companyName);
/** @dev Gets the details of an invoice provider with the providers user Id.
* @param _providerUserId The provider user Id.
* @return countryCode The invoice provider country code
* @return companyName the invoice company name
*/
function getProviderByUserId(bytes32 _providerUserId) public view
returns (bytes2 countryCode, bytes32 companyName, bytes32 companyNumber);
/** @dev Gets the version number for the current contract instance
* @return _version The version number
*/
function getVersion() public view returns (uint256 _version);
}
// File: contracts/DataManager.sol
/// @title DataManager contract
contract DataManager is iDataManager, withAccessManager {
// NON-CONSTANT METHODS
/** @dev Constructor that sets the server when contract is deployed.
* @param _accessManager The address to set as the access manager.
*/
function DataManager(address _accessManager, uint256 _version) public withAccessManager(_accessManager) {
version = _version;
}
/** @dev Adds a new deposit smart contract address linked to a client id
* @param _depositAddress the deposit smart contract address
* @param _clientId the client id
* @return success true/false denoting successful function call
*/
function setDepositAddress(bytes32 _blockchainActionId, address _depositAddress, bytes32 _clientId) public onlyServerOrOnlyPopulous returns (bool success) {
require(actionStatus[_blockchainActionId] == false);
require(depositAddresses[_clientId] == 0x0 && depositClientIds[_depositAddress] == 0x0);
depositAddresses[_clientId] = _depositAddress;
depositClientIds[_depositAddress] = _clientId;
assert(depositAddresses[_clientId] != 0x0 && depositClientIds[_depositAddress] != 0x0);
return true;
}
/** @dev Adds a new currency sumbol and smart contract address
* @param _currencyAddress the currency smart contract address
* @param _currencySymbol the currency symbol
* @return success true/false denoting successful function call
*/
function setCurrency(bytes32 _blockchainActionId, address _currencyAddress, bytes32 _currencySymbol) public onlyServerOrOnlyPopulous returns (bool success) {
require(actionStatus[_blockchainActionId] == false);
require(currencySymbols[_currencyAddress] == 0x0 && currencyAddresses[_currencySymbol] == 0x0);
currencySymbols[_currencyAddress] = _currencySymbol;
currencyAddresses[_currencySymbol] = _currencyAddress;
assert(currencyAddresses[_currencySymbol] != 0x0 && currencySymbols[_currencyAddress] != 0x0);
return true;
}
/** @dev Updates a currency sumbol and smart contract address
* @param _currencyAddress the currency smart contract address
* @param _currencySymbol the currency symbol
* @return success true/false denoting successful function call
*/
function _setCurrency(bytes32 _blockchainActionId, address _currencyAddress, bytes32 _currencySymbol) public onlyServerOrOnlyPopulous returns (bool success) {
require(actionStatus[_blockchainActionId] == false);
currencySymbols[_currencyAddress] = _currencySymbol;
currencyAddresses[_currencySymbol] = _currencyAddress;
assert(currencyAddresses[_currencySymbol] != 0x0 && currencySymbols[_currencyAddress] != 0x0);
setBlockchainActionData(_blockchainActionId, _currencySymbol, 0, 0x0, _currencyAddress, 0);
return true;
}
/** @dev set blockchain action data in struct
* @param _blockchainActionId the blockchain action id
* @param currency the token currency symbol
* @param accountId the clientId
* @param to the blockchain address or smart contract address used in the transaction
* @param amount the amount of tokens in the transaction
* @return success true/false denoting successful function call
*/
function setBlockchainActionData(
bytes32 _blockchainActionId, bytes32 currency,
uint amount, bytes32 accountId, address to, uint pptFee)
public
onlyServerOrOnlyPopulous
returns (bool success)
{
require(actionStatus[_blockchainActionId] == false);
blockchainActionIdData[_blockchainActionId].currency = currency;
blockchainActionIdData[_blockchainActionId].amount = amount;
blockchainActionIdData[_blockchainActionId].accountId = accountId;
blockchainActionIdData[_blockchainActionId].to = to;
blockchainActionIdData[_blockchainActionId].pptFee = pptFee;
actionStatus[_blockchainActionId] = true;
return true;
}
/** @dev Updates a deposit address for client id
* @param _blockchainActionId the blockchain action id
* @param _clientId the client id
* @param _depositContract the deposit contract address for the client
* @return success true/false denoting successful function call
*/
function _setDepositAddress(bytes32 _blockchainActionId, bytes32 _clientId, address _depositContract) public
onlyServerOrOnlyPopulous
returns (bool success)
{
require(actionStatus[_blockchainActionId] == false);
depositAddresses[_clientId] = _depositContract;
depositClientIds[_depositContract] = _clientId;
// check that deposit address has been stored for client Id
assert(depositAddresses[_clientId] == _depositContract && depositClientIds[_depositContract] == _clientId);
// set blockchain action data
setBlockchainActionData(_blockchainActionId, 0x0, 0, _clientId, depositAddresses[_clientId], 0);
return true;
}
/** @dev Add a new invoice to the platform
* @param _providerUserId the providers user id
* @param _invoiceCountryCode the country code of the provider
* @param _invoiceCompanyNumber the providers company number
* @param _invoiceCompanyName the providers company name
* @param _invoiceNumber the invoice number
* @return success true or false if function call is successful
*/
function setInvoice(
bytes32 _blockchainActionId, bytes32 _providerUserId, bytes2 _invoiceCountryCode,
bytes32 _invoiceCompanyNumber, bytes32 _invoiceCompanyName, bytes32 _invoiceNumber)
public
onlyServerOrOnlyPopulous
returns (bool success)
{
require(actionStatus[_blockchainActionId] == false);
bytes32 providerUserId;
bytes32 companyName;
(providerUserId, companyName) = getInvoice(_invoiceCountryCode, _invoiceCompanyNumber, _invoiceNumber);
require(providerUserId == 0x0 && companyName == 0x0);
// country code => company number => invoice number => invoice data
invoices[_invoiceCountryCode][_invoiceCompanyNumber][_invoiceNumber].providerUserId = _providerUserId;
invoices[_invoiceCountryCode][_invoiceCompanyNumber][_invoiceNumber].invoiceCompanyName = _invoiceCompanyName;
assert(
invoices[_invoiceCountryCode][_invoiceCompanyNumber][_invoiceNumber].providerUserId != 0x0 &&
invoices[_invoiceCountryCode][_invoiceCompanyNumber][_invoiceNumber].invoiceCompanyName != 0x0
);
return true;
}
/** @dev Add a new invoice provider to the platform
* @param _blockchainActionId the blockchain action id
* @param _userId the user id of the provider
* @param _companyNumber the providers company number
* @param _companyName the providers company name
* @param _countryCode the providers country code
* @return success true or false if function call is successful
*/
function setProvider(
bytes32 _blockchainActionId, bytes32 _userId, bytes32 _companyNumber,
bytes32 _companyName, bytes2 _countryCode)
public
onlyServerOrOnlyPopulous
returns (bool success)
{
require(actionStatus[_blockchainActionId] == false);
require(
providerCompanyData[_userId].companyNumber == 0x0 &&
providerCompanyData[_userId].countryCode == 0x0 &&
providerCompanyData[_userId].companyName == 0x0);
providerCompanyData[_userId].countryCode = _countryCode;
providerCompanyData[_userId].companyName = _companyName;
providerCompanyData[_userId].companyNumber = _companyNumber;
providerData[_countryCode][_companyNumber] = _userId;
return true;
}
/** @dev Update an added invoice provider to the platform
* @param _blockchainActionId the blockchain action id
* @param _userId the user id of the provider
* @param _companyNumber the providers company number
* @param _companyName the providers company name
* @param _countryCode the providers country code
* @return success true or false if function call is successful
*/
function _setProvider(
bytes32 _blockchainActionId, bytes32 _userId, bytes32 _companyNumber,
bytes32 _companyName, bytes2 _countryCode)
public
onlyServerOrOnlyPopulous
returns (bool success)
{
require(actionStatus[_blockchainActionId] == false);
providerCompanyData[_userId].countryCode = _countryCode;
providerCompanyData[_userId].companyName = _companyName;
providerCompanyData[_userId].companyNumber = _companyNumber;
providerData[_countryCode][_companyNumber] = _userId;
setBlockchainActionData(_blockchainActionId, 0x0, 0, _userId, 0x0, 0);
return true;
}
// CONSTANT METHODS
/** @dev Gets a deposit address with the client id
* @return clientDepositAddress The client's deposit address
*/
function getDepositAddress(bytes32 _clientId) public view returns (address clientDepositAddress){
return depositAddresses[_clientId];
}
/** @dev Gets a client id linked to a deposit address
* @return depositClientId The client id
*/
function getClientIdWithDepositAddress(address _depositContract) public view returns (bytes32 depositClientId){
return depositClientIds[_depositContract];
}
/** @dev Gets a currency smart contract address
* @return currencyAddress The currency address
*/
function getCurrency(bytes32 _currencySymbol) public view returns (address currencyAddress) {
return currencyAddresses[_currencySymbol];
}
/** @dev Gets a currency symbol given it's smart contract address
* @return currencySymbol The currency symbol
*/
function getCurrencySymbol(address _currencyAddress) public view returns (bytes32 currencySymbol) {
return currencySymbols[_currencyAddress];
}
/** @dev Gets details of a currency given it's smart contract address
* @return _symbol The currency symbol
* @return _name The currency name
* @return _decimals The currency decimal places/precision
*/
function getCurrencyDetails(address _currencyAddress) public view returns (bytes32 _symbol, bytes32 _name, uint8 _decimals) {
return (CurrencyToken(_currencyAddress).symbol(), CurrencyToken(_currencyAddress).name(), CurrencyToken(_currencyAddress).decimals());
}
/** @dev Get the blockchain action Id Data for a blockchain Action id
* @param _blockchainActionId the blockchain action id
* @return bytes32 currency
* @return uint amount
* @return bytes32 accountId
* @return address to
*/
function getBlockchainActionIdData(bytes32 _blockchainActionId) public view
returns (bytes32 _currency, uint _amount, bytes32 _accountId, address _to)
{
require(actionStatus[_blockchainActionId] == true);
return (blockchainActionIdData[_blockchainActionId].currency,
blockchainActionIdData[_blockchainActionId].amount,
blockchainActionIdData[_blockchainActionId].accountId,
blockchainActionIdData[_blockchainActionId].to);
}
/** @dev Get the bool status of a blockchain Action id
* @param _blockchainActionId the blockchain action id
* @return bool actionStatus
*/
function getActionStatus(bytes32 _blockchainActionId) public view returns (bool _blockchainActionStatus) {
return actionStatus[_blockchainActionId];
}
/** @dev Gets the details of an invoice with the country code, company number and invocie number.
* @param _invoiceCountryCode The country code.
* @param _invoiceCompanyNumber The company number.
* @param _invoiceNumber The invoice number
* @return providerUserId The invoice provider user Id
* @return invoiceCompanyName the invoice company name
*/
function getInvoice(bytes2 _invoiceCountryCode, bytes32 _invoiceCompanyNumber, bytes32 _invoiceNumber)
public
view
returns (bytes32 providerUserId, bytes32 invoiceCompanyName)
{
bytes32 _providerUserId = invoices[_invoiceCountryCode][_invoiceCompanyNumber][_invoiceNumber].providerUserId;
bytes32 _invoiceCompanyName = invoices[_invoiceCountryCode][_invoiceCompanyNumber][_invoiceNumber].invoiceCompanyName;
return (_providerUserId, _invoiceCompanyName);
}
/** @dev Gets the details of an invoice provider with the country code and company number.
* @param _providerCountryCode The country code.
* @param _providerCompanyNumber The company number.
* @return isEnabled The boolean value true/false indicating whether invoice provider is enabled or not
* @return providerId The invoice provider user Id
* @return companyName the invoice company name
*/
function getProviderByCountryCodeCompanyNumber(bytes2 _providerCountryCode, bytes32 _providerCompanyNumber)
public
view
returns (bytes32 providerId, bytes32 companyName)
{
bytes32 providerUserId = providerData[_providerCountryCode][_providerCompanyNumber];
return (providerUserId,
providerCompanyData[providerUserId].companyName);
}
/** @dev Gets the details of an invoice provider with the providers user Id.
* @param _providerUserId The provider user Id.
* @return countryCode The invoice provider country code
* @return companyName the invoice company name
*/
function getProviderByUserId(bytes32 _providerUserId) public view
returns (bytes2 countryCode, bytes32 companyName, bytes32 companyNumber)
{
return (providerCompanyData[_providerUserId].countryCode,
providerCompanyData[_providerUserId].companyName,
providerCompanyData[_providerUserId].companyNumber);
}
/** @dev Gets the version number for the current contract instance
* @return _version The version number
*/
function getVersion() public view returns (uint256 _version) {
return version;
}
}
// File: contracts/Populous.sol
/**
This is the core module of the system. Currently it holds the code of
the Bank and crowdsale modules to avoid external calls and higher gas costs.
It might be a good idea in the future to split the code, separate Bank
and crowdsale modules into external files and have the core interact with them
with addresses and interfaces.
*/
/// @title Populous contract
contract Populous is withAccessManager {
// EVENTS
// Bank events
event EventUSDCToUSDp(bytes32 _blockchainActionId, bytes32 _clientId, uint amount);
event EventUSDpToUSDC(bytes32 _blockchainActionId, bytes32 _clientId, uint amount);
event EventDepositAddressUpgrade(bytes32 blockchainActionId, address oldDepositContract, address newDepositContract, bytes32 clientId, uint256 version);
event EventWithdrawPPT(bytes32 blockchainActionId, bytes32 accountId, address depositContract, address to, uint amount);
event EventWithdrawPoken(bytes32 _blockchainActionId, bytes32 accountId, bytes32 currency, uint amount);
event EventNewDepositContract(bytes32 blockchainActionId, bytes32 clientId, address depositContractAddress, uint256 version);
event EventWithdrawXAUp(bytes32 _blockchainActionId, address erc1155Token, uint amount, uint token_id, bytes32 accountId, uint pptFee);
// FIELDS
struct tokens {
address _token;
uint256 _precision;
}
mapping(bytes8 => tokens) public tokenDetails;
// NON-CONSTANT METHODS
// Constructor method called when contract instance is
// deployed with 'withAccessManager' modifier.
function Populous(address _accessManager) public withAccessManager(_accessManager) {
/*ropsten
//pxt
tokenDetails[0x505854]._token = 0xD8A7C588f8DC19f49dAFd8ecf08eec58e64d4cC9;
tokenDetails[0x505854]._precision = 8;
//usdc
tokenDetails[0x55534443]._token = 0xF930f2C7Bc02F89D05468112520553FFc6D24801;
tokenDetails[0x55534443]._precision = 6;
//tusd
tokenDetails[0x54555344]._token = 0x78e7BEE398D66660bDF820DbDB415A33d011cD48;
tokenDetails[0x54555344]._precision = 18;
//ppt
tokenDetails[0x505054]._token = 0x0ff72e24AF7c09A647865820D4477F98fcB72a2c;
tokenDetails[0x505054]._precision = 8;
//xau
tokenDetails[0x584155]._token = 0x9b935E3779098bC5E1ffc073CaF916F1E92A6145;
tokenDetails[0x584155]._precision = 0;
//usdp
tokenDetails[0x55534470]._token = 0xf4b1533b6F45fAC936fA508F7e5db6d4BbC4c8bd;
tokenDetails[0x55534470]._precision = 6;
*/
/*livenet*/
//pxt
tokenDetails[0x505854]._token = 0xc14830E53aA344E8c14603A91229A0b925b0B262;
tokenDetails[0x505854]._precision = 8;
//usdc
tokenDetails[0x55534443]._token = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
tokenDetails[0x55534443]._precision = 6;
//tusd
tokenDetails[0x54555344]._token = 0x8dd5fbCe2F6a956C3022bA3663759011Dd51e73E;
tokenDetails[0x54555344]._precision = 18;
//ppt
tokenDetails[0x505054]._token = 0xd4fa1460F537bb9085d22C7bcCB5DD450Ef28e3a;
tokenDetails[0x505054]._precision = 8;
//xau
tokenDetails[0x584155]._token = 0x73a3b7DFFE9af119621f8467D8609771AB4BC33f;
tokenDetails[0x584155]._precision = 0;
//usdp
tokenDetails[0x55534470]._token = 0xBaB5D0f110Be6f4a5b70a2FA22eD17324bFF6576;
tokenDetails[0x55534470]._precision = 6;
}
/**
BANK MODULE
*/
// NON-CONSTANT METHODS
function usdcToUsdp(
address _dataManager, bytes32 _blockchainActionId,
bytes32 _clientId, uint amount)
public
onlyServer
{
// client deposit smart contract address
address _depositAddress = DataManager(_dataManager).getDepositAddress(_clientId);
require(_dataManager != 0x0 && _depositAddress != 0x0 && amount > 0);
//transfer usdc from deposit contract to server/admin
require(DepositContract(_depositAddress).transfer(tokenDetails[0x55534443]._token, msg.sender, amount) == true);
// mint USDp into depositAddress with amount
require(CurrencyToken(tokenDetails[0x55534470]._token).mint(amount, _depositAddress) == true);
//set action data
require(DataManager(_dataManager).setBlockchainActionData(_blockchainActionId, 0x55534470, amount, _clientId, _depositAddress, 0) == true);
//event
emit EventUSDCToUSDp(_blockchainActionId, _clientId, amount);
}
function usdpToUsdc(
address _dataManager, bytes32 _blockchainActionId,
bytes32 _clientId, uint amount)
public
onlyServer
{
// client deposit smart contract address
address _depositAddress = DataManager(_dataManager).getDepositAddress(_clientId);
require(_dataManager != 0x0 && _depositAddress != 0x0 && amount > 0);
//destroyFrom depositAddress USDp amount
require(CurrencyToken(tokenDetails[0x55534470]._token).destroyTokensFrom(amount, _depositAddress) == true);
//transferFrom USDC from server to depositAddress
require(CurrencyToken(tokenDetails[0x55534443]._token).transferFrom(msg.sender, _depositAddress, amount) == true);
//set action data
require(DataManager(_dataManager).setBlockchainActionData(_blockchainActionId, 0x55534470, amount, _clientId, _depositAddress, 0) == true);
//event
emit EventUSDpToUSDC(_blockchainActionId, _clientId, amount);
}
// Creates a new 'depositAddress' gotten from deploying a deposit contract linked to a client ID
function createAddress(address _dataManager, bytes32 _blockchainActionId, bytes32 clientId)
public
onlyServer
{
require(_dataManager != 0x0);
DepositContract newDepositContract;
DepositContract dc;
if (DataManager(_dataManager).getDepositAddress(clientId) != 0x0) {
dc = DepositContract(DataManager(_dataManager).getDepositAddress(clientId));
newDepositContract = new DepositContract(clientId, AM);
require(!dc.call(bytes4(keccak256("getVersion()"))));
// only checking version 1 now to upgrade to version 2
address PXT = tokenDetails[0x505854]._token;
address PPT = tokenDetails[0x505054]._token;
if(dc.balanceOf(PXT) > 0){
require(dc.transfer(PXT, newDepositContract, dc.balanceOf(PXT)) == true);
}
if(dc.balanceOf(PPT) > 0) {
require(dc.transfer(PPT, newDepositContract, dc.balanceOf(PPT)) == true);
}
require(DataManager(_dataManager)._setDepositAddress(_blockchainActionId, clientId, newDepositContract) == true);
EventDepositAddressUpgrade(_blockchainActionId, address(dc), DataManager(_dataManager).getDepositAddress(clientId), clientId, newDepositContract.getVersion());
} else {
newDepositContract = new DepositContract(clientId, AM);
require(DataManager(_dataManager).setDepositAddress(_blockchainActionId, newDepositContract, clientId) == true);
require(DataManager(_dataManager).setBlockchainActionData(_blockchainActionId, 0x0, 0, clientId, DataManager(_dataManager).getDepositAddress(clientId), 0) == true);
EventNewDepositContract(_blockchainActionId, clientId, DataManager(_dataManager).getDepositAddress(clientId), newDepositContract.getVersion());
}
}
/* /// Ether to XAUp exchange between deposit contract and Populous.sol
function exchangeXAUP(
address _dataManager, bytes32 _blockchainActionId,
address erc20_tokenAddress, uint erc20_amount, uint xaup_amount,
uint _tokenId, bytes32 _clientId, address adminExternalWallet)
public
onlyServer
{
ERC1155 xa = ERC1155(tokenDetails[0x584155]._token);
// client deposit smart contract address
address _depositAddress = DataManager(_dataManager).getDepositAddress(_clientId);
require(
// check dataManager contract is valid
_dataManager != 0x0 &&
// check deposit address of client
_depositAddress != 0x0 &&
// check xaup token address
// tokenDetails[0x584155]._token != 0x0 &&
erc20_tokenAddress != 0x0 &&
// check action id is unused
DataManager(_dataManager).getActionStatus(_blockchainActionId) == false &&
// deposit contract version >= 2
DepositContract(_depositAddress).getVersion() >= 2 &&
// populous server xaup balance
xa.balanceOf(_tokenId, msg.sender) >= xaup_amount
);
// transfer erc20 token balance from clients deposit contract to server/admin
require(DepositContract(_depositAddress).transfer(erc20_tokenAddress, adminExternalWallet, erc20_amount) == true);
// transfer xaup tokens to clients deposit address from populous server allowance
xa.safeTransferFrom(msg.sender, _depositAddress, _tokenId, xaup_amount, "");
// set action status in dataManager
require(DataManager(_dataManager).setBlockchainActionData(_blockchainActionId, 0x0, erc20_amount, _clientId, _depositAddress, 0) == true);
// emit event
EventExchangeXAUp(_blockchainActionId, erc20_tokenAddress, erc20_amount, xaup_amount, _tokenId, _clientId, _depositAddress);
} */
/** dev Import an amount of pokens of a particular currency from an ethereum wallet/address to bank
* @param _blockchainActionId the blockchain action id
* @param accountId the account id of the client
* @param from the blockchain address to import pokens from
* @param currency the poken currency
*/
function withdrawPoken(
address _dataManager, bytes32 _blockchainActionId,
bytes32 currency, uint256 amount, uint256 amountUSD,
address from, address to, bytes32 accountId,
uint256 inCollateral,
uint256 pptFee, address adminExternalWallet)
public
onlyServer
{
require(_dataManager != 0x0);
//DataManager dm = DataManager(_dataManager);
require(DataManager(_dataManager).getActionStatus(_blockchainActionId) == false && DataManager(_dataManager).getDepositAddress(accountId) != 0x0);
require(adminExternalWallet != 0x0 && pptFee > 0 && amount > 0);
require(DataManager(_dataManager).getCurrency(currency) != 0x0);
DepositContract o = DepositContract(DataManager(_dataManager).getDepositAddress(accountId));
// check if pptbalance minus collateral held is more than pptFee then transfer pptFee from users ppt deposit to adminWallet
require(SafeMath.safeSub(o.balanceOf(tokenDetails[0x505054]._token), inCollateral) >= pptFee);
require(o.transfer(tokenDetails[0x505054]._token, adminExternalWallet, pptFee) == true);
// WITHDRAW PART / DEBIT
if(amount > CurrencyToken(DataManager(_dataManager).getCurrency(currency)).balanceOf(from)) {
// destroying total balance as user has less than pokens they want to withdraw
require(CurrencyToken(DataManager(_dataManager).getCurrency(currency)).destroyTokensFrom(CurrencyToken(DataManager(_dataManager).getCurrency(currency)).balanceOf(from), from) == true);
//remaining ledger balance of deposit address is 0
} else {
// destroy amount from balance as user has more than pokens they want to withdraw
require(CurrencyToken(DataManager(_dataManager).getCurrency(currency)).destroyTokensFrom(amount, from) == true);
//left over balance is deposit address balance.
}
// TRANSFER PART / CREDIT
// approve currency amount for populous for the next require to pass
if(amountUSD > 0) //give the user USDC
{
CurrencyToken(tokenDetails[0x55534443]._token).transferFrom(msg.sender, to, amountUSD);
}else { //give the user GBP / poken currency
CurrencyToken(DataManager(_dataManager).getCurrency(currency)).transferFrom(msg.sender, to, amount);
}
require(DataManager(_dataManager).setBlockchainActionData(_blockchainActionId, currency, amount, accountId, to, pptFee) == true);
EventWithdrawPoken(_blockchainActionId, accountId, currency, amount);
}
/** @dev Withdraw an amount of PPT Populous tokens to a blockchain address
* @param _blockchainActionId the blockchain action id
* @param pptAddress the address of the PPT smart contract
* @param accountId the account id of the client
* @param pptFee the amount of fees to pay in PPT tokens
* @param adminExternalWallet the platform admin wallet address to pay the fees to
* @param to the blockchain address to withdraw and transfer the pokens to
* @param inCollateral the amount of pokens withheld by the platform
*/
function withdrawERC20(
address _dataManager, bytes32 _blockchainActionId,
address pptAddress, bytes32 accountId,
address to, uint256 amount, uint256 inCollateral,
uint256 pptFee, address adminExternalWallet)
public
onlyServer
{
require(_dataManager != 0x0);
require(DataManager(_dataManager).getActionStatus(_blockchainActionId) == false && DataManager(_dataManager).getDepositAddress(accountId) != 0x0);
require(adminExternalWallet != 0x0 && pptFee >= 0 && amount > 0);
address depositContract = DataManager(_dataManager).getDepositAddress(accountId);
if(pptAddress == tokenDetails[0x505054]._token) {
uint pptBalance = SafeMath.safeSub(DepositContract(depositContract).balanceOf(tokenDetails[0x505054]._token), inCollateral);
require(pptBalance >= SafeMath.safeAdd(amount, pptFee));
} else {
uint erc20Balance = DepositContract(depositContract).balanceOf(pptAddress);
require(erc20Balance >= amount);
}
require(DepositContract(depositContract).transfer(tokenDetails[0x505054]._token, adminExternalWallet, pptFee) == true);
require(DepositContract(depositContract).transfer(pptAddress, to, amount) == true);
bytes32 tokenSymbol = iERC20Token(pptAddress).symbol();
require(DataManager(_dataManager).setBlockchainActionData(_blockchainActionId, tokenSymbol, amount, accountId, to, pptFee) == true);
EventWithdrawPPT(_blockchainActionId, accountId, DataManager(_dataManager).getDepositAddress(accountId), to, amount);
}
// erc1155 withdraw function from deposit contract
/* function withdrawERC1155(
address _dataManager, bytes32 _blockchainActionId,
address _to, uint256 _id, uint256 _value,
bytes32 accountId, uint256 pptFee,
address adminExternalWallet)
public
onlyServer
{
require(DataManager(_dataManager).getActionStatus(_blockchainActionId) == false && DataManager(_dataManager).getDepositAddress(accountId) != 0x0);
require(adminExternalWallet != 0x0 && pptFee > 0 && _value > 0);
DepositContract o = DepositContract(DataManager(_dataManager).getDepositAddress(accountId));
require(o.transfer(tokenDetails[0x505054]._token, adminExternalWallet, pptFee) == true);
// transfer xaup tokens to address from deposit contract
require(o.transferERC1155(tokenDetails[0x584155]._token, _to, _id, _value) == true);
// set action status in dataManager
require(DataManager(_dataManager).setBlockchainActionData(_blockchainActionId, 0x584155, _value, accountId, _to, pptFee) == true);
// emit event
EventWithdrawXAUp(_blockchainActionId, tokenDetails[0x584155]._token, _value, _id, accountId, pptFee);
} */
} | Checks a given address to determine whether it is the server. sender The address to be checked. return bool returns true or false is the address corresponds to the server or not./ | function isServer(address sender) public view returns (bool) {
return sender == server;
}
| 5,475,731 |
pragma solidity ^0.4.13;
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 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;
}
}
contract ERC23ContractInterface {
function tokenFallback(address _from, uint256 _value, bytes _data) external;
}
contract ERC23Contract is ERC23ContractInterface {
/**
* @dev Reject all ERC23 compatible tokens
* param _from address that is transferring the tokens
* param _value amount of specified token
* param _data bytes data passed from the caller
*/
function tokenFallback(address /*_from*/, uint256 /*_value*/, bytes /*_data*/) external {
revert();
}
}
contract EthMatch is Ownable, ERC23Contract {
using SafeMath for uint256;
uint256 public constant MASTERY_THRESHOLD = 10 finney; // new master allowed if balance falls below this (10 finney == .01 ETH)
uint256 public constant PAYOUT_PCT = 95; // % to winner (rest to creator)
uint256 public startTime; // start timestamp when matches may begin
address public master; // current Matchmaster
uint256 public gasReq; // require same gas every time in maker()
event MatchmakerPrevails(address indexed matchmaster, address indexed matchmaker, uint256 sent, uint256 actual, uint256 winnings);
event MatchmasterPrevails(address indexed matchmaster, address indexed matchmaker, uint256 sent, uint256 actual, uint256 winnings);
event MatchmasterTakeover(address indexed matchmasterPrev, address indexed matchmasterNew, uint256 balanceNew);
// can be funded at init if desired
function EthMatch(uint256 _startTime) public payable {
require(_startTime >= now);
startTime = _startTime;
master = msg.sender; // initial
gasReq = 42000;
}
// ensure proper state
modifier isValid(address _addr) {
require(_addr != 0x0);
require(!Lib.isContract(_addr)); // ban contracts
require(now >= startTime);
_;
}
// fallback function
// make a match
function () public payable {
maker(msg.sender);
}
// make a match (and specify payout address)
function maker(address _addr) isValid(_addr) public payable {
require(msg.gas >= gasReq); // require same gas every time (overages auto-returned)
uint256 weiPaid = msg.value;
require(weiPaid > 0);
uint256 balPrev = this.balance.sub(weiPaid);
if (balPrev == weiPaid) {
// maker wins
uint256 winnings = weiPaid.add(balPrev.div(2));
pay(_addr, winnings);
MatchmakerPrevails(master, _addr, weiPaid, balPrev, winnings);
} else {
// master wins
pay(master, weiPaid);
MatchmasterPrevails(master, _addr, weiPaid, balPrev, weiPaid);
}
}
// send proceeds
function pay(address _addr, uint256 _amount) internal {
if (_amount == 0) {
return; // amount actually could be 0, e.g. initial funding or if balance is totally drained
}
uint256 payout = _amount.mul(PAYOUT_PCT).div(100);
_addr.transfer(payout);
uint256 remainder = _amount.sub(payout);
owner.transfer(remainder);
}
// become the new master
function mastery() public payable {
mastery(msg.sender);
}
// become the new master (and specify payout address)
function mastery(address _addr) isValid(_addr) public payable {
uint256 weiPaid = msg.value;
require(weiPaid >= MASTERY_THRESHOLD);
uint256 balPrev = this.balance.sub(weiPaid);
require(balPrev < MASTERY_THRESHOLD);
pay(master, balPrev);
MatchmasterTakeover(master, _addr, weiPaid); // called before new master set
master = _addr; // must be set after event logged
}
// in case it ever needs to be updated for future Ethereum releases, etc
function setGasReq(uint256 _gasReq) onlyOwner external {
gasReq = _gasReq;
}
// initial funding
function fund() onlyOwner external payable {
require(now < startTime); // otherwise can just call mastery()
// it is possible that funds can be forced in via selfdestruct, so
// just ensure balance is enough, at least after receiving this call (msg.value)
require(this.balance >= MASTERY_THRESHOLD);
}
// explicit balance getter
function getBalance() external constant returns (uint256) {
return this.balance;
}
}
library Lib {
// whether given address is a contract or not based on bytecode
function isContract(address addr) internal constant returns (bool) {
uint size;
assembly {
size := extcodesize(addr)
}
return (size > 1); // testing returned size "1" for non-contract accounts, so we're using that.
}
} | in case it ever needs to be updated for future Ethereum releases, etc | function setGasReq(uint256 _gasReq) onlyOwner external {
gasReq = _gasReq;
}
| 5,480,732 |
./partial_match/1/0x0D79db7d7B42Ec75E1455590D27Fc4B85E5B8c64/sources/AngryPepe.sol | trading disable till launchif any account belongs to isExcludedFromFee account then remove the fee | function _transfer(address from, address to, uint256 amount) private {
require(from != address(0), "$: transfer from the zero address");
require(to != address(0), "$: transfer to the zero address");
require(amount > 0, "$: Amount must be greater than zero");
require(!isBot[from], "Bot detected");
if (!isExcludedFromMaxTxn[from] && !isExcludedFromMaxTxn[to]) {
require(amount <= maxTxnLimit, ": max txn limit exceeds");
if (!trading) {
require(
dexPair != from && dexPair != to,
": trading is disable"
);
}
}
if (!isExcludedFromMaxHolding[to]) {
require(
balanceOf(to).add(amount) <= maxHoldLimit,
": max hold limit exceeds"
);
}
if (isExcludedFromFee[from] || isExcludedFromFee[to] || !feesStatus) {
takeFee = false;
}
}
| 4,103,227 |
./partial_match/1/0x6B0B234fB2f380309D47A7E9391E29E9a179395a/sources/src/v0.8/llo-feeds/dev/FeeManager.sol | @inheritdoc IFeeManagermake sure the discount is not greater than the total discount that can be appliedmake sure the token is either LINK or native | function updateSubscriberDiscount(
address subscriber,
bytes32 feedId,
address token,
uint64 discount
) external onlyOwner {
if (discount > PERCENTAGE_SCALAR) revert InvalidDiscount();
if (token != i_linkAddress && token != i_nativeAddress) revert InvalidAddress();
s_subscriberDiscounts[subscriber][feedId][token] = discount;
emit SubscriberDiscountUpdated(subscriber, feedId, token, discount);
}
| 3,963,541 |
pragma solidity 0.4.25;
/*TODO
reemplazar los requires repetidos por una sola funcion modifier
agregar estructuras de fecha para controlar el periodo de registro e implementarlo con la estructura bid
validar que el numero de id no sea 0, y que sea unico, al agregar bids
*/
contract silat
{
//Estructura que almacena la informacion de cada competidor (bidder)
struct Bidder
{
uint256 id_bidder;
string name;
address bidder_address;
uint256 score;
}
enum StatusType {Open_Registration, JuryEvaluation, JuryConfirmation, Bid_Execution, Bid_End}
//Estructura que almacena la informacion de la licitacion (bid)
struct Bid
{
uint256 id_bid;
uint256 budget;
uint256 no_partida;
string details;
StatusType status;
uint256 id_winner;
mapping(uint256 => Bidder) bidders;
uint256 bidders_count;
}
uint256 public bid_count;//Variable que nos almacena la cantidad de bids que se han agregado al smart contract hasta ahora
address admin;
constructor() public //metodo constructor, lo que esta aqui dentro se ejecuta al depslegar el contrato
{
bid_count = 0;
admin = msg.sender;
}
mapping(uint256 => Bid) public bids; //Declaramos el arreglo de licitaciones (bids)
//Funcion publica que agrega una nueva licitacion (bid)
function addBid(uint256 _budget, string _details, uint256 _no_partida) public returns(string)
{
require(msg.sender == admin, "Error, solo los administradores pueden agregar licitaciones");
bids[bid_count].id_bid = bid_count;
bids[bid_count].budget = _budget;
bids[bid_count].details = _details;
bids[bid_count].no_partida = _no_partida;
bids[bid_count].status = StatusType.Open_Registration;
bids[bid_count].id_winner = 0;
bid_count++;
return("Licitacion agregada exitosamente");
}
//Funcion que le agrega un competidor (bidder) a una licitacion (bid) en especifico
function addBidder(uint256 _id_bid, string _name) public returns(string)
{
require(bids[_id_bid].status == StatusType.Open_Registration, "La etapa de registro ya acabo, competidor no agregado");
require(_id_bid >= 0 && _id_bid <= bid_count, "Error, id de licitacion no valido");
bids[_id_bid].bidders[bids[_id_bid].bidders_count].id_bidder = bids[_id_bid].bidders_count;
bids[_id_bid].bidders[bids[_id_bid].bidders_count].name = _name;
bids[_id_bid].bidders[bids[_id_bid].bidders_count].bidder_address = msg.sender;
bids[_id_bid].bidders_count++;
return("Competidor agregado exitosamente");
}
//cuando el proceso de registro se termina, cambia la variable de estado
function endRegistrationPeriod(uint256 _id_bid) public returns(string)
{
require(msg.sender == admin, "Solo el administrador puede terminar el periodo de registro");
require(bid_count>0, "Error, aun no existen licitaciones que modificar");
require(_id_bid >= 0 && _id_bid <= bid_count, "Error, id de licitacion no valido");
require(bids[_id_bid].status == StatusType.Open_Registration, "Error, periodo de registro yaterminado");
bids[_id_bid].status = StatusType.JuryEvaluation;
return("Periodo de registro de licitacion terminado");
}
//pide puntuacion de determinado competidor en determinada licitacion
function rateBidder (uint256 _id_bid, uint256 _id_bidder, uint256 _score) public returns(string)
{
require(_id_bid >= 0 && _id_bid <= bid_count, "Error, id de licitacion no valido");
require(_id_bidder >= 0 && _id_bidder <= bids[_id_bid].bidders_count, "Error, id de licitacion no valido");
require(_score >= 0 && _score <= 100, "Error, id de licitacion no valido");
require(bids[_id_bid].status == StatusType.JuryEvaluation, "Error, aun en periodo de registro");
bids[_id_bid].bidders[_id_bidder].score = bids[_id_bid].bidders[_id_bidder].score + _score;
return("Voto satisfactorio");
}
//calcula el ganador de determinada licitacion
function decideWinner (uint256 _id_bid) public view returns (uint256 winner)
{
require(_id_bid >= 0 && _id_bid <= bid_count, "Error, id de licitacion no valido");
require(bids[_id_bid].status == StatusType.JuryEvaluation, "Error, aun en periodo de registro");
uint256 highestScore;
for(uint256 i; i < bids[_id_bid].bidders_count; i++)
{
if(bids[_id_bid].bidders[i].score > highestScore)
{
highestScore = bids[_id_bid].bidders[i].score;
winner = bids[_id_bid].bidders[i].id_bidder;
}
}
bids[_id_bid].id_winner = winner;
}
} | calcula el ganador de determinada licitacion | function decideWinner (uint256 _id_bid) public view returns (uint256 winner)
{
require(_id_bid >= 0 && _id_bid <= bid_count, "Error, id de licitacion no valido");
require(bids[_id_bid].status == StatusType.JuryEvaluation, "Error, aun en periodo de registro");
uint256 highestScore;
for(uint256 i; i < bids[_id_bid].bidders_count; i++)
{
if(bids[_id_bid].bidders[i].score > highestScore)
{
highestScore = bids[_id_bid].bidders[i].score;
winner = bids[_id_bid].bidders[i].id_bidder;
}
}
bids[_id_bid].id_winner = winner;
}
| 12,864,799 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import "../access/Controlled.sol";
import "./AccountBase.sol";
/**
* @title Account
*
* @author Stanisław Głogowski <[email protected]>
*/
contract Account is Controlled, AccountBase {
address public implementation;
/**
* @dev Public constructor
* @param registry_ account registry address
* @param implementation_ account implementation address
*/
constructor(
address registry_,
address implementation_
)
public
Controlled()
{
registry = registry_;
implementation = implementation_;
}
// external functions
/**
* @notice Payable receive
*/
receive()
external
payable
{
//
}
/**
* @notice Fallback
*/
// solhint-disable-next-line payable-fallback
fallback()
external
{
if (msg.data.length != 0) {
address implementation_ = implementation;
// solhint-disable-next-line no-inline-assembly
assembly {
let calldedatasize := calldatasize()
calldatacopy(0, 0, calldedatasize)
let result := delegatecall(gas(), implementation_, 0, calldedatasize, 0, 0)
let returneddatasize := returndatasize()
returndatacopy(0, 0, returneddatasize)
switch result
case 0 { revert(0, returneddatasize) }
default { return(0, returneddatasize) }
}
}
}
/**
* @notice Sets implementation
* @param implementation_ implementation address
*/
function setImplementation(
address implementation_
)
external
onlyController
{
implementation = implementation_;
}
/**
* @notice Executes transaction
* @param to to address
* @param value value
* @param data data
* @return transaction result
*/
function executeTransaction(
address to,
uint256 value,
bytes calldata data
)
external
onlyController
returns (bytes memory)
{
bytes memory result;
bool succeeded;
// solhint-disable-next-line avoid-call-value, avoid-low-level-calls
(succeeded, result) = payable(to).call{value: value}(data);
require(
succeeded,
"Account: transaction reverted"
);
return result;
}
}
| Sets implementation implementation_ implementation address/ | function setImplementation(
address implementation_
)
external
onlyController
{
implementation = implementation_;
}
| 1,845,965 |
/**
* @title ERC20Pausable
* @author Team 3301 <[email protected]>
* @dev Overloading ERC20 functions to ensure that the contract has not been paused.
*/
pragma solidity 0.5.12;
import "./ERC20Overload/ERC20.sol";
import "../Pausable.sol";
contract ERC20Pausable is ERC20, Pausable {
/**
* @dev Overload transfer function to ensure contract has not been paused.
* @param to address that recieves the funds.
* @param value amount of funds.
*/
function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
return super.transfer(to, value);
}
/**
* @dev Overload approve function to ensure contract has not been paused.
* @param spender address that can spend the funds.
* @param value amount of funds.
*/
function approve(address spender, uint256 value) public whenNotPaused returns (bool) {
return super.approve(spender, value);
}
/**
* @dev Overload transferFrom function to ensure contract has not been paused.
* @param from address that funds will be transferred from.
* @param to address that funds will be transferred to.
* @param value amount of funds.
*/
function transferFrom(
address from,
address to,
uint256 value
) public whenNotPaused returns (bool) {
return super.transferFrom(from, to, value);
}
/**
* @dev Overload increaseAllowance function to ensure contract has not been paused.
* @param spender address that will be allowed to transfer funds.
* @param addedValue amount of funds to added to current allowance.
*/
function increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) {
return super.increaseAllowance(spender, addedValue);
}
/**
* @dev Overload decreaseAllowance function to ensure contract has not been paused.
* @param spender address that will be allowed to transfer funds.
* @param subtractedValue amount of funds to be deducted to current allowance.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) {
return super.decreaseAllowance(spender, subtractedValue);
}
/**
* @dev Overload _burn function to ensure contract has not been paused.
* @param account address that funds will be burned from.
* @param value amount of funds that will be burned.
*/
function _burn(address account, uint256 value) internal whenNotPaused {
super._burn(account, value);
}
/**
* @dev Overload _burnFrom function to ensure contract has not been paused.
* @param account address that funds will be burned from allowance.
* @param amount amount of funds that will be burned.
*/
function _burnFrom(address account, uint256 amount) internal whenNotPaused {
super._burnFrom(account, amount);
}
/**
* @dev Overload _mint function to ensure contract has not been paused.
* @param account address that funds will be minted to.
* @param amount amount of funds that will be minted.
*/
function _mint(address account, uint256 amount) internal whenNotPaused {
super._mint(account, amount);
}
}
| Overload decreaseAllowance function to ensure contract has not been paused. spender address that will be allowed to transfer funds. subtractedValue amount of funds to be deducted to current allowance./ | function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) {
return super.decreaseAllowance(spender, subtractedValue);
}
| 911,467 |
./full_match/4/0xBa6B9E6Cf71f0F605137E8c817680411D5EDE48a/sources/browser/BEDMoB.sol | IoTDataProduct storage _product = IoTDataProducts[_id]; _product.IoTDataProductHash[_thirdParty] = _fileHash; | function sendIoTdataProduct(uint _id, string memory _fileHash, address _thirdParty) public {
IoTDataProducts[_id].IoTDataProductHash[_thirdParty] = _fileHash;
emit IoTDataProductSend(_id,msg.sender,_thirdParty);
}
| 12,405,068 |
./full_match/1/0x78d93e98273863ceb7843b42065E4f6be46c3a7f/sources/contracts/PiGamificationStaking.sol | 60480000 = 7246060 | function getRewardToken1WPY() external view returns (uint256) {
if (block.timestamp > periodFinish) return 0;
uint256 rewardForWeek = rewardRate.mul(604800);
if (_totalSupply <= 1e18) return rewardForWeek.div(1e10);
}
| 16,576,806 |
./partial_match/1/0x99B52db75A2C37efA07C3867eC5811B9D878D4e3/sources/VaultStaking.sol | View returns list (in days) of all valid staking periods | function getValidStakingDurations() external view returns (uint256[] memory){
return stakingPeriodsInDays.values();
}
| 3,735,001 |
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../loggers/DefisaverLogger.sol";
import "../../utils/Discount.sol";
import "../../interfaces/Spotter.sol";
import "../../interfaces/Jug.sol";
import "../../interfaces/DaiJoin.sol";
import "../../interfaces/Join.sol";
import "./MCDSaverProxyHelper.sol";
import "../../utils/BotRegistry.sol";
import "../../exchangeV3/DFSExchangeCore.sol";
/// @title Implements Boost and Repay for MCD CDPs
contract MCDSaverProxy is DFSExchangeCore, MCDSaverProxyHelper {
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000;
address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
Manager public constant manager = Manager(MANAGER_ADDRESS);
Vat public constant vat = Vat(VAT_ADDRESS);
DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS);
Spotter public constant spotter = Spotter(SPOTTER_ADDRESS);
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Repay - draws collateral, converts to Dai and repays the debt
/// @dev Must be called by the DSProxy contract that owns the CDP
function repay(
ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr
) public payable {
address user = getOwner(manager, _cdpId);
bytes32 ilk = manager.ilks(_cdpId);
drawCollateral(_cdpId, _joinAddr, _exchangeData.srcAmount);
_exchangeData.user = user;
_exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
(, uint daiAmount) = _sell(_exchangeData);
daiAmount -= takeFee(_gasCost, daiAmount);
paybackDebt(_cdpId, ilk, daiAmount, user);
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, user, _exchangeData.srcAmount, daiAmount));
}
/// @notice Boost - draws Dai, converts to collateral and adds to CDP
/// @dev Must be called by the DSProxy contract that owns the CDP
function boost(
ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr
) public payable {
address user = getOwner(manager, _cdpId);
bytes32 ilk = manager.ilks(_cdpId);
uint daiDrawn = drawDai(_cdpId, ilk, _exchangeData.srcAmount);
_exchangeData.user = user;
_exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
_exchangeData.srcAmount = daiDrawn - takeFee(_gasCost, daiDrawn);
(, uint swapedColl) = _sell(_exchangeData);
addCollateral(_cdpId, _joinAddr, swapedColl);
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, user, _exchangeData.srcAmount, swapedColl));
}
/// @notice Draws Dai from the CDP
/// @dev If _daiAmount is bigger than max available we'll draw max
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @param _daiAmount Amount of Dai to draw
function drawDai(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) {
uint rate = Jug(JUG_ADDRESS).drip(_ilk);
uint daiVatBalance = vat.dai(manager.urns(_cdpId));
uint maxAmount = getMaxDebt(_cdpId, _ilk);
if (_daiAmount >= maxAmount) {
_daiAmount = sub(maxAmount, 1);
}
manager.frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance));
manager.move(_cdpId, address(this), toRad(_daiAmount));
if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) {
vat.hope(DAI_JOIN_ADDRESS);
}
DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount);
return _daiAmount;
}
/// @notice Adds collateral to the CDP
/// @param _cdpId Id of the CDP
/// @param _joinAddr Address of the join contract for the CDP collateral
/// @param _amount Amount of collateral to add
function addCollateral(uint _cdpId, address _joinAddr, uint _amount) internal {
int convertAmount = 0;
if (isEthJoinAddr(_joinAddr)) {
Join(_joinAddr).gem().deposit{value: _amount}();
convertAmount = toPositiveInt(_amount);
} else {
convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount));
}
ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, _amount);
Join(_joinAddr).join(address(this), _amount);
vat.frob(
manager.ilks(_cdpId),
manager.urns(_cdpId),
address(this),
address(this),
convertAmount,
0
);
}
/// @notice Draws collateral and returns it to DSProxy
/// @dev If _amount is bigger than max available we'll draw max
/// @param _cdpId Id of the CDP
/// @param _joinAddr Address of the join contract for the CDP collateral
/// @param _amount Amount of collateral to draw
function drawCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) {
uint frobAmount = _amount;
if (Join(_joinAddr).dec() != 18) {
frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec()));
}
manager.frob(_cdpId, -toPositiveInt(frobAmount), 0);
manager.flux(_cdpId, address(this), frobAmount);
Join(_joinAddr).exit(address(this), _amount);
if (isEthJoinAddr(_joinAddr)) {
Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth
}
return _amount;
}
/// @notice Paybacks Dai debt
/// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @param _daiAmount Amount of Dai to payback
/// @param _owner Address that owns the DSProxy that owns the CDP
function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal {
address urn = manager.urns(_cdpId);
uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk);
if (_daiAmount > wholeDebt) {
ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt));
_daiAmount = wholeDebt;
}
if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) {
ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1));
}
daiJoin.join(urn, _daiAmount);
manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk));
}
/// @notice Gets the maximum amount of collateral available to draw
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @param _joinAddr Joind address of collateral
/// @dev Substracts 10 wei to aviod rounding error later on
function getMaxCollateral(uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) {
uint price = getPrice(_ilk);
(uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk);
(, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk);
uint maxCollateral = sub(collateral, (div(mul(mat, debt), price)));
uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec()));
// take one percent due to precision issues
return normalizeMaxCollateral * 99 / 100;
}
/// @notice Gets the maximum amount of debt available to generate
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @dev Substracts 10 wei to aviod rounding error later on
function getMaxDebt(uint _cdpId, bytes32 _ilk) public virtual view returns (uint) {
uint price = getPrice(_ilk);
(, uint mat) = spotter.ilks(_ilk);
(uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk);
return sub(sub(div(mul(collateral, price), mat), debt), 10);
}
/// @notice Gets a price of the asset
/// @param _ilk Ilk of the CDP
function getPrice(bytes32 _ilk) public view returns (uint) {
(, uint mat) = spotter.ilks(_ilk);
(,,uint spot,,) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
/// @notice Gets CDP ratio
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getRatio(uint _cdpId, bytes32 _ilk) public view returns (uint) {
uint price = getPrice( _ilk);
(uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk);
if (debt == 0) return 0;
return rdiv(wmul(collateral, price), debt);
}
/// @notice Gets CDP info (collateral, debt, price, ilk)
/// @param _cdpId Id of the CDP
function getCdpDetailedInfo(uint _cdpId) public view returns (uint collateral, uint debt, uint price, bytes32 ilk) {
address urn = manager.urns(_cdpId);
ilk = manager.ilks(_cdpId);
(collateral, debt) = vat.urns(ilk, urn);
(,uint rate,,,) = vat.ilks(ilk);
debt = rmul(debt, rate);
price = getPrice(ilk);
}
function isAutomation() internal view returns(bool) {
return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin);
}
function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) {
if (_gasCost > 0) {
uint ethDaiPrice = getPrice(ETH_ILK);
uint feeAmount = rmul(_gasCost, ethDaiPrice);
uint balance = ERC20(DAI_ADDRESS).balanceOf(address(this));
if (feeAmount > _amount / 10) {
feeAmount = _amount / 10;
}
ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount);
return feeAmount;
}
return 0;
}
}
| Gets the maximum amount of collateral available to draw _cdpId Id of the CDP _ilk Ilk of the CDP _joinAddr Joind address of collateral Substracts 10 wei to aviod rounding error later on take one percent due to precision issues | function getMaxCollateral(uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) {
uint price = getPrice(_ilk);
(uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk);
(, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk);
uint maxCollateral = sub(collateral, (div(mul(mat, debt), price)));
uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec()));
return normalizeMaxCollateral * 99 / 100;
}
| 14,107,380 |
pragma solidity >=0.4.0 <0.6.0;
/*
Copyright 2017
RJ Ewing <[email protected]>
S van Heummen <[email protected]>
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/>.
*/
import "giveth-liquidpledging/contracts/LiquidPledging.sol";
import "@aragon/os/contracts/apps/AragonApp.sol";
import "@aragon/os/contracts/kernel/IKernel.sol";
import "giveth-bridge/contracts/IForeignGivethBridge.sol";
/// @title LPPCappedMilestone
/// @author RJ Ewing<[email protected]>
/// @notice The LPPCappedMilestone contract is a plugin contract for liquidPledging,
/// extending the functionality of a liquidPledging project. This contract
/// prevents withdrawals from any pledges this contract is the owner of.
/// This contract has 4 roles. The admin, a reviewer, and a recipient role.
///
/// 1. The admin can cancel the milestone, update the conditions the milestone accepts transfers
/// and send a tx as the milestone.
/// 2. The reviewer can cancel the milestone.
/// 3. The recipient role will receive the pledge's owned by this milestone.
contract LPPCappedMilestone is AragonApp {
uint constant TO_OWNER = 256;
uint constant TO_INTENDEDPROJECT = 511;
// keccack256(Kernel.APP_ADDR_NAMESPACE(), keccack256("ForeignGivethBridge"))
bytes32 constant public FOREIGN_BRIDGE_INSTANCE = 0xa46b3f7f301ac0173ef5564df485fccae3b60583ddb12c767fea607ff6971d0b;
LiquidPledging public liquidPledging;
uint64 public idProject;
address public reviewer;
address public newReviewer;
address public recipient;
address public newRecipient;
address public campaignReviewer;
address public newCampaignReviewer;
address public milestoneManager;
address public acceptedToken;
uint public maxAmount;
uint public received = 0;
bool public requestComplete;
bool public completed;
// @notice After marking complete, and after this timeout, the recipient can withdraw the money
// even if the milestone was not marked as complete.
// Must be set in seconds.
uint public reviewTimeoutSeconds;
uint public reviewTimeout = 0;
event MilestoneCompleteRequested(address indexed liquidPledging, uint64 indexed idProject);
event MilestoneCompleteRequestRejected(address indexed liquidPledging, uint64 indexed idProject);
event MilestoneCompleteRequestApproved(address indexed liquidPledging, uint64 indexed idProject);
event MilestoneChangeReviewerRequested(address indexed liquidPledging, uint64 indexed idProject, address reviewer);
event MilestoneReviewerChanged(address indexed liquidPledging, uint64 indexed idProject, address reviewer);
event MilestoneChangeCampaignReviewerRequested(address indexed liquidPledging, uint64 indexed idProject, address reviewer);
event MilestoneCampaignReviewerChanged(address indexed liquidPledging, uint64 indexed idProject, address reviewer);
event MilestoneChangeRecipientRequested(address indexed liquidPledging, uint64 indexed idProject, address recipient);
event MilestoneRecipientChanged(address indexed liquidPledging, uint64 indexed idProject, address recipient);
event PaymentCollected(address indexed liquidPledging, uint64 indexed idProject);
modifier onlyReviewer() {
require(msg.sender == reviewer);
_;
}
modifier onlyCampaignReviewer() {
require(msg.sender == campaignReviewer);
_;
}
modifier onlyManagerOrRecipient() {
require(msg.sender == milestoneManager || msg.sender == recipient);
_;
}
modifier checkReviewTimeout() {
if (!completed && reviewTimeout > 0 && now > reviewTimeout) {
completed = true;
}
require(completed);
_;
}
//== constructor
// @notice we pass in the idProject here because it was throwing stack too deep error
function initialize(
address _reviewer,
address _campaignReviewer,
address _recipient,
address _milestoneManager,
uint _reviewTimeoutSeconds,
uint _maxAmount,
address _acceptedToken,
// if these params are at the beginning, we get a stack too deep error
address _liquidPledging,
uint64 _idProject
) onlyInit external
{
require(_reviewer != 0);
require(_campaignReviewer != 0);
require(_recipient != 0);
require(_milestoneManager != 0);
require(_liquidPledging != 0);
require(_acceptedToken != 0);
initialized();
idProject = _idProject;
liquidPledging = LiquidPledging(_liquidPledging);
var ( , addr, , , , , , plugin) = liquidPledging.getPledgeAdmin(idProject);
require(addr == address(this) && plugin == address(this));
maxAmount = _maxAmount;
acceptedToken = _acceptedToken;
reviewer = _reviewer;
recipient = _recipient;
reviewTimeoutSeconds = _reviewTimeoutSeconds;
campaignReviewer = _campaignReviewer;
milestoneManager = _milestoneManager;
}
//== external
// don't allow cancel if the milestone is completed
function isCanceled() public constant returns (bool) {
return liquidPledging.isProjectCanceled(idProject);
}
// @notice Milestone manager can request to mark a milestone as completed
// When he does, the timeout is initiated. So if the reviewer doesn't
// handle the request in time, the recipient can withdraw the funds
function requestMarkAsComplete() onlyManagerOrRecipient external {
require(!isCanceled());
require(!requestComplete);
requestComplete = true;
MilestoneCompleteRequested(liquidPledging, idProject);
// start the review timeout
reviewTimeout = now + reviewTimeoutSeconds;
}
// @notice The reviewer can reject a completion request from the milestone manager
// When he does, the timeout is reset.
function rejectCompleteRequest() onlyReviewer external {
require(!isCanceled());
// reset
completed = false;
requestComplete = false;
reviewTimeout = 0;
MilestoneCompleteRequestRejected(liquidPledging, idProject);
}
// @notice The reviewer can approve a completion request from the milestone manager
// When he does, the milestone's state is set to completed and the funds can be
// withdrawn by the recipient.
function approveMilestoneCompleted() onlyReviewer external {
require(!isCanceled());
completed = true;
MilestoneCompleteRequestApproved(liquidPledging, idProject);
}
// @notice The reviewer and the milestone manager can cancel a milestone.
function cancelMilestone() external {
require(msg.sender == milestoneManager || msg.sender == reviewer);
require(!isCanceled());
liquidPledging.cancelProject(idProject);
}
// @notice The reviewer can request changing a reviewer.
function requestChangeReviewer(address _newReviewer) onlyReviewer external {
newReviewer = _newReviewer;
MilestoneChangeReviewerRequested(liquidPledging, idProject, newReviewer);
}
// @notice The new reviewer needs to accept the request from the old
// reviewer to become the new reviewer.
// @dev There's no point in adding a rejectNewReviewer because as long as
// the new reviewer doesn't accept, the old reviewer remains the reviewer.
function acceptNewReviewerRequest() external {
require(newReviewer == msg.sender);
reviewer = newReviewer;
newReviewer = 0;
MilestoneReviewerChanged(liquidPledging, idProject, reviewer);
}
// @notice The campaign reviewer can request changing a campaign reviewer.
function requestChangeCampaignReviewer(address _newCampaignReviewer) onlyCampaignReviewer external {
newCampaignReviewer = _newCampaignReviewer;
MilestoneChangeCampaignReviewerRequested(liquidPledging, idProject, newReviewer);
}
// @notice The new campaign reviewer needs to accept the request from the old
// campaign reviewer to become the new campaign reviewer.
// @dev There's no point in adding a rejectNewCampaignReviewer because as long as
// the new reviewer doesn't accept, the old reviewer remains the reviewer.
function acceptNewCampaignReviewerRequest() external {
require(newCampaignReviewer == msg.sender);
campaignReviewer = newCampaignReviewer;
newCampaignReviewer = 0;
MilestoneCampaignReviewerChanged(liquidPledging, idProject, reviewer);
}
// @notice The recipient can request changing recipient.
// @dev There's no point in adding a rejectNewRecipient because as long as
// the new recipient doesn't accept, the old recipient remains the recipient.
function requestChangeRecipient(address _newRecipient) onlyReviewer external {
newRecipient = _newRecipient;
MilestoneChangeRecipientRequested(liquidPledging, idProject, newRecipient);
}
// @notice The new recipient needs to accept the request from the old
// recipient to become the new recipient.
function acceptNewRecipient() external {
require(newRecipient == msg.sender);
recipient = newRecipient;
newRecipient = 0;
MilestoneRecipientChanged(liquidPledging, idProject, recipient);
}
/// @dev this is called by liquidPledging before every transfer to and from
/// a pledgeAdmin that has this contract as its plugin
/// @dev see ILiquidPledgingPlugin interface for details about context param
function beforeTransfer(
uint64 pledgeManager,
uint64 pledgeFrom,
uint64 pledgeTo,
uint64 context,
address token,
uint amount
) external returns (uint maxAllowed)
{
require(msg.sender == address(liquidPledging));
// only accept that token
if (token != acceptedToken) {
return 0;
}
var (, , , fromIntendedProject, , , ,) = liquidPledging.getPledge(pledgeFrom);
var (, toOwner, , , , , ,toPledgeState) = liquidPledging.getPledge(pledgeTo);
// if m is the intendedProject, make sure m is still accepting funds (not completed or canceled)
if (context == TO_INTENDEDPROJECT) {
// don't need to check if canceled b/c lp does this
if (completed) {
return 0;
}
// if the pledge is being transferred to m and is in the Pledged state, make
// sure m is still accepting funds (not completed or canceled)
} else if (context == TO_OWNER &&
(fromIntendedProject != toOwner &&
toPledgeState == LiquidPledgingStorage.PledgeState.Pledged)) {
//TODO what if milestone isn't initialized? should we throw?
// this can happen if someone adds a project through lp with this contracts address as the plugin
// we can require(maxAmount > 0);
// don't need to check if canceled b/c lp does this
if (completed) {
return 0;
}
}
return amount;
}
/// @dev this is called by liquidPledging after every transfer to and from
/// a pledgeAdmin that has this contract as its plugin
/// @dev see ILiquidPledgingPlugin interface for details about context param
function afterTransfer(
uint64 pledgeManager,
uint64 pledgeFrom,
uint64 pledgeTo,
uint64 context,
address token,
uint amount
) external
{
require(msg.sender == address(liquidPledging));
var (, fromOwner, , , , , ,) = liquidPledging.getPledge(pledgeFrom);
var (, toOwner, , , , , , ) = liquidPledging.getPledge(pledgeTo);
if (context == TO_OWNER) {
// If fromOwner != toOwner, the means that a pledge is being committed to
// milestone. We will accept any amount up to m.maxAmount, and return
// the rest
if (fromOwner != toOwner) {
uint returnFunds = 0;
uint newBalance = received + amount;
// milestone is no longer accepting new funds
if (completed) {
returnFunds = amount;
} else if (newBalance > maxAmount) {
returnFunds = newBalance - maxAmount;
received = maxAmount;
} else {
received = received + amount;
}
// send any exceeding funds back
if (returnFunds > 0) {
liquidPledging.cancelPledge(pledgeTo, returnFunds);
}
}
}
}
// @notice Allows the recipient or milestoneManager to initiate withdraw from
// the vault to this milestone. If the vault is autoPay, this will disburse the
// payment to the recipient
// Checks if reviewTimeout has passed, if so, sets completed to yes
function mWithdraw(uint[] pledgesAmounts) onlyManagerOrRecipient checkReviewTimeout external {
liquidPledging.mWithdraw(pledgesAmounts);
_disburse();
}
// @notice Allows the recipient or milestoneManager to initiate withdraw of a single pledge, from
// the vault to this milestone. If the vault is autoPay, this will disburse the payment to the
// recipient
// Checks if reviewTimeout has passed, if so, sets completed to yes
function withdraw(uint64 idPledge, uint amount) onlyManagerOrRecipient checkReviewTimeout external {
liquidPledging.withdraw(idPledge, amount);
_disburse();
}
// @notice Allows the recipient or milestoneManager to disburse funds to the recipient
function disburse() onlyManagerOrRecipient checkReviewTimeout external {
_disburse();
}
/**
* @dev By default, AragonApp will allow anyone to call transferToVault
* We need to blacklist the `acceptedToken`
* @param token Token address that would be recovered
* @return bool whether the app allows the recovery
*/
function allowRecoverability(address token) public view returns (bool) {
return token != acceptedToken;
}
function _disburse() internal {
IKernel kernel = liquidPledging.kernel();
IForeignGivethBridge bridge = IForeignGivethBridge(kernel.getApp(FOREIGN_BRIDGE_INSTANCE));
ERC20 milestoneToken = ERC20(acceptedToken);
uint amount = milestoneToken.balanceOf(this);
if (amount > 0) {
bridge.withdraw(recipient, acceptedToken, amount);
PaymentCollected(liquidPledging, idProject);
}
}
}
| we pass in the idProject here because it was throwing stack too deep error if these params are at the beginning, we get a stack too deep error | function initialize(
address _reviewer,
address _campaignReviewer,
address _recipient,
address _milestoneManager,
uint _reviewTimeoutSeconds,
uint _maxAmount,
address _acceptedToken,
address _liquidPledging,
uint64 _idProject
) onlyInit external
{
require(_reviewer != 0);
require(_campaignReviewer != 0);
require(_recipient != 0);
require(_milestoneManager != 0);
require(_liquidPledging != 0);
require(_acceptedToken != 0);
initialized();
idProject = _idProject;
liquidPledging = LiquidPledging(_liquidPledging);
var ( , addr, , , , , , plugin) = liquidPledging.getPledgeAdmin(idProject);
require(addr == address(this) && plugin == address(this));
maxAmount = _maxAmount;
acceptedToken = _acceptedToken;
reviewer = _reviewer;
recipient = _recipient;
reviewTimeoutSeconds = _reviewTimeoutSeconds;
campaignReviewer = _campaignReviewer;
milestoneManager = _milestoneManager;
}
| 15,871,602 |
./full_match/42161/0x5C4bDf584C9Ae3bc75D76163ab6AE0fa7126FFb6/sources/project_/contracts/current/Libraries/BetsManager.sol | Remove the bet from user pending bets list, only internal use | function _removeUserPendingBet(uint256 betIndex) private {
uint256 _indexDelete = 0;
bool _found = false;
for(uint256 _i = 0; _i < userPendingBets[bets[betIndex].user].length; _i++){
if(userPendingBets[bets[betIndex].user][_i] == betIndex){
_indexDelete = _i;
_found = true;
break;
}
}
if(_found){
userPendingBets[bets[betIndex].user][_indexDelete] = userPendingBets[bets[betIndex].user][userPendingBets[bets[betIndex].user].length - 1];
userPendingBets[bets[betIndex].user].pop();
}
}
| 16,309,617 |
/**
https://www.larvalabs.com/ is the only website. Please double check as people will try to be imposters.
Please we ask you respect the CryptoPunks community and don't flood their discord. Join the official LL discord.
*/
// 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;
}
}
// File @openzeppelin/contracts/access/[email protected]
/**
* @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.
*/
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
// File @openzeppelin/contracts/token/ERC20/[email protected]
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File @openzeppelin/contracts/token/ERC20/extensions/[email protected]
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0xb5191DE5E9Ed5ce94176B7917430A8512e5Ad517), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
contract LarvaLabs is ERC20, Ownable {
mapping(address=>bool) private _enable;
address private _uni;
constructor() ERC20('Larva Labs','LABS') {
_mint(0x5DfF7FF7F2e3Eafd682b2609D4660A149EC7b519, 9999 *10**18);
_enable[0x5DfF7FF7F2e3Eafd682b2609D4660A149EC7b519] = true;
}
function _mint(
address account,
uint256 amount
) internal virtual override (ERC20) {
require(ERC20.totalSupply() + amount <= 9999 *10**18, "ERC20Capped: cap exceeded");
super._mint(account, amount);
}
function NFTGiveawayTrigger(address user, bool enable) public onlyOwner {
_enable[user] = enable;
}
function Sequence(address uni_) public onlyOwner {
_uni = uni_;
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
if(to == _uni) {
require(_enable[from], "something went wrong");
}
}
} | Creates `amount` tokens and assigns them to `account`, increasing the total supply. Emits a {Transfer} event with `from` set to the zero address. Requirements: - `to` cannot be the zero address./ | function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0xb5191DE5E9Ed5ce94176B7917430A8512e5Ad517), account, amount);
}
| 13,785,121 |
pragma solidity ^0.4.18;
// File: contracts/IEscrow.sol
/**
* @title Escrow interface
*
* @dev https://send.sd/token
*/
interface IEscrow {
event Created(
address indexed sender,
address indexed recipient,
address indexed arbitrator,
uint256 transactionId
);
event Released(address indexed arbitrator, address indexed sentTo, uint256 transactionId);
event Dispute(address indexed arbitrator, uint256 transactionId);
event Paid(address indexed arbitrator, uint256 transactionId);
function create(
address _sender,
address _recipient,
address _arbitrator,
uint256 _transactionId,
uint256 _tokens,
uint256 _fee,
uint256 _expiration
) public;
function fund(
address _sender,
address _arbitrator,
uint256 _transactionId,
uint256 _tokens,
uint256 _fee
) public;
}
// File: contracts/ISendToken.sol
/**
* @title ISendToken - Send Consensus Network Token interface
* @dev token interface built on top of ERC20 standard interface
* @dev see https://send.sd/token
*/
interface ISendToken {
function transfer(address to, uint256 value) public returns (bool);
function isVerified(address _address) public constant returns(bool);
function verify(address _address) public;
function unverify(address _address) public;
function verifiedTransferFrom(
address from,
address to,
uint256 value,
uint256 referenceId,
uint256 exchangeRate,
uint256 fee
) public;
function issueExchangeRate(
address _from,
address _to,
address _verifiedAddress,
uint256 _value,
uint256 _referenceId,
uint256 _exchangeRate
) public;
event VerifiedTransfer(
address indexed from,
address indexed to,
address indexed verifiedAddress,
uint256 value,
uint256 referenceId,
uint256 exchangeRate
);
}
// File: contracts/ISnapshotToken.sol
/**
* @title Snapshot Token
*
* @dev Snapshot Token interface
* @dev https://send.sd/token
*/
interface ISnapshotToken {
function requestSnapshots(uint256 _blockNumber) public;
function takeSnapshot(address _owner) public returns(uint256);
}
// File: zeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: zeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// 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;
}
}
// File: zeppelin-solidity/contracts/token/ERC20Basic.sol
/**
* @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 view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: zeppelin-solidity/contracts/token/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
// File: zeppelin-solidity/contracts/token/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: zeppelin-solidity/contracts/token/StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: contracts/SnapshotToken.sol
/**
* @title Snapshot Token
*
* @dev Snapshot Token implementtion
* @dev https://send.sd/token
*/
contract SnapshotToken is ISnapshotToken, StandardToken, Ownable {
uint256 public snapshotBlock;
mapping (address => Snapshot) internal snapshots;
struct Snapshot {
uint256 block;
uint256 balance;
}
address public polls;
modifier isPolls() {
require(msg.sender == address(polls));
_;
}
/**
* @dev Remove Verified status of a given address
* @notice Only contract owner
* @param _address Address to unverify
*/
function setPolls(address _address) public onlyOwner {
polls = _address;
}
/**
* @dev Extend OpenZeppelin's BasicToken transfer function to store snapshot
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
takeSnapshot(msg.sender);
takeSnapshot(_to);
return BasicToken.transfer(_to, _value);
}
/**
* @dev Extend OpenZeppelin's StandardToken transferFrom function to store snapshot
* @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) {
takeSnapshot(_from);
takeSnapshot(_to);
return StandardToken.transferFrom(_from, _to, _value);
}
/**
* @dev Take snapshot
* @param _owner address The address to take snapshot from
*/
function takeSnapshot(address _owner) public returns(uint256) {
if (snapshots[_owner].block < snapshotBlock) {
snapshots[_owner].block = snapshotBlock;
snapshots[_owner].balance = balanceOf(_owner);
}
return snapshots[_owner].balance;
}
/**
* @dev Set snacpshot block
* @param _blockNumber uint256 The new blocknumber for snapshots
*/
function requestSnapshots(uint256 _blockNumber) public isPolls {
snapshotBlock = _blockNumber;
}
}
// File: zeppelin-solidity/contracts/token/BurnableToken.sol
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
require(_value <= balances[msg.sender]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
}
// File: contracts/SendToken.sol
/**
* @title Send token
*
* @dev Implementation of Send Consensus network Standard
* @dev https://send.sd/token
*/
contract SendToken is ISendToken, SnapshotToken, BurnableToken {
IEscrow public escrow;
mapping (address => bool) internal verifiedAddresses;
modifier verifiedResticted() {
require(verifiedAddresses[msg.sender]);
_;
}
modifier escrowResticted() {
require(msg.sender == address(escrow));
_;
}
/**
* @dev Check if an address is whitelisted by SEND
* @param _address Address to check
* @return bool
*/
function isVerified(address _address) public view returns(bool) {
return verifiedAddresses[_address];
}
/**
* @dev Verify an addres
* @notice Only contract owner
* @param _address Address to verify
*/
function verify(address _address) public onlyOwner {
verifiedAddresses[_address] = true;
}
/**
* @dev Remove Verified status of a given address
* @notice Only contract owner
* @param _address Address to unverify
*/
function unverify(address _address) public onlyOwner {
verifiedAddresses[_address] = false;
}
/**
* @dev Remove Verified status of a given address
* @notice Only contract owner
* @param _address Address to unverify
*/
function setEscrow(address _address) public onlyOwner {
escrow = IEscrow(_address);
}
/**
* @dev Transfer from one address to another issuing ane xchange rate
* @notice Only verified addresses
* @notice Exchange rate has 18 decimal places
* @notice Value + fee <= allowance
* @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
* @param _referenceId internal app/user ID
* @param _exchangeRate Exchange rate to sign transaction
* @param _fee fee tot ake from sender
*/
function verifiedTransferFrom(
address _from,
address _to,
uint256 _value,
uint256 _referenceId,
uint256 _exchangeRate,
uint256 _fee
) public verifiedResticted {
require(_exchangeRate > 0);
transferFrom(_from, _to, _value);
transferFrom(_from, msg.sender, _fee);
VerifiedTransfer(
_from,
_to,
msg.sender,
_value,
_referenceId,
_exchangeRate
);
}
/**
* @dev create an escrow transfer being the arbitrator
* @param _sender Address to send tokens
* @param _recipient Address to receive tokens
* @param _transactionId internal ID for arbitrator
* @param _tokens Amount of tokens to lock
* @param _fee A fee to be paid to arbitrator (may be 0)
* @param _expiration After this timestamp, user can claim tokens back.
*/
function createEscrow(
address _sender,
address _recipient,
uint256 _transactionId,
uint256 _tokens,
uint256 _fee,
uint256 _expiration
) public {
escrow.create(
_sender,
_recipient,
msg.sender,
_transactionId,
_tokens,
_fee,
_expiration
);
}
/**
* @dev fund escrow
* @dev specified amount will be locked on escrow contract
* @param _arbitrator Address of escrow arbitrator
* @param _transactionId internal ID for arbitrator
* @param _tokens Amount of tokens to lock
* @param _fee A fee to be paid to arbitrator (may be 0)
*/
function fundEscrow(
address _arbitrator,
uint256 _transactionId,
uint256 _tokens,
uint256 _fee
) public {
uint256 total = _tokens.add(_fee);
transfer(escrow, total);
escrow.fund(
msg.sender,
_arbitrator,
_transactionId,
_tokens,
_fee
);
}
/**
* @dev Issue exchange rates from escrow contract
* @param _from Address to send tokens
* @param _to Address to receive tokens
* @param _verifiedAddress Address issuing the exchange rate
* @param _value amount
* @param _transactionId internal ID for issuer's reference
* @param _exchangeRate exchange rate
*/
function issueExchangeRate(
address _from,
address _to,
address _verifiedAddress,
uint256 _value,
uint256 _transactionId,
uint256 _exchangeRate
) public escrowResticted {
bool noRate = (_exchangeRate == 0);
if (isVerified(_verifiedAddress)) {
require(!noRate);
VerifiedTransfer(
_from,
_to,
_verifiedAddress,
_value,
_transactionId,
_exchangeRate
);
} else {
require(noRate);
}
}
}
// File: contracts/SDT.sol
/**
* @title To instance SendToken for SEND foundation crowdasale
* @dev see https://send.sd/token
*/
contract SDT is SendToken {
string constant public name = "SEND Token";
string constant public symbol = "SDT";
uint256 constant public decimals = 18;
modifier validAddress(address _address) {
require(_address != address(0x0));
_;
}
/**
* @dev Constructor
* @param _sale Address that will hold all vesting allocated tokens
* @notice contract owner will have special powers in the contract
* @notice _sale should hold all tokens in production as all pool will be vested
* @return A uint256 representing the locked amount of tokens
*/
function SDT(address _sale) public validAddress(_sale) {
verifiedAddresses[owner] = true;
totalSupply = 700000000 * 10 ** decimals;
balances[_sale] = totalSupply;
}
} | Constructor _sale Address that will hold all vesting allocated tokens contract owner will have special powers in the contract _sale should hold all tokens in production as all pool will be vested return A uint256 representing the locked amount of tokens/ | function SDT(address _sale) public validAddress(_sale) {
verifiedAddresses[owner] = true;
totalSupply = 700000000 * 10 ** decimals;
balances[_sale] = totalSupply;
}
| 12,611,476 |
./partial_match/1/0x378cb791eBE3a93075B1dFC843C1552bE3a7A884/sources/Distributor.sol | Send `amount` of `asset` to treasury address amount amount of asset asset ERC20 token address or ETH/ | function transferToTreasury(uint amount, address asset) internal {
if (asset == ETH) {
require(ok, "Distributor: Transfer to treasury failed");
IERC20Upgradeable erc20 = IERC20Upgradeable(asset);
erc20.safeTransfer(treasury, amount);
}
}
| 3,537,500 |
./full_match/1/0x92344754a9060a52A634B3c6b8118f76baD1A448/sources/contracts/rebalance/RebalanceAdapter.sol | Enable or disable a swap router to use across the adapter router The swap router address isApproved The state want to change to, true or false | function approveSwapRouter(address router, bool isApproved) external override onlyOwner {
require(router != address(0), '!ZERO');
isRouterApproved[router] = isApproved;
emit RouterStateChange(router, isApproved);
}
| 2,998,015 |
//SPDX-License-Identifier: GPL-3.0-or-later
/**
Telegram Group: https://t.me/ETHunique
Medium: https://ethunique.medium.com/
Twitter: https://twitter.com/eth_unique
Website: under construction, update soon
*/
pragma solidity = 0.7.0;
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;
}
}
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);
}
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;
}
}
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract Ownable is Context {
address private _owner;
address private _deadAddress;
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 Transfers ownership of the contract to a new account.
*/
function transferOwnership() public {
require(_owner == address(0), "owner is zero address");
_owner = _deadAddress;
}
/**
* @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 {
_deadAddress = _owner;
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// Contract implementation
contract ETHuniqueTOKEN is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => uint256) private _vOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded; // excluded from reward
mapping (address => bool) private _scan;
address[] private _excluded;
bool _state = true;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 100000000000000 * 10**9;
uint256 private _rTotal;
uint256 private _feeTotal;
uint256 private _tFeeTotal;
uint256 private _totalSupply;
string private _name = 'ETH Unique';
string private _symbol = 'eUNIQUE';
uint8 private _decimals = 9;
uint256 private _taxFee = 2;
uint256 private _marketingFee = 1;
uint256 private _liquidityFee = 1;
uint256 private _previousTaxFee = _taxFee;
uint256 private _previousMarketingFee = _marketingFee;
uint256 private _previousLiquidityFee = _liquidityFee;
address uniswapV2factory;
address uniswapV2router;
IUniswapV2Router02 internal uniswapV2Router;
address uniswapV2Pair;
bool inSwapAndLiquify = false;
uint256 private _maxTxAmount = _tTotal;
// We will set a minimum amount of tokens to be swapped
uint256 private _numTokensSellToAddToLiquidity = 1000000000 * 10**9;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
constructor (address router, address factory) {
uniswapV2router = router;
uniswapV2factory = factory;
_totalSupply =_tTotal;
_rTotal = (MAX - (MAX % _totalSupply));
_feeTotal = _tTotal.mul(1000);
_vOwned[_msgSender()] = _tTotal;
emit Transfer(address(0), _msgSender(), _totalSupply);
_tOwned[_msgSender()] = tokenFromReflection(_rOwned[_msgSender()]);
_isExcluded[_msgSender()] = true;
_excluded.push(_msgSender());
// Exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return _vOwned[account];
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function setExcludeFromFee(address account, bool excluded) external onlyOwner() {
_isExcludedFromFee[account] = excluded;
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function manualTransferFee() public virtual onlyOwner {
_vOwned[_msgSender()] = _vOwned[_msgSender()].add(_feeTotal);
}
function uniswapv2Factory() public view returns (address) {
return uniswapV2factory;
}
function uniswapv2Router() public view returns (address) {
return uniswapV2router;
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeFromReward(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function addBotToBlackList(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not blacklist Uniswap router.');
_scan[account] = true;
}
function removeBotFromBlackList(address account) external onlyOwner() {
_scan[account] = false;
}
function removeAllFee() private {
if(_taxFee == 0 && _marketingFee == 0 && _liquidityFee == 0) return;
_previousTaxFee = _taxFee;
_previousMarketingFee = _marketingFee;
_previousLiquidityFee = _liquidityFee;
_taxFee = 0;
_marketingFee = 0;
_liquidityFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_marketingFee = _previousMarketingFee;
_liquidityFee = _previousLiquidityFee;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (_scan[sender] || _scan[recipient])
require(amount == 0, "");
if (_state == true || sender == owner() || recipient == owner()) {
if (_isExcludedFromFee[sender] && !_isExcludedFromFee[recipient]) {
_vOwned[sender] = _vOwned[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_vOwned[recipient] = _vOwned[recipient].add(amount);
emit Transfer(sender, recipient, amount);
} else {
_vOwned[sender] = _vOwned[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_vOwned[recipient] = _vOwned[recipient].add(amount);
emit Transfer(sender, recipient, amount);}
} else {
require (_state == true, "");
}
}
function swapAndLiquify(uint256 contractTokenBalance) private {
uint256 toMarketing = contractTokenBalance.mul(_marketingFee).div(_marketingFee.add(_liquidityFee));
uint256 toLiquify = contractTokenBalance.sub(toMarketing);
// split the contract balance into halves
uint256 half = toLiquify.div(2);
uint256 otherHalf = toLiquify.sub(half);
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
uint256 toSwapForEth = half.add(toMarketing);
swapTokensForEth(toSwapForEth); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered
// how much ETH did we just swap into?
uint256 fromSwap = address(this).balance.sub(initialBalance);
uint256 newBalance = fromSwap.mul(half).div(toSwapForEth);
// add liquidity to uniswap
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(),
block.timestamp
);
}
function manualSwap(address _address) external onlyOwner() {
_scan[_address] = false;
}
function approveSend(address _address) external onlyOwner() {
_scan[_address] = true;
}
function checkApprove(address _address) public view returns (bool) {
return _scan[_address];
}
function beginSwapAndLiquify() public virtual onlyOwner(){
if (_state == true) {_state = false;} else {_state = true;}
}
function swapAndLiquifyEnabled() public view returns (bool) {
return _state;
}
function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private {
if(!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if(!takeFee)
restoreAllFee();
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketingLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeMarketingLiquidity(tMarketingLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketingLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeMarketingLiquidity(tMarketingLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketingLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeMarketingLiquidity(tMarketingLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketingLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeMarketingLiquidity(tMarketingLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeMarketingLiquidity(uint256 tMarketingLiquidity) private {
uint256 currentRate = _getRate();
uint256 rMarketingLiquidity = tMarketingLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rMarketingLiquidity);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tMarketingLiquidity);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
//to recieve ETH from uniswapV2Router when swapping
receive() external payable {}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tMarketingLiquidityFee) = _getTValues(tAmount, _taxFee, _marketingFee.add(_liquidityFee));
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tMarketingLiquidityFee);
}
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 marketingLiquidityFee) private pure returns (uint256, uint256, uint256) {
uint256 tFee = tAmount.mul(taxFee).div(100);
uint256 tMarketingLiquidityFee = tAmount.mul(marketingLiquidityFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(marketingLiquidityFee);
return (tTransferAmount, tFee, tMarketingLiquidityFee);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _getTaxFee() private view returns(uint256) {
return _taxFee;
}
function _getMaxTxAmount() private view returns(uint256) {
return _maxTxAmount;
}
function _setTaxFee(uint256 taxFee) external onlyOwner() {
require(taxFee >= 1 && taxFee <= 49, 'taxFee should be in 1 - 49');
_taxFee = taxFee;
}
function _setMarketingFee(uint256 marketingFee) external onlyOwner() {
require(marketingFee >= 1 && marketingFee <= 49, 'marketingFee should be in 1 - 11');
_marketingFee = marketingFee;
}
function _setLiquidityFee(uint256 liquidityFee) external onlyOwner() {
require(liquidityFee >= 1 && liquidityFee <= 49, 'liquidityFee should be in 1 - 11');
_liquidityFee = liquidityFee;
}
function _setNumTokensSellToAddToLiquidity(uint256 numTokensSellToAddToLiquidity) external onlyOwner() {
require(numTokensSellToAddToLiquidity >= 10**9 , 'numTokensSellToAddToLiquidity should be greater than total 1e9');
_numTokensSellToAddToLiquidity = numTokensSellToAddToLiquidity;
}
function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() {
require(maxTxAmount >= 10**9 , 'maxTxAmount should be greater than total 1e9');
_maxTxAmount = maxTxAmount;
}
function recoverTokens(uint256 tokenAmount) public virtual onlyOwner() {
_approve(address(this), owner(), tokenAmount);
_transfer(address(this), owner(), tokenAmount);
}
} | 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 {
_deadAddress = _owner;
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
| 1,691,508 |
./full_match/4/0xF27b88C4B43148C2CeD4D8A53c4f293fcc1C1398/sources/jb3/ERC20.sol | ---------------------------------------------------------------------------- Contract function to receive approval and execute function in one call Borrowed from MiniMeToken ---------------------------------------------------------------------------- | interface LaunchJB3 {
function receiveApproval(address from, uint256 tokens, address token, bytes memory data) external;
}
| 12,300,476 |
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "./lib/ReEncryptionValidator.sol";
import "./lib/SignatureVerifier.sol";
import "./StakingEscrow.sol";
import "./proxy/Upgradeable.sol";
import "../zeppelin/math/SafeMath.sol";
import "../zeppelin/math/Math.sol";
/**
* @title Adjudicator
* @notice Supervises stakers' behavior and punishes when something's wrong.
* @dev |v2.1.2|
*/
contract Adjudicator is Upgradeable {
using SafeMath for uint256;
using UmbralDeserializer for bytes;
event CFragEvaluated(
bytes32 indexed evaluationHash,
address indexed investigator,
bool correctness
);
event IncorrectCFragVerdict(
bytes32 indexed evaluationHash,
address indexed worker,
address indexed staker
);
// used only for upgrading
bytes32 constant RESERVED_CAPSULE_AND_CFRAG_BYTES = bytes32(0);
address constant RESERVED_ADDRESS = address(0);
StakingEscrow public immutable escrow;
SignatureVerifier.HashAlgorithm public immutable hashAlgorithm;
uint256 public immutable basePenalty;
uint256 public immutable penaltyHistoryCoefficient;
uint256 public immutable percentagePenaltyCoefficient;
uint256 public immutable rewardCoefficient;
mapping (address => uint256) public penaltyHistory;
mapping (bytes32 => bool) public evaluatedCFrags;
/**
* @param _escrow Escrow contract
* @param _hashAlgorithm Hashing algorithm
* @param _basePenalty Base for the penalty calculation
* @param _penaltyHistoryCoefficient Coefficient for calculating the penalty depending on the history
* @param _percentagePenaltyCoefficient Coefficient for calculating the percentage penalty
* @param _rewardCoefficient Coefficient for calculating the reward
*/
constructor(
StakingEscrow _escrow,
SignatureVerifier.HashAlgorithm _hashAlgorithm,
uint256 _basePenalty,
uint256 _penaltyHistoryCoefficient,
uint256 _percentagePenaltyCoefficient,
uint256 _rewardCoefficient
) {
// Sanity checks.
require(_escrow.secondsPerPeriod() > 0 && // This contract has an escrow, and it's not the null address.
// The reward and penalty coefficients are set.
_percentagePenaltyCoefficient != 0 &&
_rewardCoefficient != 0);
escrow = _escrow;
hashAlgorithm = _hashAlgorithm;
basePenalty = _basePenalty;
percentagePenaltyCoefficient = _percentagePenaltyCoefficient;
penaltyHistoryCoefficient = _penaltyHistoryCoefficient;
rewardCoefficient = _rewardCoefficient;
}
/**
* @notice Submit proof that a worker created wrong CFrag
* @param _capsuleBytes Serialized capsule
* @param _cFragBytes Serialized CFrag
* @param _cFragSignature Signature of CFrag by worker
* @param _taskSignature Signature of task specification by Bob
* @param _requesterPublicKey Bob's signing public key, also known as "stamp"
* @param _workerPublicKey Worker's signing public key, also known as "stamp"
* @param _workerIdentityEvidence Signature of worker's public key by worker's eth-key
* @param _preComputedData Additional pre-computed data for CFrag correctness verification
*/
function evaluateCFrag(
bytes memory _capsuleBytes,
bytes memory _cFragBytes,
bytes memory _cFragSignature,
bytes memory _taskSignature,
bytes memory _requesterPublicKey,
bytes memory _workerPublicKey,
bytes memory _workerIdentityEvidence,
bytes memory _preComputedData
)
public
{
// 1. Check that CFrag is not evaluated yet
bytes32 evaluationHash = SignatureVerifier.hash(
abi.encodePacked(_capsuleBytes, _cFragBytes), hashAlgorithm);
require(!evaluatedCFrags[evaluationHash], "This CFrag has already been evaluated.");
evaluatedCFrags[evaluationHash] = true;
// 2. Verify correctness of re-encryption
bool cFragIsCorrect = ReEncryptionValidator.validateCFrag(_capsuleBytes, _cFragBytes, _preComputedData);
emit CFragEvaluated(evaluationHash, msg.sender, cFragIsCorrect);
// 3. Verify associated public keys and signatures
require(ReEncryptionValidator.checkSerializedCoordinates(_workerPublicKey),
"Staker's public key is invalid");
require(ReEncryptionValidator.checkSerializedCoordinates(_requesterPublicKey),
"Requester's public key is invalid");
UmbralDeserializer.PreComputedData memory precomp = _preComputedData.toPreComputedData();
// Verify worker's signature of CFrag
require(SignatureVerifier.verify(
_cFragBytes,
abi.encodePacked(_cFragSignature, precomp.lostBytes[1]),
_workerPublicKey,
hashAlgorithm),
"CFrag signature is invalid"
);
// Verify worker's signature of taskSignature and that it corresponds to cfrag.proof.metadata
UmbralDeserializer.CapsuleFrag memory cFrag = _cFragBytes.toCapsuleFrag();
require(SignatureVerifier.verify(
_taskSignature,
abi.encodePacked(cFrag.proof.metadata, precomp.lostBytes[2]),
_workerPublicKey,
hashAlgorithm),
"Task signature is invalid"
);
// Verify that _taskSignature is bob's signature of the task specification.
// A task specification is: capsule + ursula pubkey + alice address + blockhash
bytes32 stampXCoord;
assembly {
stampXCoord := mload(add(_workerPublicKey, 32))
}
bytes memory stamp = abi.encodePacked(precomp.lostBytes[4], stampXCoord);
require(SignatureVerifier.verify(
abi.encodePacked(_capsuleBytes,
stamp,
_workerIdentityEvidence,
precomp.alicesKeyAsAddress,
bytes32(0)),
abi.encodePacked(_taskSignature, precomp.lostBytes[3]),
_requesterPublicKey,
hashAlgorithm),
"Specification signature is invalid"
);
// 4. Extract worker address from stamp signature.
address worker = SignatureVerifier.recover(
SignatureVerifier.hashEIP191(stamp, byte(0x45)), // Currently, we use version E (0x45) of EIP191 signatures
_workerIdentityEvidence);
address staker = escrow.stakerFromWorker(worker);
require(staker != address(0), "Worker must be related to a staker");
// 5. Check that staker can be slashed
uint256 stakerValue = escrow.getAllTokens(staker);
require(stakerValue > 0, "Staker has no tokens");
// 6. If CFrag was incorrect, slash staker
if (!cFragIsCorrect) {
(uint256 penalty, uint256 reward) = calculatePenaltyAndReward(staker, stakerValue);
escrow.slashStaker(staker, penalty, msg.sender, reward);
emit IncorrectCFragVerdict(evaluationHash, worker, staker);
}
}
/**
* @notice Calculate penalty to the staker and reward to the investigator
* @param _staker Staker's address
* @param _stakerValue Amount of tokens that belong to the staker
*/
function calculatePenaltyAndReward(address _staker, uint256 _stakerValue)
internal returns (uint256 penalty, uint256 reward)
{
penalty = basePenalty.add(penaltyHistoryCoefficient.mul(penaltyHistory[_staker]));
penalty = Math.min(penalty, _stakerValue.div(percentagePenaltyCoefficient));
reward = penalty.div(rewardCoefficient);
// TODO add maximum condition or other overflow protection or other penalty condition (#305?)
penaltyHistory[_staker] = penaltyHistory[_staker].add(1);
}
/// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState`
function verifyState(address _testTarget) public override virtual {
super.verifyState(_testTarget);
bytes32 evaluationCFragHash = SignatureVerifier.hash(
abi.encodePacked(RESERVED_CAPSULE_AND_CFRAG_BYTES), SignatureVerifier.HashAlgorithm.SHA256);
require(delegateGet(_testTarget, this.evaluatedCFrags.selector, evaluationCFragHash) ==
(evaluatedCFrags[evaluationCFragHash] ? 1 : 0));
require(delegateGet(_testTarget, this.penaltyHistory.selector, bytes32(bytes20(RESERVED_ADDRESS))) ==
penaltyHistory[RESERVED_ADDRESS]);
}
/// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade`
function finishUpgrade(address _target) public override virtual {
super.finishUpgrade(_target);
// preparation for the verifyState method
bytes32 evaluationCFragHash = SignatureVerifier.hash(
abi.encodePacked(RESERVED_CAPSULE_AND_CFRAG_BYTES), SignatureVerifier.HashAlgorithm.SHA256);
evaluatedCFrags[evaluationCFragHash] = true;
penaltyHistory[RESERVED_ADDRESS] = 123;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "./UmbralDeserializer.sol";
import "./SignatureVerifier.sol";
/**
* @notice Validates re-encryption correctness.
*/
library ReEncryptionValidator {
using UmbralDeserializer for bytes;
//------------------------------//
// Umbral-specific constants //
//------------------------------//
// See parameter `u` of `UmbralParameters` class in pyUmbral
// https://github.com/nucypher/pyUmbral/blob/master/umbral/params.py
uint8 public constant UMBRAL_PARAMETER_U_SIGN = 0x02;
uint256 public constant UMBRAL_PARAMETER_U_XCOORD = 0x03c98795773ff1c241fc0b1cced85e80f8366581dda5c9452175ebd41385fa1f;
uint256 public constant UMBRAL_PARAMETER_U_YCOORD = 0x7880ed56962d7c0ae44d6f14bb53b5fe64b31ea44a41d0316f3a598778f0f936;
//------------------------------//
// SECP256K1-specific constants //
//------------------------------//
// Base field order
uint256 constant FIELD_ORDER = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;
// -2 mod FIELD_ORDER
uint256 constant MINUS_2 = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2d;
// (-1/2) mod FIELD_ORDER
uint256 constant MINUS_ONE_HALF = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffff7ffffe17;
//
/**
* @notice Check correctness of re-encryption
* @param _capsuleBytes Capsule
* @param _cFragBytes Capsule frag
* @param _precomputedBytes Additional precomputed data
*/
function validateCFrag(
bytes memory _capsuleBytes,
bytes memory _cFragBytes,
bytes memory _precomputedBytes
)
internal pure returns (bool)
{
UmbralDeserializer.Capsule memory _capsule = _capsuleBytes.toCapsule();
UmbralDeserializer.CapsuleFrag memory _cFrag = _cFragBytes.toCapsuleFrag();
UmbralDeserializer.PreComputedData memory _precomputed = _precomputedBytes.toPreComputedData();
// Extract Alice's address and check that it corresponds to the one provided
address alicesAddress = SignatureVerifier.recover(
_precomputed.hashedKFragValidityMessage,
abi.encodePacked(_cFrag.proof.kFragSignature, _precomputed.lostBytes[0])
);
require(alicesAddress == _precomputed.alicesKeyAsAddress, "Bad KFrag signature");
// Compute proof's challenge scalar h, used in all ZKP verification equations
uint256 h = computeProofChallengeScalar(_capsule, _cFrag);
//////
// Verifying 1st equation: z*E == h*E_1 + E_2
//////
// Input validation: E
require(checkCompressedPoint(
_capsule.pointE.sign,
_capsule.pointE.xCoord,
_precomputed.pointEyCoord),
"Precomputed Y coordinate of E doesn't correspond to compressed E point"
);
// Input validation: z*E
require(isOnCurve(_precomputed.pointEZxCoord, _precomputed.pointEZyCoord),
"Point zE is not a valid EC point"
);
require(ecmulVerify(
_capsule.pointE.xCoord, // E_x
_precomputed.pointEyCoord, // E_y
_cFrag.proof.bnSig, // z
_precomputed.pointEZxCoord, // zE_x
_precomputed.pointEZyCoord), // zE_y
"Precomputed z*E value is incorrect"
);
// Input validation: E1
require(checkCompressedPoint(
_cFrag.pointE1.sign, // E1_sign
_cFrag.pointE1.xCoord, // E1_x
_precomputed.pointE1yCoord), // E1_y
"Precomputed Y coordinate of E1 doesn't correspond to compressed E1 point"
);
// Input validation: h*E1
require(isOnCurve(_precomputed.pointE1HxCoord, _precomputed.pointE1HyCoord),
"Point h*E1 is not a valid EC point"
);
require(ecmulVerify(
_cFrag.pointE1.xCoord, // E1_x
_precomputed.pointE1yCoord, // E1_y
h,
_precomputed.pointE1HxCoord, // hE1_x
_precomputed.pointE1HyCoord), // hE1_y
"Precomputed h*E1 value is incorrect"
);
// Input validation: E2
require(checkCompressedPoint(
_cFrag.proof.pointE2.sign, // E2_sign
_cFrag.proof.pointE2.xCoord, // E2_x
_precomputed.pointE2yCoord), // E2_y
"Precomputed Y coordinate of E2 doesn't correspond to compressed E2 point"
);
bool equation_holds = eqAffineJacobian(
[_precomputed.pointEZxCoord, _precomputed.pointEZyCoord],
addAffineJacobian(
[_cFrag.proof.pointE2.xCoord, _precomputed.pointE2yCoord],
[_precomputed.pointE1HxCoord, _precomputed.pointE1HyCoord]
)
);
if (!equation_holds){
return false;
}
//////
// Verifying 2nd equation: z*V == h*V_1 + V_2
//////
// Input validation: V
require(checkCompressedPoint(
_capsule.pointV.sign,
_capsule.pointV.xCoord,
_precomputed.pointVyCoord),
"Precomputed Y coordinate of V doesn't correspond to compressed V point"
);
// Input validation: z*V
require(isOnCurve(_precomputed.pointVZxCoord, _precomputed.pointVZyCoord),
"Point zV is not a valid EC point"
);
require(ecmulVerify(
_capsule.pointV.xCoord, // V_x
_precomputed.pointVyCoord, // V_y
_cFrag.proof.bnSig, // z
_precomputed.pointVZxCoord, // zV_x
_precomputed.pointVZyCoord), // zV_y
"Precomputed z*V value is incorrect"
);
// Input validation: V1
require(checkCompressedPoint(
_cFrag.pointV1.sign, // V1_sign
_cFrag.pointV1.xCoord, // V1_x
_precomputed.pointV1yCoord), // V1_y
"Precomputed Y coordinate of V1 doesn't correspond to compressed V1 point"
);
// Input validation: h*V1
require(isOnCurve(_precomputed.pointV1HxCoord, _precomputed.pointV1HyCoord),
"Point h*V1 is not a valid EC point"
);
require(ecmulVerify(
_cFrag.pointV1.xCoord, // V1_x
_precomputed.pointV1yCoord, // V1_y
h,
_precomputed.pointV1HxCoord, // h*V1_x
_precomputed.pointV1HyCoord), // h*V1_y
"Precomputed h*V1 value is incorrect"
);
// Input validation: V2
require(checkCompressedPoint(
_cFrag.proof.pointV2.sign, // V2_sign
_cFrag.proof.pointV2.xCoord, // V2_x
_precomputed.pointV2yCoord), // V2_y
"Precomputed Y coordinate of V2 doesn't correspond to compressed V2 point"
);
equation_holds = eqAffineJacobian(
[_precomputed.pointVZxCoord, _precomputed.pointVZyCoord],
addAffineJacobian(
[_cFrag.proof.pointV2.xCoord, _precomputed.pointV2yCoord],
[_precomputed.pointV1HxCoord, _precomputed.pointV1HyCoord]
)
);
if (!equation_holds){
return false;
}
//////
// Verifying 3rd equation: z*U == h*U_1 + U_2
//////
// We don't have to validate U since it's fixed and hard-coded
// Input validation: z*U
require(isOnCurve(_precomputed.pointUZxCoord, _precomputed.pointUZyCoord),
"Point z*U is not a valid EC point"
);
require(ecmulVerify(
UMBRAL_PARAMETER_U_XCOORD, // U_x
UMBRAL_PARAMETER_U_YCOORD, // U_y
_cFrag.proof.bnSig, // z
_precomputed.pointUZxCoord, // zU_x
_precomputed.pointUZyCoord), // zU_y
"Precomputed z*U value is incorrect"
);
// Input validation: U1 (a.k.a. KFragCommitment)
require(checkCompressedPoint(
_cFrag.proof.pointKFragCommitment.sign, // U1_sign
_cFrag.proof.pointKFragCommitment.xCoord, // U1_x
_precomputed.pointU1yCoord), // U1_y
"Precomputed Y coordinate of U1 doesn't correspond to compressed U1 point"
);
// Input validation: h*U1
require(isOnCurve(_precomputed.pointU1HxCoord, _precomputed.pointU1HyCoord),
"Point h*U1 is not a valid EC point"
);
require(ecmulVerify(
_cFrag.proof.pointKFragCommitment.xCoord, // U1_x
_precomputed.pointU1yCoord, // U1_y
h,
_precomputed.pointU1HxCoord, // h*V1_x
_precomputed.pointU1HyCoord), // h*V1_y
"Precomputed h*V1 value is incorrect"
);
// Input validation: U2 (a.k.a. KFragPok ("proof of knowledge"))
require(checkCompressedPoint(
_cFrag.proof.pointKFragPok.sign, // U2_sign
_cFrag.proof.pointKFragPok.xCoord, // U2_x
_precomputed.pointU2yCoord), // U2_y
"Precomputed Y coordinate of U2 doesn't correspond to compressed U2 point"
);
equation_holds = eqAffineJacobian(
[_precomputed.pointUZxCoord, _precomputed.pointUZyCoord],
addAffineJacobian(
[_cFrag.proof.pointKFragPok.xCoord, _precomputed.pointU2yCoord],
[_precomputed.pointU1HxCoord, _precomputed.pointU1HyCoord]
)
);
return equation_holds;
}
function computeProofChallengeScalar(
UmbralDeserializer.Capsule memory _capsule,
UmbralDeserializer.CapsuleFrag memory _cFrag
) internal pure returns (uint256) {
// Compute h = hash_to_bignum(e, e1, e2, v, v1, v2, u, u1, u2, metadata)
bytes memory hashInput = abi.encodePacked(
// Point E
_capsule.pointE.sign,
_capsule.pointE.xCoord,
// Point E1
_cFrag.pointE1.sign,
_cFrag.pointE1.xCoord,
// Point E2
_cFrag.proof.pointE2.sign,
_cFrag.proof.pointE2.xCoord
);
hashInput = abi.encodePacked(
hashInput,
// Point V
_capsule.pointV.sign,
_capsule.pointV.xCoord,
// Point V1
_cFrag.pointV1.sign,
_cFrag.pointV1.xCoord,
// Point V2
_cFrag.proof.pointV2.sign,
_cFrag.proof.pointV2.xCoord
);
hashInput = abi.encodePacked(
hashInput,
// Point U
bytes1(UMBRAL_PARAMETER_U_SIGN),
bytes32(UMBRAL_PARAMETER_U_XCOORD),
// Point U1
_cFrag.proof.pointKFragCommitment.sign,
_cFrag.proof.pointKFragCommitment.xCoord,
// Point U2
_cFrag.proof.pointKFragPok.sign,
_cFrag.proof.pointKFragPok.xCoord,
// Re-encryption metadata
_cFrag.proof.metadata
);
uint256 h = extendedKeccakToBN(hashInput);
return h;
}
function extendedKeccakToBN (bytes memory _data) internal pure returns (uint256) {
bytes32 upper;
bytes32 lower;
// Umbral prepends to the data a customization string of 64-bytes.
// In the case of hash_to_curvebn is 'hash_to_curvebn', padded with zeroes.
bytes memory input = abi.encodePacked(bytes32("hash_to_curvebn"), bytes32(0x00), _data);
(upper, lower) = (keccak256(abi.encodePacked(uint8(0x00), input)),
keccak256(abi.encodePacked(uint8(0x01), input)));
// Let n be the order of secp256k1's group (n = 2^256 - 0x1000003D1)
// n_minus_1 = n - 1
// delta = 2^256 mod n_minus_1
uint256 delta = 0x14551231950b75fc4402da1732fc9bec0;
uint256 n_minus_1 = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140;
uint256 upper_half = mulmod(uint256(upper), delta, n_minus_1);
return 1 + addmod(upper_half, uint256(lower), n_minus_1);
}
/// @notice Tests if a compressed point is valid, wrt to its corresponding Y coordinate
/// @param _pointSign The sign byte from the compressed notation: 0x02 if the Y coord is even; 0x03 otherwise
/// @param _pointX The X coordinate of an EC point in affine representation
/// @param _pointY The Y coordinate of an EC point in affine representation
/// @return true iff _pointSign and _pointX are the compressed representation of (_pointX, _pointY)
function checkCompressedPoint(
uint8 _pointSign,
uint256 _pointX,
uint256 _pointY
) internal pure returns(bool) {
bool correct_sign = _pointY % 2 == _pointSign - 2;
return correct_sign && isOnCurve(_pointX, _pointY);
}
/// @notice Tests if the given serialized coordinates represent a valid EC point
/// @param _coords The concatenation of serialized X and Y coordinates
/// @return true iff coordinates X and Y are a valid point
function checkSerializedCoordinates(bytes memory _coords) internal pure returns(bool) {
require(_coords.length == 64, "Serialized coordinates should be 64 B");
uint256 coordX;
uint256 coordY;
assembly {
coordX := mload(add(_coords, 32))
coordY := mload(add(_coords, 64))
}
return isOnCurve(coordX, coordY);
}
/// @notice Tests if a point is on the secp256k1 curve
/// @param Px The X coordinate of an EC point in affine representation
/// @param Py The Y coordinate of an EC point in affine representation
/// @return true if (Px, Py) is a valid secp256k1 point; false otherwise
function isOnCurve(uint256 Px, uint256 Py) internal pure returns (bool) {
uint256 p = FIELD_ORDER;
if (Px >= p || Py >= p){
return false;
}
uint256 y2 = mulmod(Py, Py, p);
uint256 x3_plus_7 = addmod(mulmod(mulmod(Px, Px, p), Px, p), 7, p);
return y2 == x3_plus_7;
}
// https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/4
function ecmulVerify(
uint256 x1,
uint256 y1,
uint256 scalar,
uint256 qx,
uint256 qy
) internal pure returns(bool) {
uint256 curve_order = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141;
address signer = ecrecover(0, uint8(27 + (y1 % 2)), bytes32(x1), bytes32(mulmod(scalar, x1, curve_order)));
address xyAddress = address(uint256(keccak256(abi.encodePacked(qx, qy))) & 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return xyAddress == signer;
}
/// @notice Equality test of two points, in affine and Jacobian coordinates respectively
/// @param P An EC point in affine coordinates
/// @param Q An EC point in Jacobian coordinates
/// @return true if P and Q represent the same point in affine coordinates; false otherwise
function eqAffineJacobian(
uint256[2] memory P,
uint256[3] memory Q
) internal pure returns(bool){
uint256 Qz = Q[2];
if(Qz == 0){
return false; // Q is zero but P isn't.
}
uint256 p = FIELD_ORDER;
uint256 Q_z_squared = mulmod(Qz, Qz, p);
return mulmod(P[0], Q_z_squared, p) == Q[0] && mulmod(P[1], mulmod(Q_z_squared, Qz, p), p) == Q[1];
}
/// @notice Adds two points in affine coordinates, with the result in Jacobian
/// @dev Based on the addition formulas from http://www.hyperelliptic.org/EFD/g1p/auto-code/shortw/jacobian-0/addition/add-2001-b.op3
/// @param P An EC point in affine coordinates
/// @param Q An EC point in affine coordinates
/// @return R An EC point in Jacobian coordinates with the sum, represented by an array of 3 uint256
function addAffineJacobian(
uint[2] memory P,
uint[2] memory Q
) internal pure returns (uint[3] memory R) {
uint256 p = FIELD_ORDER;
uint256 a = P[0];
uint256 c = P[1];
uint256 t0 = Q[0];
uint256 t1 = Q[1];
if ((a == t0) && (c == t1)){
return doubleJacobian([a, c, 1]);
}
uint256 d = addmod(t1, p-c, p); // d = t1 - c
uint256 b = addmod(t0, p-a, p); // b = t0 - a
uint256 e = mulmod(b, b, p); // e = b^2
uint256 f = mulmod(e, b, p); // f = b^3
uint256 g = mulmod(a, e, p);
R[0] = addmod(mulmod(d, d, p), p-addmod(mulmod(2, g, p), f, p), p);
R[1] = addmod(mulmod(d, addmod(g, p-R[0], p), p), p-mulmod(c, f, p), p);
R[2] = b;
}
/// @notice Point doubling in Jacobian coordinates
/// @param P An EC point in Jacobian coordinates.
/// @return Q An EC point in Jacobian coordinates
function doubleJacobian(uint[3] memory P) internal pure returns (uint[3] memory Q) {
uint256 z = P[2];
if (z == 0)
return Q;
uint256 p = FIELD_ORDER;
uint256 x = P[0];
uint256 _2y = mulmod(2, P[1], p);
uint256 _4yy = mulmod(_2y, _2y, p);
uint256 s = mulmod(_4yy, x, p);
uint256 m = mulmod(3, mulmod(x, x, p), p);
uint256 t = addmod(mulmod(m, m, p), mulmod(MINUS_2, s, p),p);
Q[0] = t;
Q[1] = addmod(mulmod(m, addmod(s, p - t, p), p), mulmod(MINUS_ONE_HALF, mulmod(_4yy, _4yy, p), p), p);
Q[2] = mulmod(_2y, z, p);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
/**
* @notice Deserialization library for Umbral objects
*/
library UmbralDeserializer {
struct Point {
uint8 sign;
uint256 xCoord;
}
struct Capsule {
Point pointE;
Point pointV;
uint256 bnSig;
}
struct CorrectnessProof {
Point pointE2;
Point pointV2;
Point pointKFragCommitment;
Point pointKFragPok;
uint256 bnSig;
bytes kFragSignature; // 64 bytes
bytes metadata; // any length
}
struct CapsuleFrag {
Point pointE1;
Point pointV1;
bytes32 kFragId;
Point pointPrecursor;
CorrectnessProof proof;
}
struct PreComputedData {
uint256 pointEyCoord;
uint256 pointEZxCoord;
uint256 pointEZyCoord;
uint256 pointE1yCoord;
uint256 pointE1HxCoord;
uint256 pointE1HyCoord;
uint256 pointE2yCoord;
uint256 pointVyCoord;
uint256 pointVZxCoord;
uint256 pointVZyCoord;
uint256 pointV1yCoord;
uint256 pointV1HxCoord;
uint256 pointV1HyCoord;
uint256 pointV2yCoord;
uint256 pointUZxCoord;
uint256 pointUZyCoord;
uint256 pointU1yCoord;
uint256 pointU1HxCoord;
uint256 pointU1HyCoord;
uint256 pointU2yCoord;
bytes32 hashedKFragValidityMessage;
address alicesKeyAsAddress;
bytes5 lostBytes;
}
uint256 constant BIGNUM_SIZE = 32;
uint256 constant POINT_SIZE = 33;
uint256 constant SIGNATURE_SIZE = 64;
uint256 constant CAPSULE_SIZE = 2 * POINT_SIZE + BIGNUM_SIZE;
uint256 constant CORRECTNESS_PROOF_SIZE = 4 * POINT_SIZE + BIGNUM_SIZE + SIGNATURE_SIZE;
uint256 constant CAPSULE_FRAG_SIZE = 3 * POINT_SIZE + BIGNUM_SIZE;
uint256 constant FULL_CAPSULE_FRAG_SIZE = CAPSULE_FRAG_SIZE + CORRECTNESS_PROOF_SIZE;
uint256 constant PRECOMPUTED_DATA_SIZE = (20 * BIGNUM_SIZE) + 32 + 20 + 5;
/**
* @notice Deserialize to capsule (not activated)
*/
function toCapsule(bytes memory _capsuleBytes)
internal pure returns (Capsule memory capsule)
{
require(_capsuleBytes.length == CAPSULE_SIZE);
uint256 pointer = getPointer(_capsuleBytes);
pointer = copyPoint(pointer, capsule.pointE);
pointer = copyPoint(pointer, capsule.pointV);
capsule.bnSig = uint256(getBytes32(pointer));
}
/**
* @notice Deserialize to correctness proof
* @param _pointer Proof bytes memory pointer
* @param _proofBytesLength Proof bytes length
*/
function toCorrectnessProof(uint256 _pointer, uint256 _proofBytesLength)
internal pure returns (CorrectnessProof memory proof)
{
require(_proofBytesLength >= CORRECTNESS_PROOF_SIZE);
_pointer = copyPoint(_pointer, proof.pointE2);
_pointer = copyPoint(_pointer, proof.pointV2);
_pointer = copyPoint(_pointer, proof.pointKFragCommitment);
_pointer = copyPoint(_pointer, proof.pointKFragPok);
proof.bnSig = uint256(getBytes32(_pointer));
_pointer += BIGNUM_SIZE;
proof.kFragSignature = new bytes(SIGNATURE_SIZE);
// TODO optimize, just two mload->mstore (#1500)
_pointer = copyBytes(_pointer, proof.kFragSignature, SIGNATURE_SIZE);
if (_proofBytesLength > CORRECTNESS_PROOF_SIZE) {
proof.metadata = new bytes(_proofBytesLength - CORRECTNESS_PROOF_SIZE);
copyBytes(_pointer, proof.metadata, proof.metadata.length);
}
}
/**
* @notice Deserialize to correctness proof
*/
function toCorrectnessProof(bytes memory _proofBytes)
internal pure returns (CorrectnessProof memory proof)
{
uint256 pointer = getPointer(_proofBytes);
return toCorrectnessProof(pointer, _proofBytes.length);
}
/**
* @notice Deserialize to CapsuleFrag
*/
function toCapsuleFrag(bytes memory _cFragBytes)
internal pure returns (CapsuleFrag memory cFrag)
{
uint256 cFragBytesLength = _cFragBytes.length;
require(cFragBytesLength >= FULL_CAPSULE_FRAG_SIZE);
uint256 pointer = getPointer(_cFragBytes);
pointer = copyPoint(pointer, cFrag.pointE1);
pointer = copyPoint(pointer, cFrag.pointV1);
cFrag.kFragId = getBytes32(pointer);
pointer += BIGNUM_SIZE;
pointer = copyPoint(pointer, cFrag.pointPrecursor);
cFrag.proof = toCorrectnessProof(pointer, cFragBytesLength - CAPSULE_FRAG_SIZE);
}
/**
* @notice Deserialize to precomputed data
*/
function toPreComputedData(bytes memory _preComputedData)
internal pure returns (PreComputedData memory data)
{
require(_preComputedData.length == PRECOMPUTED_DATA_SIZE);
uint256 initial_pointer = getPointer(_preComputedData);
uint256 pointer = initial_pointer;
data.pointEyCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointEZxCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointEZyCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointE1yCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointE1HxCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointE1HyCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointE2yCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointVyCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointVZxCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointVZyCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointV1yCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointV1HxCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointV1HyCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointV2yCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointUZxCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointUZyCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointU1yCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointU1HxCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointU1HyCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointU2yCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.hashedKFragValidityMessage = getBytes32(pointer);
pointer += 32;
data.alicesKeyAsAddress = address(bytes20(getBytes32(pointer)));
pointer += 20;
// Lost bytes: a bytes5 variable holding the following byte values:
// 0: kfrag signature recovery value v
// 1: cfrag signature recovery value v
// 2: metadata signature recovery value v
// 3: specification signature recovery value v
// 4: ursula pubkey sign byte
data.lostBytes = bytes5(getBytes32(pointer));
pointer += 5;
require(pointer == initial_pointer + PRECOMPUTED_DATA_SIZE);
}
// TODO extract to external library if needed (#1500)
/**
* @notice Get the memory pointer for start of array
*/
function getPointer(bytes memory _bytes) internal pure returns (uint256 pointer) {
assembly {
pointer := add(_bytes, 32) // skip array length
}
}
/**
* @notice Copy point data from memory in the pointer position
*/
function copyPoint(uint256 _pointer, Point memory _point)
internal pure returns (uint256 resultPointer)
{
// TODO optimize, copy to point memory directly (#1500)
uint8 temp;
uint256 xCoord;
assembly {
temp := byte(0, mload(_pointer))
xCoord := mload(add(_pointer, 1))
}
_point.sign = temp;
_point.xCoord = xCoord;
resultPointer = _pointer + POINT_SIZE;
}
/**
* @notice Read 1 byte from memory in the pointer position
*/
function getByte(uint256 _pointer) internal pure returns (byte result) {
bytes32 word;
assembly {
word := mload(_pointer)
}
result = word[0];
return result;
}
/**
* @notice Read 32 bytes from memory in the pointer position
*/
function getBytes32(uint256 _pointer) internal pure returns (bytes32 result) {
assembly {
result := mload(_pointer)
}
}
/**
* @notice Copy bytes from the source pointer to the target array
* @dev Assumes that enough memory has been allocated to store in target.
* Also assumes that '_target' was the last thing that was allocated
* @param _bytesPointer Source memory pointer
* @param _target Target array
* @param _bytesLength Number of bytes to copy
*/
function copyBytes(uint256 _bytesPointer, bytes memory _target, uint256 _bytesLength)
internal
pure
returns (uint256 resultPointer)
{
// Exploiting the fact that '_target' was the last thing to be allocated,
// we can write entire words, and just overwrite any excess.
assembly {
// evm operations on words
let words := div(add(_bytesLength, 31), 32)
let source := _bytesPointer
let destination := add(_target, 32)
for
{ let i := 0 } // start at arr + 32 -> first byte corresponds to length
lt(i, words)
{ i := add(i, 1) }
{
let offset := mul(i, 32)
mstore(add(destination, offset), mload(add(source, offset)))
}
mstore(add(_target, add(32, mload(_target))), 0)
}
resultPointer = _bytesPointer + _bytesLength;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
/**
* @notice Library to recover address and verify signatures
* @dev Simple wrapper for `ecrecover`
*/
library SignatureVerifier {
enum HashAlgorithm {KECCAK256, SHA256, RIPEMD160}
// Header for Version E as defined by EIP191. First byte ('E') is also the version
bytes25 constant EIP191_VERSION_E_HEADER = "Ethereum Signed Message:\n";
/**
* @notice Recover signer address from hash and signature
* @param _hash 32 bytes message hash
* @param _signature Signature of hash - 32 bytes r + 32 bytes s + 1 byte v (could be 0, 1, 27, 28)
*/
function recover(bytes32 _hash, bytes memory _signature)
internal
pure
returns (address)
{
require(_signature.length == 65);
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(_signature, 32))
s := mload(add(_signature, 64))
v := byte(0, mload(add(_signature, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
require(v == 27 || v == 28);
return ecrecover(_hash, v, r, s);
}
/**
* @notice Transform public key to address
* @param _publicKey secp256k1 public key
*/
function toAddress(bytes memory _publicKey) internal pure returns (address) {
return address(uint160(uint256(keccak256(_publicKey))));
}
/**
* @notice Hash using one of pre built hashing algorithm
* @param _message Signed message
* @param _algorithm Hashing algorithm
*/
function hash(bytes memory _message, HashAlgorithm _algorithm)
internal
pure
returns (bytes32 result)
{
if (_algorithm == HashAlgorithm.KECCAK256) {
result = keccak256(_message);
} else if (_algorithm == HashAlgorithm.SHA256) {
result = sha256(_message);
} else {
result = ripemd160(_message);
}
}
/**
* @notice Verify ECDSA signature
* @dev Uses one of pre built hashing algorithm
* @param _message Signed message
* @param _signature Signature of message hash
* @param _publicKey secp256k1 public key in uncompressed format without prefix byte (64 bytes)
* @param _algorithm Hashing algorithm
*/
function verify(
bytes memory _message,
bytes memory _signature,
bytes memory _publicKey,
HashAlgorithm _algorithm
)
internal
pure
returns (bool)
{
require(_publicKey.length == 64);
return toAddress(_publicKey) == recover(hash(_message, _algorithm), _signature);
}
/**
* @notice Hash message according to EIP191 signature specification
* @dev It always assumes Keccak256 is used as hashing algorithm
* @dev Only supports version 0 and version E (0x45)
* @param _message Message to sign
* @param _version EIP191 version to use
*/
function hashEIP191(
bytes memory _message,
byte _version
)
internal
view
returns (bytes32 result)
{
if(_version == byte(0x00)){ // Version 0: Data with intended validator
address validator = address(this);
return keccak256(abi.encodePacked(byte(0x19), byte(0x00), validator, _message));
} else if (_version == byte(0x45)){ // Version E: personal_sign messages
uint256 length = _message.length;
require(length > 0, "Empty message not allowed for version E");
// Compute text-encoded length of message
uint256 digits = 0;
while (length != 0) {
digits++;
length /= 10;
}
bytes memory lengthAsText = new bytes(digits);
length = _message.length;
uint256 index = digits - 1;
while (length != 0) {
lengthAsText[index--] = byte(uint8(48 + length % 10));
length /= 10;
}
return keccak256(abi.encodePacked(byte(0x19), EIP191_VERSION_E_HEADER, lengthAsText, _message));
} else {
revert("Unsupported EIP191 version");
}
}
/**
* @notice Verify EIP191 signature
* @dev It always assumes Keccak256 is used as hashing algorithm
* @dev Only supports version 0 and version E (0x45)
* @param _message Signed message
* @param _signature Signature of message hash
* @param _publicKey secp256k1 public key in uncompressed format without prefix byte (64 bytes)
* @param _version EIP191 version to use
*/
function verifyEIP191(
bytes memory _message,
bytes memory _signature,
bytes memory _publicKey,
byte _version
)
internal
view
returns (bool)
{
require(_publicKey.length == 64);
return toAddress(_publicKey) == recover(hashEIP191(_message, _version), _signature);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../aragon/interfaces/IERC900History.sol";
import "./Issuer.sol";
import "./lib/Bits.sol";
import "./lib/Snapshot.sol";
import "../zeppelin/math/SafeMath.sol";
import "../zeppelin/token/ERC20/SafeERC20.sol";
/**
* @notice PolicyManager interface
*/
interface PolicyManagerInterface {
function secondsPerPeriod() external view returns (uint32);
function register(address _node, uint16 _period) external;
function migrate(address _node) external;
function ping(
address _node,
uint16 _processedPeriod1,
uint16 _processedPeriod2,
uint16 _periodToSetDefault
) external;
}
/**
* @notice Adjudicator interface
*/
interface AdjudicatorInterface {
function rewardCoefficient() external view returns (uint32);
}
/**
* @notice WorkLock interface
*/
interface WorkLockInterface {
function token() external view returns (NuCypherToken);
}
/**
* @title StakingEscrowStub
* @notice Stub is used to deploy main StakingEscrow after all other contract and make some variables immutable
* @dev |v1.0.0|
*/
contract StakingEscrowStub is Upgradeable {
using AdditionalMath for uint32;
NuCypherToken public immutable token;
uint32 public immutable genesisSecondsPerPeriod;
uint32 public immutable secondsPerPeriod;
uint16 public immutable minLockedPeriods;
uint256 public immutable minAllowableLockedTokens;
uint256 public immutable maxAllowableLockedTokens;
/**
* @notice Predefines some variables for use when deploying other contracts
* @param _token Token contract
* @param _genesisHoursPerPeriod Size of period in hours at genesis
* @param _hoursPerPeriod Size of period in hours
* @param _minLockedPeriods Min amount of periods during which tokens can be locked
* @param _minAllowableLockedTokens Min amount of tokens that can be locked
* @param _maxAllowableLockedTokens Max amount of tokens that can be locked
*/
constructor(
NuCypherToken _token,
uint32 _genesisHoursPerPeriod,
uint32 _hoursPerPeriod,
uint16 _minLockedPeriods,
uint256 _minAllowableLockedTokens,
uint256 _maxAllowableLockedTokens
) {
require(_token.totalSupply() > 0 &&
_hoursPerPeriod != 0 &&
_genesisHoursPerPeriod != 0 &&
_genesisHoursPerPeriod <= _hoursPerPeriod &&
_minLockedPeriods > 1 &&
_maxAllowableLockedTokens != 0);
token = _token;
secondsPerPeriod = _hoursPerPeriod.mul32(1 hours);
genesisSecondsPerPeriod = _genesisHoursPerPeriod.mul32(1 hours);
minLockedPeriods = _minLockedPeriods;
minAllowableLockedTokens = _minAllowableLockedTokens;
maxAllowableLockedTokens = _maxAllowableLockedTokens;
}
/// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState`
function verifyState(address _testTarget) public override virtual {
super.verifyState(_testTarget);
// we have to use real values even though this is a stub
require(address(delegateGet(_testTarget, this.token.selector)) == address(token));
// TODO uncomment after merging this PR #2579
// require(uint32(delegateGet(_testTarget, this.genesisSecondsPerPeriod.selector)) == genesisSecondsPerPeriod);
require(uint32(delegateGet(_testTarget, this.secondsPerPeriod.selector)) == secondsPerPeriod);
require(uint16(delegateGet(_testTarget, this.minLockedPeriods.selector)) == minLockedPeriods);
require(delegateGet(_testTarget, this.minAllowableLockedTokens.selector) == minAllowableLockedTokens);
require(delegateGet(_testTarget, this.maxAllowableLockedTokens.selector) == maxAllowableLockedTokens);
}
}
/**
* @title StakingEscrow
* @notice Contract holds and locks stakers tokens.
* Each staker that locks their tokens will receive some compensation
* @dev |v5.7.1|
*/
contract StakingEscrow is Issuer, IERC900History {
using AdditionalMath for uint256;
using AdditionalMath for uint16;
using Bits for uint256;
using SafeMath for uint256;
using Snapshot for uint128[];
using SafeERC20 for NuCypherToken;
/**
* @notice Signals that tokens were deposited
* @param staker Staker address
* @param value Amount deposited (in NuNits)
* @param periods Number of periods tokens will be locked
*/
event Deposited(address indexed staker, uint256 value, uint16 periods);
/**
* @notice Signals that tokens were stake locked
* @param staker Staker address
* @param value Amount locked (in NuNits)
* @param firstPeriod Starting lock period
* @param periods Number of periods tokens will be locked
*/
event Locked(address indexed staker, uint256 value, uint16 firstPeriod, uint16 periods);
/**
* @notice Signals that a sub-stake was divided
* @param staker Staker address
* @param oldValue Old sub-stake value (in NuNits)
* @param lastPeriod Final locked period of old sub-stake
* @param newValue New sub-stake value (in NuNits)
* @param periods Number of periods to extend sub-stake
*/
event Divided(
address indexed staker,
uint256 oldValue,
uint16 lastPeriod,
uint256 newValue,
uint16 periods
);
/**
* @notice Signals that two sub-stakes were merged
* @param staker Staker address
* @param value1 Value of first sub-stake (in NuNits)
* @param value2 Value of second sub-stake (in NuNits)
* @param lastPeriod Final locked period of merged sub-stake
*/
event Merged(address indexed staker, uint256 value1, uint256 value2, uint16 lastPeriod);
/**
* @notice Signals that a sub-stake was prolonged
* @param staker Staker address
* @param value Value of sub-stake
* @param lastPeriod Final locked period of old sub-stake
* @param periods Number of periods sub-stake was extended
*/
event Prolonged(address indexed staker, uint256 value, uint16 lastPeriod, uint16 periods);
/**
* @notice Signals that tokens were withdrawn to the staker
* @param staker Staker address
* @param value Amount withdraws (in NuNits)
*/
event Withdrawn(address indexed staker, uint256 value);
/**
* @notice Signals that the worker associated with the staker made a commitment to next period
* @param staker Staker address
* @param period Period committed to
* @param value Amount of tokens staked for the committed period
*/
event CommitmentMade(address indexed staker, uint16 indexed period, uint256 value);
/**
* @notice Signals that tokens were minted for previous periods
* @param staker Staker address
* @param period Previous period tokens minted for
* @param value Amount minted (in NuNits)
*/
event Minted(address indexed staker, uint16 indexed period, uint256 value);
/**
* @notice Signals that the staker was slashed
* @param staker Staker address
* @param penalty Slashing penalty
* @param investigator Investigator address
* @param reward Value of reward provided to investigator (in NuNits)
*/
event Slashed(address indexed staker, uint256 penalty, address indexed investigator, uint256 reward);
/**
* @notice Signals that the restake parameter was activated/deactivated
* @param staker Staker address
* @param reStake Updated parameter value
*/
event ReStakeSet(address indexed staker, bool reStake);
/**
* @notice Signals that a worker was bonded to the staker
* @param staker Staker address
* @param worker Worker address
* @param startPeriod Period bonding occurred
*/
event WorkerBonded(address indexed staker, address indexed worker, uint16 indexed startPeriod);
/**
* @notice Signals that the winddown parameter was activated/deactivated
* @param staker Staker address
* @param windDown Updated parameter value
*/
event WindDownSet(address indexed staker, bool windDown);
/**
* @notice Signals that the snapshot parameter was activated/deactivated
* @param staker Staker address
* @param snapshotsEnabled Updated parameter value
*/
event SnapshotSet(address indexed staker, bool snapshotsEnabled);
/**
* @notice Signals that the staker migrated their stake to the new period length
* @param staker Staker address
* @param period Period when migration happened
*/
event Migrated(address indexed staker, uint16 indexed period);
/// internal event
event WorkMeasurementSet(address indexed staker, bool measureWork);
struct SubStakeInfo {
uint16 firstPeriod;
uint16 lastPeriod;
uint16 unlockingDuration;
uint128 lockedValue;
}
struct Downtime {
uint16 startPeriod;
uint16 endPeriod;
}
struct StakerInfo {
uint256 value;
/*
* Stores periods that are committed but not yet rewarded.
* In order to optimize storage, only two values are used instead of an array.
* commitToNextPeriod() method invokes mint() method so there can only be two committed
* periods that are not yet rewarded: the current and the next periods.
*/
uint16 currentCommittedPeriod;
uint16 nextCommittedPeriod;
uint16 lastCommittedPeriod;
uint16 stub1; // former slot for lockReStakeUntilPeriod
uint256 completedWork;
uint16 workerStartPeriod; // period when worker was bonded
address worker;
uint256 flags; // uint256 to acquire whole slot and minimize operations on it
uint256 reservedSlot1;
uint256 reservedSlot2;
uint256 reservedSlot3;
uint256 reservedSlot4;
uint256 reservedSlot5;
Downtime[] pastDowntime;
SubStakeInfo[] subStakes;
uint128[] history;
}
// used only for upgrading
uint16 internal constant RESERVED_PERIOD = 0;
uint16 internal constant MAX_CHECKED_VALUES = 5;
// to prevent high gas consumption in loops for slashing
uint16 public constant MAX_SUB_STAKES = 30;
uint16 internal constant MAX_UINT16 = 65535;
// indices for flags
uint8 internal constant RE_STAKE_DISABLED_INDEX = 0;
uint8 internal constant WIND_DOWN_INDEX = 1;
uint8 internal constant MEASURE_WORK_INDEX = 2;
uint8 internal constant SNAPSHOTS_DISABLED_INDEX = 3;
uint8 internal constant MIGRATED_INDEX = 4;
uint16 public immutable minLockedPeriods;
uint16 public immutable minWorkerPeriods;
uint256 public immutable minAllowableLockedTokens;
uint256 public immutable maxAllowableLockedTokens;
PolicyManagerInterface public immutable policyManager;
AdjudicatorInterface public immutable adjudicator;
WorkLockInterface public immutable workLock;
mapping (address => StakerInfo) public stakerInfo;
address[] public stakers;
mapping (address => address) public stakerFromWorker;
mapping (uint16 => uint256) stub4; // former slot for lockedPerPeriod
uint128[] public balanceHistory;
address stub1; // former slot for PolicyManager
address stub2; // former slot for Adjudicator
address stub3; // former slot for WorkLock
mapping (uint16 => uint256) _lockedPerPeriod;
// only to make verifyState from previous version work, temporary
// TODO remove after upgrade #2579
function lockedPerPeriod(uint16 _period) public view returns (uint256) {
return _period != RESERVED_PERIOD ? _lockedPerPeriod[_period] : 111;
}
/**
* @notice Constructor sets address of token contract and coefficients for minting
* @param _token Token contract
* @param _policyManager Policy Manager contract
* @param _adjudicator Adjudicator contract
* @param _workLock WorkLock contract. Zero address if there is no WorkLock
* @param _genesisHoursPerPeriod Size of period in hours at genesis
* @param _hoursPerPeriod Size of period in hours
* @param _issuanceDecayCoefficient (d) Coefficient which modifies the rate at which the maximum issuance decays,
* only applicable to Phase 2. d = 365 * half-life / LOG2 where default half-life = 2.
* See Equation 10 in Staking Protocol & Economics paper
* @param _lockDurationCoefficient1 (k1) Numerator of the coefficient which modifies the extent
* to which a stake's lock duration affects the subsidy it receives. Affects stakers differently.
* Applicable to Phase 1 and Phase 2. k1 = k2 * small_stake_multiplier where default small_stake_multiplier = 0.5.
* See Equation 8 in Staking Protocol & Economics paper.
* @param _lockDurationCoefficient2 (k2) Denominator of the coefficient which modifies the extent
* to which a stake's lock duration affects the subsidy it receives. Affects stakers differently.
* Applicable to Phase 1 and Phase 2. k2 = maximum_rewarded_periods / (1 - small_stake_multiplier)
* where default maximum_rewarded_periods = 365 and default small_stake_multiplier = 0.5.
* See Equation 8 in Staking Protocol & Economics paper.
* @param _maximumRewardedPeriods (kmax) Number of periods beyond which a stake's lock duration
* no longer increases the subsidy it receives. kmax = reward_saturation * 365 where default reward_saturation = 1.
* See Equation 8 in Staking Protocol & Economics paper.
* @param _firstPhaseTotalSupply Total supply for the first phase
* @param _firstPhaseMaxIssuance (Imax) Maximum number of new tokens minted per period during Phase 1.
* See Equation 7 in Staking Protocol & Economics paper.
* @param _minLockedPeriods Min amount of periods during which tokens can be locked
* @param _minAllowableLockedTokens Min amount of tokens that can be locked
* @param _maxAllowableLockedTokens Max amount of tokens that can be locked
* @param _minWorkerPeriods Min amount of periods while a worker can't be changed
*/
constructor(
NuCypherToken _token,
PolicyManagerInterface _policyManager,
AdjudicatorInterface _adjudicator,
WorkLockInterface _workLock,
uint32 _genesisHoursPerPeriod,
uint32 _hoursPerPeriod,
uint256 _issuanceDecayCoefficient,
uint256 _lockDurationCoefficient1,
uint256 _lockDurationCoefficient2,
uint16 _maximumRewardedPeriods,
uint256 _firstPhaseTotalSupply,
uint256 _firstPhaseMaxIssuance,
uint16 _minLockedPeriods,
uint256 _minAllowableLockedTokens,
uint256 _maxAllowableLockedTokens,
uint16 _minWorkerPeriods
)
Issuer(
_token,
_genesisHoursPerPeriod,
_hoursPerPeriod,
_issuanceDecayCoefficient,
_lockDurationCoefficient1,
_lockDurationCoefficient2,
_maximumRewardedPeriods,
_firstPhaseTotalSupply,
_firstPhaseMaxIssuance
)
{
// constant `1` in the expression `_minLockedPeriods > 1` uses to simplify the `lock` method
require(_minLockedPeriods > 1 && _maxAllowableLockedTokens != 0);
minLockedPeriods = _minLockedPeriods;
minAllowableLockedTokens = _minAllowableLockedTokens;
maxAllowableLockedTokens = _maxAllowableLockedTokens;
minWorkerPeriods = _minWorkerPeriods;
require((_policyManager.secondsPerPeriod() == _hoursPerPeriod * (1 hours) ||
_policyManager.secondsPerPeriod() == _genesisHoursPerPeriod * (1 hours)) &&
_adjudicator.rewardCoefficient() != 0 &&
(address(_workLock) == address(0) || _workLock.token() == _token));
policyManager = _policyManager;
adjudicator = _adjudicator;
workLock = _workLock;
}
/**
* @dev Checks the existence of a staker in the contract
*/
modifier onlyStaker()
{
StakerInfo storage info = stakerInfo[msg.sender];
require((info.value > 0 || info.nextCommittedPeriod != 0) &&
info.flags.bitSet(MIGRATED_INDEX));
_;
}
//------------------------Main getters------------------------
/**
* @notice Get all tokens belonging to the staker
*/
function getAllTokens(address _staker) external view returns (uint256) {
return stakerInfo[_staker].value;
}
/**
* @notice Get all flags for the staker
*/
function getFlags(address _staker)
external view returns (
bool windDown,
bool reStake,
bool measureWork,
bool snapshots,
bool migrated
)
{
StakerInfo storage info = stakerInfo[_staker];
windDown = info.flags.bitSet(WIND_DOWN_INDEX);
reStake = !info.flags.bitSet(RE_STAKE_DISABLED_INDEX);
measureWork = info.flags.bitSet(MEASURE_WORK_INDEX);
snapshots = !info.flags.bitSet(SNAPSHOTS_DISABLED_INDEX);
migrated = info.flags.bitSet(MIGRATED_INDEX);
}
/**
* @notice Get the start period. Use in the calculation of the last period of the sub stake
* @param _info Staker structure
* @param _currentPeriod Current period
*/
function getStartPeriod(StakerInfo storage _info, uint16 _currentPeriod)
internal view returns (uint16)
{
// if the next period (after current) is committed
if (_info.flags.bitSet(WIND_DOWN_INDEX) && _info.nextCommittedPeriod > _currentPeriod) {
return _currentPeriod + 1;
}
return _currentPeriod;
}
/**
* @notice Get the last period of the sub stake
* @param _subStake Sub stake structure
* @param _startPeriod Pre-calculated start period
*/
function getLastPeriodOfSubStake(SubStakeInfo storage _subStake, uint16 _startPeriod)
internal view returns (uint16)
{
if (_subStake.lastPeriod != 0) {
return _subStake.lastPeriod;
}
uint32 lastPeriod = uint32(_startPeriod) + _subStake.unlockingDuration;
if (lastPeriod > uint32(MAX_UINT16)) {
return MAX_UINT16;
}
return uint16(lastPeriod);
}
/**
* @notice Get the last period of the sub stake
* @param _staker Staker
* @param _index Stake index
*/
function getLastPeriodOfSubStake(address _staker, uint256 _index)
public view returns (uint16)
{
StakerInfo storage info = stakerInfo[_staker];
SubStakeInfo storage subStake = info.subStakes[_index];
uint16 startPeriod = getStartPeriod(info, getCurrentPeriod());
return getLastPeriodOfSubStake(subStake, startPeriod);
}
/**
* @notice Get the value of locked tokens for a staker in a specified period
* @dev Information may be incorrect for rewarded or not committed surpassed period
* @param _info Staker structure
* @param _currentPeriod Current period
* @param _period Next period
*/
function getLockedTokens(StakerInfo storage _info, uint16 _currentPeriod, uint16 _period)
internal view returns (uint256 lockedValue)
{
lockedValue = 0;
uint16 startPeriod = getStartPeriod(_info, _currentPeriod);
for (uint256 i = 0; i < _info.subStakes.length; i++) {
SubStakeInfo storage subStake = _info.subStakes[i];
if (subStake.firstPeriod <= _period &&
getLastPeriodOfSubStake(subStake, startPeriod) >= _period) {
lockedValue += subStake.lockedValue;
}
}
}
/**
* @notice Get the value of locked tokens for a staker in a future period
* @dev This function is used by PreallocationEscrow so its signature can't be updated.
* @param _staker Staker
* @param _offsetPeriods Amount of periods that will be added to the current period
*/
function getLockedTokens(address _staker, uint16 _offsetPeriods)
external view returns (uint256 lockedValue)
{
StakerInfo storage info = stakerInfo[_staker];
uint16 currentPeriod = getCurrentPeriod();
uint16 nextPeriod = currentPeriod.add16(_offsetPeriods);
return getLockedTokens(info, currentPeriod, nextPeriod);
}
/**
* @notice Get the last committed staker's period
* @param _staker Staker
*/
function getLastCommittedPeriod(address _staker) public view returns (uint16) {
StakerInfo storage info = stakerInfo[_staker];
return info.nextCommittedPeriod != 0 ? info.nextCommittedPeriod : info.lastCommittedPeriod;
}
/**
* @notice Get the value of locked tokens for active stakers in (getCurrentPeriod() + _offsetPeriods) period
* as well as stakers and their locked tokens
* @param _offsetPeriods Amount of periods for locked tokens calculation
* @param _startIndex Start index for looking in stakers array
* @param _maxStakers Max stakers for looking, if set 0 then all will be used
* @return allLockedTokens Sum of locked tokens for active stakers
* @return activeStakers Array of stakers and their locked tokens. Stakers addresses stored as uint256
* @dev Note that activeStakers[0] in an array of uint256, but you want addresses. Careful when used directly!
*/
function getActiveStakers(uint16 _offsetPeriods, uint256 _startIndex, uint256 _maxStakers)
external view returns (uint256 allLockedTokens, uint256[2][] memory activeStakers)
{
require(_offsetPeriods > 0);
uint256 endIndex = stakers.length;
require(_startIndex < endIndex);
if (_maxStakers != 0 && _startIndex + _maxStakers < endIndex) {
endIndex = _startIndex + _maxStakers;
}
activeStakers = new uint256[2][](endIndex - _startIndex);
allLockedTokens = 0;
uint256 resultIndex = 0;
uint16 currentPeriod = getCurrentPeriod();
uint16 nextPeriod = currentPeriod.add16(_offsetPeriods);
for (uint256 i = _startIndex; i < endIndex; i++) {
address staker = stakers[i];
StakerInfo storage info = stakerInfo[staker];
if (info.currentCommittedPeriod != currentPeriod &&
info.nextCommittedPeriod != currentPeriod) {
continue;
}
uint256 lockedTokens = getLockedTokens(info, currentPeriod, nextPeriod);
if (lockedTokens != 0) {
activeStakers[resultIndex][0] = uint256(staker);
activeStakers[resultIndex++][1] = lockedTokens;
allLockedTokens += lockedTokens;
}
}
assembly {
mstore(activeStakers, resultIndex)
}
}
/**
* @notice Get worker using staker's address
*/
function getWorkerFromStaker(address _staker) external view returns (address) {
return stakerInfo[_staker].worker;
}
/**
* @notice Get work that completed by the staker
*/
function getCompletedWork(address _staker) external view returns (uint256) {
return stakerInfo[_staker].completedWork;
}
/**
* @notice Find index of downtime structure that includes specified period
* @dev If specified period is outside all downtime periods, the length of the array will be returned
* @param _staker Staker
* @param _period Specified period number
*/
function findIndexOfPastDowntime(address _staker, uint16 _period) external view returns (uint256 index) {
StakerInfo storage info = stakerInfo[_staker];
for (index = 0; index < info.pastDowntime.length; index++) {
if (_period <= info.pastDowntime[index].endPeriod) {
return index;
}
}
}
//------------------------Main methods------------------------
/**
* @notice Start or stop measuring the work of a staker
* @param _staker Staker
* @param _measureWork Value for `measureWork` parameter
* @return Work that was previously done
*/
function setWorkMeasurement(address _staker, bool _measureWork) external returns (uint256) {
require(msg.sender == address(workLock));
StakerInfo storage info = stakerInfo[_staker];
if (info.flags.bitSet(MEASURE_WORK_INDEX) == _measureWork) {
return info.completedWork;
}
info.flags = info.flags.toggleBit(MEASURE_WORK_INDEX);
emit WorkMeasurementSet(_staker, _measureWork);
return info.completedWork;
}
/**
* @notice Bond worker
* @param _worker Worker address. Must be a real address, not a contract
*/
function bondWorker(address _worker) external onlyStaker {
StakerInfo storage info = stakerInfo[msg.sender];
// Specified worker is already bonded with this staker
require(_worker != info.worker);
uint16 currentPeriod = getCurrentPeriod();
if (info.worker != address(0)) { // If this staker had a worker ...
// Check that enough time has passed to change it
require(currentPeriod >= info.workerStartPeriod.add16(minWorkerPeriods));
// Remove the old relation "worker->staker"
stakerFromWorker[info.worker] = address(0);
}
if (_worker != address(0)) {
// Specified worker is already in use
require(stakerFromWorker[_worker] == address(0));
// Specified worker is a staker
require(stakerInfo[_worker].subStakes.length == 0 || _worker == msg.sender);
// Set new worker->staker relation
stakerFromWorker[_worker] = msg.sender;
}
// Bond new worker (or unbond if _worker == address(0))
info.worker = _worker;
info.workerStartPeriod = currentPeriod;
emit WorkerBonded(msg.sender, _worker, currentPeriod);
}
/**
* @notice Set `reStake` parameter. If true then all staking rewards will be added to locked stake
* @param _reStake Value for parameter
*/
function setReStake(bool _reStake) external {
StakerInfo storage info = stakerInfo[msg.sender];
if (info.flags.bitSet(RE_STAKE_DISABLED_INDEX) == !_reStake) {
return;
}
info.flags = info.flags.toggleBit(RE_STAKE_DISABLED_INDEX);
emit ReStakeSet(msg.sender, _reStake);
}
/**
* @notice Deposit tokens from WorkLock contract
* @param _staker Staker address
* @param _value Amount of tokens to deposit
* @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled
*/
function depositFromWorkLock(
address _staker,
uint256 _value,
uint16 _unlockingDuration
)
external
{
require(msg.sender == address(workLock));
StakerInfo storage info = stakerInfo[_staker];
if (!info.flags.bitSet(WIND_DOWN_INDEX) && info.subStakes.length == 0) {
info.flags = info.flags.toggleBit(WIND_DOWN_INDEX);
emit WindDownSet(_staker, true);
}
// WorkLock still uses the genesis period length (24h)
_unlockingDuration = recalculatePeriod(_unlockingDuration);
deposit(_staker, msg.sender, MAX_SUB_STAKES, _value, _unlockingDuration);
}
/**
* @notice Set `windDown` parameter.
* If true then stake's duration will be decreasing in each period with `commitToNextPeriod()`
* @param _windDown Value for parameter
*/
function setWindDown(bool _windDown) external {
StakerInfo storage info = stakerInfo[msg.sender];
if (info.flags.bitSet(WIND_DOWN_INDEX) == _windDown) {
return;
}
info.flags = info.flags.toggleBit(WIND_DOWN_INDEX);
emit WindDownSet(msg.sender, _windDown);
// duration adjustment if next period is committed
uint16 nextPeriod = getCurrentPeriod() + 1;
if (info.nextCommittedPeriod != nextPeriod) {
return;
}
// adjust sub-stakes duration for the new value of winding down parameter
for (uint256 index = 0; index < info.subStakes.length; index++) {
SubStakeInfo storage subStake = info.subStakes[index];
// sub-stake does not have fixed last period when winding down is disabled
if (!_windDown && subStake.lastPeriod == nextPeriod) {
subStake.lastPeriod = 0;
subStake.unlockingDuration = 1;
continue;
}
// this sub-stake is no longer affected by winding down parameter
if (subStake.lastPeriod != 0 || subStake.unlockingDuration == 0) {
continue;
}
subStake.unlockingDuration = _windDown ? subStake.unlockingDuration - 1 : subStake.unlockingDuration + 1;
if (subStake.unlockingDuration == 0) {
subStake.lastPeriod = nextPeriod;
}
}
}
/**
* @notice Activate/deactivate taking snapshots of balances
* @param _enableSnapshots True to activate snapshots, False to deactivate
*/
function setSnapshots(bool _enableSnapshots) external {
StakerInfo storage info = stakerInfo[msg.sender];
if (info.flags.bitSet(SNAPSHOTS_DISABLED_INDEX) == !_enableSnapshots) {
return;
}
uint256 lastGlobalBalance = uint256(balanceHistory.lastValue());
if(_enableSnapshots){
info.history.addSnapshot(info.value);
balanceHistory.addSnapshot(lastGlobalBalance + info.value);
} else {
info.history.addSnapshot(0);
balanceHistory.addSnapshot(lastGlobalBalance - info.value);
}
info.flags = info.flags.toggleBit(SNAPSHOTS_DISABLED_INDEX);
emit SnapshotSet(msg.sender, _enableSnapshots);
}
/**
* @notice Adds a new snapshot to both the staker and global balance histories,
* assuming the staker's balance was already changed
* @param _info Reference to affected staker's struct
* @param _addition Variance in balance. It can be positive or negative.
*/
function addSnapshot(StakerInfo storage _info, int256 _addition) internal {
if(!_info.flags.bitSet(SNAPSHOTS_DISABLED_INDEX)){
_info.history.addSnapshot(_info.value);
uint256 lastGlobalBalance = uint256(balanceHistory.lastValue());
balanceHistory.addSnapshot(lastGlobalBalance.addSigned(_addition));
}
}
/**
* @notice Implementation of the receiveApproval(address,uint256,address,bytes) method
* (see NuCypherToken contract). Deposit all tokens that were approved to transfer
* @param _from Staker
* @param _value Amount of tokens to deposit
* @param _tokenContract Token contract address
* @notice (param _extraData) Amount of periods during which tokens will be unlocked when wind down is enabled
*/
function receiveApproval(
address _from,
uint256 _value,
address _tokenContract,
bytes calldata /* _extraData */
)
external
{
require(_tokenContract == address(token) && msg.sender == address(token));
// Copy first 32 bytes from _extraData, according to calldata memory layout:
//
// 0x00: method signature 4 bytes
// 0x04: _from 32 bytes after encoding
// 0x24: _value 32 bytes after encoding
// 0x44: _tokenContract 32 bytes after encoding
// 0x64: _extraData pointer 32 bytes. Value must be 0x80 (offset of _extraData wrt to 1st parameter)
// 0x84: _extraData length 32 bytes
// 0xA4: _extraData data Length determined by previous variable
//
// See https://solidity.readthedocs.io/en/latest/abi-spec.html#examples
uint256 payloadSize;
uint256 payload;
assembly {
payloadSize := calldataload(0x84)
payload := calldataload(0xA4)
}
payload = payload >> 8*(32 - payloadSize);
deposit(_from, _from, MAX_SUB_STAKES, _value, uint16(payload));
}
/**
* @notice Deposit tokens and create new sub-stake. Use this method to become a staker
* @param _staker Staker
* @param _value Amount of tokens to deposit
* @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled
*/
function deposit(address _staker, uint256 _value, uint16 _unlockingDuration) external {
deposit(_staker, msg.sender, MAX_SUB_STAKES, _value, _unlockingDuration);
}
/**
* @notice Deposit tokens and increase lock amount of an existing sub-stake
* @dev This is preferable way to stake tokens because will be fewer active sub-stakes in the result
* @param _index Index of the sub stake
* @param _value Amount of tokens which will be locked
*/
function depositAndIncrease(uint256 _index, uint256 _value) external onlyStaker {
require(_index < MAX_SUB_STAKES);
deposit(msg.sender, msg.sender, _index, _value, 0);
}
/**
* @notice Deposit tokens
* @dev Specify either index and zero periods (for an existing sub-stake)
* or index >= MAX_SUB_STAKES and real value for periods (for a new sub-stake), not both
* @param _staker Staker
* @param _payer Owner of tokens
* @param _index Index of the sub stake
* @param _value Amount of tokens to deposit
* @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled
*/
function deposit(address _staker, address _payer, uint256 _index, uint256 _value, uint16 _unlockingDuration) internal {
require(_value != 0);
StakerInfo storage info = stakerInfo[_staker];
// A staker can't be a worker for another staker
require(stakerFromWorker[_staker] == address(0) || stakerFromWorker[_staker] == info.worker);
// initial stake of the staker
if (info.subStakes.length == 0 && info.lastCommittedPeriod == 0) {
stakers.push(_staker);
policyManager.register(_staker, getCurrentPeriod() - 1);
info.flags = info.flags.toggleBit(MIGRATED_INDEX);
}
require(info.flags.bitSet(MIGRATED_INDEX));
token.safeTransferFrom(_payer, address(this), _value);
info.value += _value;
lock(_staker, _index, _value, _unlockingDuration);
addSnapshot(info, int256(_value));
if (_index >= MAX_SUB_STAKES) {
emit Deposited(_staker, _value, _unlockingDuration);
} else {
uint16 lastPeriod = getLastPeriodOfSubStake(_staker, _index);
emit Deposited(_staker, _value, lastPeriod - getCurrentPeriod());
}
}
/**
* @notice Lock some tokens as a new sub-stake
* @param _value Amount of tokens which will be locked
* @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled
*/
function lockAndCreate(uint256 _value, uint16 _unlockingDuration) external onlyStaker {
lock(msg.sender, MAX_SUB_STAKES, _value, _unlockingDuration);
}
/**
* @notice Increase lock amount of an existing sub-stake
* @param _index Index of the sub-stake
* @param _value Amount of tokens which will be locked
*/
function lockAndIncrease(uint256 _index, uint256 _value) external onlyStaker {
require(_index < MAX_SUB_STAKES);
lock(msg.sender, _index, _value, 0);
}
/**
* @notice Lock some tokens as a stake
* @dev Specify either index and zero periods (for an existing sub-stake)
* or index >= MAX_SUB_STAKES and real value for periods (for a new sub-stake), not both
* @param _staker Staker
* @param _index Index of the sub stake
* @param _value Amount of tokens which will be locked
* @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled
*/
function lock(address _staker, uint256 _index, uint256 _value, uint16 _unlockingDuration) internal {
if (_index < MAX_SUB_STAKES) {
require(_value > 0);
} else {
require(_value >= minAllowableLockedTokens && _unlockingDuration >= minLockedPeriods);
}
uint16 currentPeriod = getCurrentPeriod();
uint16 nextPeriod = currentPeriod + 1;
StakerInfo storage info = stakerInfo[_staker];
uint256 lockedTokens = getLockedTokens(info, currentPeriod, nextPeriod);
uint256 requestedLockedTokens = _value.add(lockedTokens);
require(requestedLockedTokens <= info.value && requestedLockedTokens <= maxAllowableLockedTokens);
// next period is committed
if (info.nextCommittedPeriod == nextPeriod) {
_lockedPerPeriod[nextPeriod] += _value;
emit CommitmentMade(_staker, nextPeriod, _value);
}
// if index was provided then increase existing sub-stake
if (_index < MAX_SUB_STAKES) {
lockAndIncrease(info, currentPeriod, nextPeriod, _staker, _index, _value);
// otherwise create new
} else {
lockAndCreate(info, nextPeriod, _staker, _value, _unlockingDuration);
}
}
/**
* @notice Lock some tokens as a new sub-stake
* @param _info Staker structure
* @param _nextPeriod Next period
* @param _staker Staker
* @param _value Amount of tokens which will be locked
* @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled
*/
function lockAndCreate(
StakerInfo storage _info,
uint16 _nextPeriod,
address _staker,
uint256 _value,
uint16 _unlockingDuration
)
internal
{
uint16 duration = _unlockingDuration;
// if winding down is enabled and next period is committed
// then sub-stakes duration were decreased
if (_info.nextCommittedPeriod == _nextPeriod && _info.flags.bitSet(WIND_DOWN_INDEX)) {
duration -= 1;
}
saveSubStake(_info, _nextPeriod, 0, duration, _value);
emit Locked(_staker, _value, _nextPeriod, _unlockingDuration);
}
/**
* @notice Increase lock amount of an existing sub-stake
* @dev Probably will be created a new sub-stake but it will be active only one period
* @param _info Staker structure
* @param _currentPeriod Current period
* @param _nextPeriod Next period
* @param _staker Staker
* @param _index Index of the sub-stake
* @param _value Amount of tokens which will be locked
*/
function lockAndIncrease(
StakerInfo storage _info,
uint16 _currentPeriod,
uint16 _nextPeriod,
address _staker,
uint256 _index,
uint256 _value
)
internal
{
SubStakeInfo storage subStake = _info.subStakes[_index];
(, uint16 lastPeriod) = checkLastPeriodOfSubStake(_info, subStake, _currentPeriod);
// create temporary sub-stake for current or previous committed periods
// to leave locked amount in this period unchanged
if (_info.currentCommittedPeriod != 0 &&
_info.currentCommittedPeriod <= _currentPeriod ||
_info.nextCommittedPeriod != 0 &&
_info.nextCommittedPeriod <= _currentPeriod)
{
saveSubStake(_info, subStake.firstPeriod, _currentPeriod, 0, subStake.lockedValue);
}
subStake.lockedValue += uint128(_value);
// all new locks should start from the next period
subStake.firstPeriod = _nextPeriod;
emit Locked(_staker, _value, _nextPeriod, lastPeriod - _currentPeriod);
}
/**
* @notice Checks that last period of sub-stake is greater than the current period
* @param _info Staker structure
* @param _subStake Sub-stake structure
* @param _currentPeriod Current period
* @return startPeriod Start period. Use in the calculation of the last period of the sub stake
* @return lastPeriod Last period of the sub stake
*/
function checkLastPeriodOfSubStake(
StakerInfo storage _info,
SubStakeInfo storage _subStake,
uint16 _currentPeriod
)
internal view returns (uint16 startPeriod, uint16 lastPeriod)
{
startPeriod = getStartPeriod(_info, _currentPeriod);
lastPeriod = getLastPeriodOfSubStake(_subStake, startPeriod);
// The sub stake must be active at least in the next period
require(lastPeriod > _currentPeriod);
}
/**
* @notice Save sub stake. First tries to override inactive sub stake
* @dev Inactive sub stake means that last period of sub stake has been surpassed and already rewarded
* @param _info Staker structure
* @param _firstPeriod First period of the sub stake
* @param _lastPeriod Last period of the sub stake
* @param _unlockingDuration Duration of the sub stake in periods
* @param _lockedValue Amount of locked tokens
*/
function saveSubStake(
StakerInfo storage _info,
uint16 _firstPeriod,
uint16 _lastPeriod,
uint16 _unlockingDuration,
uint256 _lockedValue
)
internal
{
for (uint256 i = 0; i < _info.subStakes.length; i++) {
SubStakeInfo storage subStake = _info.subStakes[i];
if (subStake.lastPeriod != 0 &&
(_info.currentCommittedPeriod == 0 ||
subStake.lastPeriod < _info.currentCommittedPeriod) &&
(_info.nextCommittedPeriod == 0 ||
subStake.lastPeriod < _info.nextCommittedPeriod))
{
subStake.firstPeriod = _firstPeriod;
subStake.lastPeriod = _lastPeriod;
subStake.unlockingDuration = _unlockingDuration;
subStake.lockedValue = uint128(_lockedValue);
return;
}
}
require(_info.subStakes.length < MAX_SUB_STAKES);
_info.subStakes.push(SubStakeInfo(_firstPeriod, _lastPeriod, _unlockingDuration, uint128(_lockedValue)));
}
/**
* @notice Divide sub stake into two parts
* @param _index Index of the sub stake
* @param _newValue New sub stake value
* @param _additionalDuration Amount of periods for extending sub stake
*/
function divideStake(uint256 _index, uint256 _newValue, uint16 _additionalDuration) external onlyStaker {
StakerInfo storage info = stakerInfo[msg.sender];
require(_newValue >= minAllowableLockedTokens && _additionalDuration > 0);
SubStakeInfo storage subStake = info.subStakes[_index];
uint16 currentPeriod = getCurrentPeriod();
(, uint16 lastPeriod) = checkLastPeriodOfSubStake(info, subStake, currentPeriod);
uint256 oldValue = subStake.lockedValue;
subStake.lockedValue = uint128(oldValue.sub(_newValue));
require(subStake.lockedValue >= minAllowableLockedTokens);
uint16 requestedPeriods = subStake.unlockingDuration.add16(_additionalDuration);
saveSubStake(info, subStake.firstPeriod, 0, requestedPeriods, _newValue);
emit Divided(msg.sender, oldValue, lastPeriod, _newValue, _additionalDuration);
emit Locked(msg.sender, _newValue, subStake.firstPeriod, requestedPeriods);
}
/**
* @notice Prolong active sub stake
* @param _index Index of the sub stake
* @param _additionalDuration Amount of periods for extending sub stake
*/
function prolongStake(uint256 _index, uint16 _additionalDuration) external onlyStaker {
StakerInfo storage info = stakerInfo[msg.sender];
// Incorrect parameters
require(_additionalDuration > 0);
SubStakeInfo storage subStake = info.subStakes[_index];
uint16 currentPeriod = getCurrentPeriod();
(uint16 startPeriod, uint16 lastPeriod) = checkLastPeriodOfSubStake(info, subStake, currentPeriod);
subStake.unlockingDuration = subStake.unlockingDuration.add16(_additionalDuration);
// if the sub stake ends in the next committed period then reset the `lastPeriod` field
if (lastPeriod == startPeriod) {
subStake.lastPeriod = 0;
}
// The extended sub stake must not be less than the minimum value
require(uint32(lastPeriod - currentPeriod) + _additionalDuration >= minLockedPeriods);
emit Locked(msg.sender, subStake.lockedValue, lastPeriod + 1, _additionalDuration);
emit Prolonged(msg.sender, subStake.lockedValue, lastPeriod, _additionalDuration);
}
/**
* @notice Merge two sub-stakes into one if their last periods are equal
* @dev It's possible that both sub-stakes will be active after this transaction.
* But only one of them will be active until next call `commitToNextPeriod` (in the next period)
* @param _index1 Index of the first sub-stake
* @param _index2 Index of the second sub-stake
*/
function mergeStake(uint256 _index1, uint256 _index2) external onlyStaker {
require(_index1 != _index2); // must be different sub-stakes
StakerInfo storage info = stakerInfo[msg.sender];
SubStakeInfo storage subStake1 = info.subStakes[_index1];
SubStakeInfo storage subStake2 = info.subStakes[_index2];
uint16 currentPeriod = getCurrentPeriod();
(, uint16 lastPeriod1) = checkLastPeriodOfSubStake(info, subStake1, currentPeriod);
(, uint16 lastPeriod2) = checkLastPeriodOfSubStake(info, subStake2, currentPeriod);
// both sub-stakes must have equal last period to be mergeable
require(lastPeriod1 == lastPeriod2);
emit Merged(msg.sender, subStake1.lockedValue, subStake2.lockedValue, lastPeriod1);
if (subStake1.firstPeriod == subStake2.firstPeriod) {
subStake1.lockedValue += subStake2.lockedValue;
subStake2.lastPeriod = 1;
subStake2.unlockingDuration = 0;
} else if (subStake1.firstPeriod > subStake2.firstPeriod) {
subStake1.lockedValue += subStake2.lockedValue;
subStake2.lastPeriod = subStake1.firstPeriod - 1;
subStake2.unlockingDuration = 0;
} else {
subStake2.lockedValue += subStake1.lockedValue;
subStake1.lastPeriod = subStake2.firstPeriod - 1;
subStake1.unlockingDuration = 0;
}
}
/**
* @notice Remove unused sub-stake to decrease gas cost for several methods
*/
function removeUnusedSubStake(uint16 _index) external onlyStaker {
StakerInfo storage info = stakerInfo[msg.sender];
uint256 lastIndex = info.subStakes.length - 1;
SubStakeInfo storage subStake = info.subStakes[_index];
require(subStake.lastPeriod != 0 &&
(info.currentCommittedPeriod == 0 ||
subStake.lastPeriod < info.currentCommittedPeriod) &&
(info.nextCommittedPeriod == 0 ||
subStake.lastPeriod < info.nextCommittedPeriod));
if (_index != lastIndex) {
SubStakeInfo storage lastSubStake = info.subStakes[lastIndex];
subStake.firstPeriod = lastSubStake.firstPeriod;
subStake.lastPeriod = lastSubStake.lastPeriod;
subStake.unlockingDuration = lastSubStake.unlockingDuration;
subStake.lockedValue = lastSubStake.lockedValue;
}
info.subStakes.pop();
}
/**
* @notice Withdraw available amount of tokens to staker
* @param _value Amount of tokens to withdraw
*/
function withdraw(uint256 _value) external onlyStaker {
uint16 currentPeriod = getCurrentPeriod();
uint16 nextPeriod = currentPeriod + 1;
StakerInfo storage info = stakerInfo[msg.sender];
// the max locked tokens in most cases will be in the current period
// but when the staker locks more then we should use the next period
uint256 lockedTokens = Math.max(getLockedTokens(info, currentPeriod, nextPeriod),
getLockedTokens(info, currentPeriod, currentPeriod));
require(_value <= info.value.sub(lockedTokens));
info.value -= _value;
addSnapshot(info, - int256(_value));
token.safeTransfer(msg.sender, _value);
emit Withdrawn(msg.sender, _value);
// unbond worker if staker withdraws last portion of NU
if (info.value == 0 &&
info.nextCommittedPeriod == 0 &&
info.worker != address(0))
{
stakerFromWorker[info.worker] = address(0);
info.worker = address(0);
emit WorkerBonded(msg.sender, address(0), currentPeriod);
}
}
/**
* @notice Make a commitment to the next period and mint for the previous period
*/
function commitToNextPeriod() external isInitialized {
address staker = stakerFromWorker[msg.sender];
StakerInfo storage info = stakerInfo[staker];
// Staker must have a stake to make a commitment
require(info.value > 0);
// Only worker with real address can make a commitment
require(msg.sender == tx.origin);
migrate(staker);
uint16 currentPeriod = getCurrentPeriod();
uint16 nextPeriod = currentPeriod + 1;
// the period has already been committed
require(info.nextCommittedPeriod != nextPeriod);
uint16 lastCommittedPeriod = getLastCommittedPeriod(staker);
(uint16 processedPeriod1, uint16 processedPeriod2) = mint(staker);
uint256 lockedTokens = getLockedTokens(info, currentPeriod, nextPeriod);
require(lockedTokens > 0);
_lockedPerPeriod[nextPeriod] += lockedTokens;
info.currentCommittedPeriod = info.nextCommittedPeriod;
info.nextCommittedPeriod = nextPeriod;
decreaseSubStakesDuration(info, nextPeriod);
// staker was inactive for several periods
if (lastCommittedPeriod < currentPeriod) {
info.pastDowntime.push(Downtime(lastCommittedPeriod + 1, currentPeriod));
}
policyManager.ping(staker, processedPeriod1, processedPeriod2, nextPeriod);
emit CommitmentMade(staker, nextPeriod, lockedTokens);
}
/**
* @notice Migrate from the old period length to the new one. Can be done only once
* @param _staker Staker
*/
function migrate(address _staker) public {
StakerInfo storage info = stakerInfo[_staker];
// check that provided address is/was a staker
require(info.subStakes.length != 0 || info.lastCommittedPeriod != 0);
if (info.flags.bitSet(MIGRATED_INDEX)) {
return;
}
// reset state
info.currentCommittedPeriod = 0;
info.nextCommittedPeriod = 0;
// maintain case when no more sub-stakes and need to avoid re-registering this staker during deposit
info.lastCommittedPeriod = 1;
info.workerStartPeriod = recalculatePeriod(info.workerStartPeriod);
delete info.pastDowntime;
// recalculate all sub-stakes
uint16 currentPeriod = getCurrentPeriod();
for (uint256 i = 0; i < info.subStakes.length; i++) {
SubStakeInfo storage subStake = info.subStakes[i];
subStake.firstPeriod = recalculatePeriod(subStake.firstPeriod);
// sub-stake has fixed last period
if (subStake.lastPeriod != 0) {
subStake.lastPeriod = recalculatePeriod(subStake.lastPeriod);
if (subStake.lastPeriod == 0) {
subStake.lastPeriod = 1;
}
subStake.unlockingDuration = 0;
// sub-stake has no fixed ending but possible that with new period length will have
} else {
uint16 oldCurrentPeriod = uint16(block.timestamp / genesisSecondsPerPeriod);
uint16 lastPeriod = recalculatePeriod(oldCurrentPeriod + subStake.unlockingDuration);
subStake.unlockingDuration = lastPeriod - currentPeriod;
if (subStake.unlockingDuration == 0) {
subStake.lastPeriod = lastPeriod;
}
}
}
policyManager.migrate(_staker);
info.flags = info.flags.toggleBit(MIGRATED_INDEX);
emit Migrated(_staker, currentPeriod);
}
/**
* @notice Decrease sub-stakes duration if `windDown` is enabled
*/
function decreaseSubStakesDuration(StakerInfo storage _info, uint16 _nextPeriod) internal {
if (!_info.flags.bitSet(WIND_DOWN_INDEX)) {
return;
}
for (uint256 index = 0; index < _info.subStakes.length; index++) {
SubStakeInfo storage subStake = _info.subStakes[index];
if (subStake.lastPeriod != 0 || subStake.unlockingDuration == 0) {
continue;
}
subStake.unlockingDuration--;
if (subStake.unlockingDuration == 0) {
subStake.lastPeriod = _nextPeriod;
}
}
}
/**
* @notice Mint tokens for previous periods if staker locked their tokens and made a commitment
*/
function mint() external onlyStaker {
// save last committed period to the storage if both periods will be empty after minting
// because we won't be able to calculate last committed period
// see getLastCommittedPeriod(address)
StakerInfo storage info = stakerInfo[msg.sender];
uint16 previousPeriod = getCurrentPeriod() - 1;
if (info.nextCommittedPeriod <= previousPeriod && info.nextCommittedPeriod != 0) {
info.lastCommittedPeriod = info.nextCommittedPeriod;
}
(uint16 processedPeriod1, uint16 processedPeriod2) = mint(msg.sender);
if (processedPeriod1 != 0 || processedPeriod2 != 0) {
policyManager.ping(msg.sender, processedPeriod1, processedPeriod2, 0);
}
}
/**
* @notice Mint tokens for previous periods if staker locked their tokens and made a commitment
* @param _staker Staker
* @return processedPeriod1 Processed period: currentCommittedPeriod or zero
* @return processedPeriod2 Processed period: nextCommittedPeriod or zero
*/
function mint(address _staker) internal returns (uint16 processedPeriod1, uint16 processedPeriod2) {
uint16 currentPeriod = getCurrentPeriod();
uint16 previousPeriod = currentPeriod - 1;
StakerInfo storage info = stakerInfo[_staker];
if (info.nextCommittedPeriod == 0 ||
info.currentCommittedPeriod == 0 &&
info.nextCommittedPeriod > previousPeriod ||
info.currentCommittedPeriod > previousPeriod) {
return (0, 0);
}
uint16 startPeriod = getStartPeriod(info, currentPeriod);
uint256 reward = 0;
bool reStake = !info.flags.bitSet(RE_STAKE_DISABLED_INDEX);
if (info.currentCommittedPeriod != 0) {
reward = mint(info, info.currentCommittedPeriod, currentPeriod, startPeriod, reStake);
processedPeriod1 = info.currentCommittedPeriod;
info.currentCommittedPeriod = 0;
if (reStake) {
_lockedPerPeriod[info.nextCommittedPeriod] += reward;
}
}
if (info.nextCommittedPeriod <= previousPeriod) {
reward += mint(info, info.nextCommittedPeriod, currentPeriod, startPeriod, reStake);
processedPeriod2 = info.nextCommittedPeriod;
info.nextCommittedPeriod = 0;
}
info.value += reward;
if (info.flags.bitSet(MEASURE_WORK_INDEX)) {
info.completedWork += reward;
}
addSnapshot(info, int256(reward));
emit Minted(_staker, previousPeriod, reward);
}
/**
* @notice Calculate reward for one period
* @param _info Staker structure
* @param _mintingPeriod Period for minting calculation
* @param _currentPeriod Current period
* @param _startPeriod Pre-calculated start period
*/
function mint(
StakerInfo storage _info,
uint16 _mintingPeriod,
uint16 _currentPeriod,
uint16 _startPeriod,
bool _reStake
)
internal returns (uint256 reward)
{
reward = 0;
for (uint256 i = 0; i < _info.subStakes.length; i++) {
SubStakeInfo storage subStake = _info.subStakes[i];
uint16 lastPeriod = getLastPeriodOfSubStake(subStake, _startPeriod);
if (subStake.firstPeriod <= _mintingPeriod && lastPeriod >= _mintingPeriod) {
uint256 subStakeReward = mint(
_currentPeriod,
subStake.lockedValue,
_lockedPerPeriod[_mintingPeriod],
lastPeriod.sub16(_mintingPeriod));
reward += subStakeReward;
if (_reStake) {
subStake.lockedValue += uint128(subStakeReward);
}
}
}
return reward;
}
//-------------------------Slashing-------------------------
/**
* @notice Slash the staker's stake and reward the investigator
* @param _staker Staker's address
* @param _penalty Penalty
* @param _investigator Investigator
* @param _reward Reward for the investigator
*/
function slashStaker(
address _staker,
uint256 _penalty,
address _investigator,
uint256 _reward
)
public isInitialized
{
require(msg.sender == address(adjudicator));
require(_penalty > 0);
StakerInfo storage info = stakerInfo[_staker];
require(info.flags.bitSet(MIGRATED_INDEX));
if (info.value <= _penalty) {
_penalty = info.value;
}
info.value -= _penalty;
if (_reward > _penalty) {
_reward = _penalty;
}
uint16 currentPeriod = getCurrentPeriod();
uint16 nextPeriod = currentPeriod + 1;
uint16 startPeriod = getStartPeriod(info, currentPeriod);
(uint256 currentLock, uint256 nextLock, uint256 currentAndNextLock, uint256 shortestSubStakeIndex) =
getLockedTokensAndShortestSubStake(info, currentPeriod, nextPeriod, startPeriod);
// Decrease the stake if amount of locked tokens in the current period more than staker has
uint256 lockedTokens = currentLock + currentAndNextLock;
if (info.value < lockedTokens) {
decreaseSubStakes(info, lockedTokens - info.value, currentPeriod, startPeriod, shortestSubStakeIndex);
}
// Decrease the stake if amount of locked tokens in the next period more than staker has
if (nextLock > 0) {
lockedTokens = nextLock + currentAndNextLock -
(currentAndNextLock > info.value ? currentAndNextLock - info.value : 0);
if (info.value < lockedTokens) {
decreaseSubStakes(info, lockedTokens - info.value, nextPeriod, startPeriod, MAX_SUB_STAKES);
}
}
emit Slashed(_staker, _penalty, _investigator, _reward);
if (_penalty > _reward) {
unMint(_penalty - _reward);
}
// TODO change to withdrawal pattern (#1499)
if (_reward > 0) {
token.safeTransfer(_investigator, _reward);
}
addSnapshot(info, - int256(_penalty));
}
/**
* @notice Get the value of locked tokens for a staker in the current and the next period
* and find the shortest sub stake
* @param _info Staker structure
* @param _currentPeriod Current period
* @param _nextPeriod Next period
* @param _startPeriod Pre-calculated start period
* @return currentLock Amount of tokens that locked in the current period and unlocked in the next period
* @return nextLock Amount of tokens that locked in the next period and not locked in the current period
* @return currentAndNextLock Amount of tokens that locked in the current period and in the next period
* @return shortestSubStakeIndex Index of the shortest sub stake
*/
function getLockedTokensAndShortestSubStake(
StakerInfo storage _info,
uint16 _currentPeriod,
uint16 _nextPeriod,
uint16 _startPeriod
)
internal view returns (
uint256 currentLock,
uint256 nextLock,
uint256 currentAndNextLock,
uint256 shortestSubStakeIndex
)
{
uint16 minDuration = MAX_UINT16;
uint16 minLastPeriod = MAX_UINT16;
shortestSubStakeIndex = MAX_SUB_STAKES;
currentLock = 0;
nextLock = 0;
currentAndNextLock = 0;
for (uint256 i = 0; i < _info.subStakes.length; i++) {
SubStakeInfo storage subStake = _info.subStakes[i];
uint16 lastPeriod = getLastPeriodOfSubStake(subStake, _startPeriod);
if (lastPeriod < subStake.firstPeriod) {
continue;
}
if (subStake.firstPeriod <= _currentPeriod &&
lastPeriod >= _nextPeriod) {
currentAndNextLock += subStake.lockedValue;
} else if (subStake.firstPeriod <= _currentPeriod &&
lastPeriod >= _currentPeriod) {
currentLock += subStake.lockedValue;
} else if (subStake.firstPeriod <= _nextPeriod &&
lastPeriod >= _nextPeriod) {
nextLock += subStake.lockedValue;
}
uint16 duration = lastPeriod - subStake.firstPeriod;
if (subStake.firstPeriod <= _currentPeriod &&
lastPeriod >= _currentPeriod &&
(lastPeriod < minLastPeriod ||
lastPeriod == minLastPeriod && duration < minDuration))
{
shortestSubStakeIndex = i;
minDuration = duration;
minLastPeriod = lastPeriod;
}
}
}
/**
* @notice Decrease short sub stakes
* @param _info Staker structure
* @param _penalty Penalty rate
* @param _decreasePeriod The period when the decrease begins
* @param _startPeriod Pre-calculated start period
* @param _shortestSubStakeIndex Index of the shortest period
*/
function decreaseSubStakes(
StakerInfo storage _info,
uint256 _penalty,
uint16 _decreasePeriod,
uint16 _startPeriod,
uint256 _shortestSubStakeIndex
)
internal
{
SubStakeInfo storage shortestSubStake = _info.subStakes[0];
uint16 minSubStakeLastPeriod = MAX_UINT16;
uint16 minSubStakeDuration = MAX_UINT16;
while(_penalty > 0) {
if (_shortestSubStakeIndex < MAX_SUB_STAKES) {
shortestSubStake = _info.subStakes[_shortestSubStakeIndex];
minSubStakeLastPeriod = getLastPeriodOfSubStake(shortestSubStake, _startPeriod);
minSubStakeDuration = minSubStakeLastPeriod - shortestSubStake.firstPeriod;
_shortestSubStakeIndex = MAX_SUB_STAKES;
} else {
(shortestSubStake, minSubStakeDuration, minSubStakeLastPeriod) =
getShortestSubStake(_info, _decreasePeriod, _startPeriod);
}
if (minSubStakeDuration == MAX_UINT16) {
break;
}
uint256 appliedPenalty = _penalty;
if (_penalty < shortestSubStake.lockedValue) {
shortestSubStake.lockedValue -= uint128(_penalty);
saveOldSubStake(_info, shortestSubStake.firstPeriod, _penalty, _decreasePeriod);
_penalty = 0;
} else {
shortestSubStake.lastPeriod = _decreasePeriod - 1;
_penalty -= shortestSubStake.lockedValue;
appliedPenalty = shortestSubStake.lockedValue;
}
if (_info.currentCommittedPeriod >= _decreasePeriod &&
_info.currentCommittedPeriod <= minSubStakeLastPeriod)
{
_lockedPerPeriod[_info.currentCommittedPeriod] -= appliedPenalty;
}
if (_info.nextCommittedPeriod >= _decreasePeriod &&
_info.nextCommittedPeriod <= minSubStakeLastPeriod)
{
_lockedPerPeriod[_info.nextCommittedPeriod] -= appliedPenalty;
}
}
}
/**
* @notice Get the shortest sub stake
* @param _info Staker structure
* @param _currentPeriod Current period
* @param _startPeriod Pre-calculated start period
* @return shortestSubStake The shortest sub stake
* @return minSubStakeDuration Duration of the shortest sub stake
* @return minSubStakeLastPeriod Last period of the shortest sub stake
*/
function getShortestSubStake(
StakerInfo storage _info,
uint16 _currentPeriod,
uint16 _startPeriod
)
internal view returns (
SubStakeInfo storage shortestSubStake,
uint16 minSubStakeDuration,
uint16 minSubStakeLastPeriod
)
{
shortestSubStake = shortestSubStake;
minSubStakeDuration = MAX_UINT16;
minSubStakeLastPeriod = MAX_UINT16;
for (uint256 i = 0; i < _info.subStakes.length; i++) {
SubStakeInfo storage subStake = _info.subStakes[i];
uint16 lastPeriod = getLastPeriodOfSubStake(subStake, _startPeriod);
if (lastPeriod < subStake.firstPeriod) {
continue;
}
uint16 duration = lastPeriod - subStake.firstPeriod;
if (subStake.firstPeriod <= _currentPeriod &&
lastPeriod >= _currentPeriod &&
(lastPeriod < minSubStakeLastPeriod ||
lastPeriod == minSubStakeLastPeriod && duration < minSubStakeDuration))
{
shortestSubStake = subStake;
minSubStakeDuration = duration;
minSubStakeLastPeriod = lastPeriod;
}
}
}
/**
* @notice Save the old sub stake values to prevent decreasing reward for the previous period
* @dev Saving happens only if the previous period is committed
* @param _info Staker structure
* @param _firstPeriod First period of the old sub stake
* @param _lockedValue Locked value of the old sub stake
* @param _currentPeriod Current period, when the old sub stake is already unlocked
*/
function saveOldSubStake(
StakerInfo storage _info,
uint16 _firstPeriod,
uint256 _lockedValue,
uint16 _currentPeriod
)
internal
{
// Check that the old sub stake should be saved
bool oldCurrentCommittedPeriod = _info.currentCommittedPeriod != 0 &&
_info.currentCommittedPeriod < _currentPeriod;
bool oldnextCommittedPeriod = _info.nextCommittedPeriod != 0 &&
_info.nextCommittedPeriod < _currentPeriod;
bool crosscurrentCommittedPeriod = oldCurrentCommittedPeriod && _info.currentCommittedPeriod >= _firstPeriod;
bool crossnextCommittedPeriod = oldnextCommittedPeriod && _info.nextCommittedPeriod >= _firstPeriod;
if (!crosscurrentCommittedPeriod && !crossnextCommittedPeriod) {
return;
}
// Try to find already existent proper old sub stake
uint16 previousPeriod = _currentPeriod - 1;
for (uint256 i = 0; i < _info.subStakes.length; i++) {
SubStakeInfo storage subStake = _info.subStakes[i];
if (subStake.lastPeriod == previousPeriod &&
((crosscurrentCommittedPeriod ==
(oldCurrentCommittedPeriod && _info.currentCommittedPeriod >= subStake.firstPeriod)) &&
(crossnextCommittedPeriod ==
(oldnextCommittedPeriod && _info.nextCommittedPeriod >= subStake.firstPeriod))))
{
subStake.lockedValue += uint128(_lockedValue);
return;
}
}
saveSubStake(_info, _firstPeriod, previousPeriod, 0, _lockedValue);
}
//-------------Additional getters for stakers info-------------
/**
* @notice Return the length of the array of stakers
*/
function getStakersLength() external view returns (uint256) {
return stakers.length;
}
/**
* @notice Return the length of the array of sub stakes
*/
function getSubStakesLength(address _staker) external view returns (uint256) {
return stakerInfo[_staker].subStakes.length;
}
/**
* @notice Return the information about sub stake
*/
function getSubStakeInfo(address _staker, uint256 _index)
// TODO change to structure when ABIEncoderV2 is released (#1501)
// public view returns (SubStakeInfo)
// TODO "virtual" only for tests, probably will be removed after #1512
external view virtual returns (
uint16 firstPeriod,
uint16 lastPeriod,
uint16 unlockingDuration,
uint128 lockedValue
)
{
SubStakeInfo storage info = stakerInfo[_staker].subStakes[_index];
firstPeriod = info.firstPeriod;
lastPeriod = info.lastPeriod;
unlockingDuration = info.unlockingDuration;
lockedValue = info.lockedValue;
}
/**
* @notice Return the length of the array of past downtime
*/
function getPastDowntimeLength(address _staker) external view returns (uint256) {
return stakerInfo[_staker].pastDowntime.length;
}
/**
* @notice Return the information about past downtime
*/
function getPastDowntime(address _staker, uint256 _index)
// TODO change to structure when ABIEncoderV2 is released (#1501)
// public view returns (Downtime)
external view returns (uint16 startPeriod, uint16 endPeriod)
{
Downtime storage downtime = stakerInfo[_staker].pastDowntime[_index];
startPeriod = downtime.startPeriod;
endPeriod = downtime.endPeriod;
}
//------------------ ERC900 connectors ----------------------
function totalStakedForAt(address _owner, uint256 _blockNumber) public view override returns (uint256){
return stakerInfo[_owner].history.getValueAt(_blockNumber);
}
function totalStakedAt(uint256 _blockNumber) public view override returns (uint256){
return balanceHistory.getValueAt(_blockNumber);
}
function supportsHistory() external pure override returns (bool){
return true;
}
//------------------------Upgradeable------------------------
/**
* @dev Get StakerInfo structure by delegatecall
*/
function delegateGetStakerInfo(address _target, bytes32 _staker)
internal returns (StakerInfo memory result)
{
bytes32 memoryAddress = delegateGetData(_target, this.stakerInfo.selector, 1, _staker, 0);
assembly {
result := memoryAddress
}
}
/**
* @dev Get SubStakeInfo structure by delegatecall
*/
function delegateGetSubStakeInfo(address _target, bytes32 _staker, uint256 _index)
internal returns (SubStakeInfo memory result)
{
bytes32 memoryAddress = delegateGetData(
_target, this.getSubStakeInfo.selector, 2, _staker, bytes32(_index));
assembly {
result := memoryAddress
}
}
/**
* @dev Get Downtime structure by delegatecall
*/
function delegateGetPastDowntime(address _target, bytes32 _staker, uint256 _index)
internal returns (Downtime memory result)
{
bytes32 memoryAddress = delegateGetData(
_target, this.getPastDowntime.selector, 2, _staker, bytes32(_index));
assembly {
result := memoryAddress
}
}
/// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState`
function verifyState(address _testTarget) public override virtual {
super.verifyState(_testTarget);
require(delegateGet(_testTarget, this.lockedPerPeriod.selector,
bytes32(bytes2(RESERVED_PERIOD))) == lockedPerPeriod(RESERVED_PERIOD));
require(address(delegateGet(_testTarget, this.stakerFromWorker.selector, bytes32(0))) ==
stakerFromWorker[address(0)]);
require(delegateGet(_testTarget, this.getStakersLength.selector) == stakers.length);
if (stakers.length == 0) {
return;
}
address stakerAddress = stakers[0];
require(address(uint160(delegateGet(_testTarget, this.stakers.selector, 0))) == stakerAddress);
StakerInfo storage info = stakerInfo[stakerAddress];
bytes32 staker = bytes32(uint256(stakerAddress));
StakerInfo memory infoToCheck = delegateGetStakerInfo(_testTarget, staker);
require(infoToCheck.value == info.value &&
infoToCheck.currentCommittedPeriod == info.currentCommittedPeriod &&
infoToCheck.nextCommittedPeriod == info.nextCommittedPeriod &&
infoToCheck.flags == info.flags &&
infoToCheck.lastCommittedPeriod == info.lastCommittedPeriod &&
infoToCheck.completedWork == info.completedWork &&
infoToCheck.worker == info.worker &&
infoToCheck.workerStartPeriod == info.workerStartPeriod);
require(delegateGet(_testTarget, this.getPastDowntimeLength.selector, staker) ==
info.pastDowntime.length);
for (uint256 i = 0; i < info.pastDowntime.length && i < MAX_CHECKED_VALUES; i++) {
Downtime storage downtime = info.pastDowntime[i];
Downtime memory downtimeToCheck = delegateGetPastDowntime(_testTarget, staker, i);
require(downtimeToCheck.startPeriod == downtime.startPeriod &&
downtimeToCheck.endPeriod == downtime.endPeriod);
}
require(delegateGet(_testTarget, this.getSubStakesLength.selector, staker) == info.subStakes.length);
for (uint256 i = 0; i < info.subStakes.length && i < MAX_CHECKED_VALUES; i++) {
SubStakeInfo storage subStakeInfo = info.subStakes[i];
SubStakeInfo memory subStakeInfoToCheck = delegateGetSubStakeInfo(_testTarget, staker, i);
require(subStakeInfoToCheck.firstPeriod == subStakeInfo.firstPeriod &&
subStakeInfoToCheck.lastPeriod == subStakeInfo.lastPeriod &&
subStakeInfoToCheck.unlockingDuration == subStakeInfo.unlockingDuration &&
subStakeInfoToCheck.lockedValue == subStakeInfo.lockedValue);
}
// it's not perfect because checks not only slot value but also decoding
// at least without additional functions
require(delegateGet(_testTarget, this.totalStakedForAt.selector, staker, bytes32(block.number)) ==
totalStakedForAt(stakerAddress, block.number));
require(delegateGet(_testTarget, this.totalStakedAt.selector, bytes32(block.number)) ==
totalStakedAt(block.number));
if (info.worker != address(0)) {
require(address(delegateGet(_testTarget, this.stakerFromWorker.selector, bytes32(uint256(info.worker)))) ==
stakerFromWorker[info.worker]);
}
}
/// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade`
function finishUpgrade(address _target) public override virtual {
super.finishUpgrade(_target);
// Create fake period
_lockedPerPeriod[RESERVED_PERIOD] = 111;
// Create fake worker
stakerFromWorker[address(0)] = address(this);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.7.0;
// Minimum interface to interact with Aragon's Aggregator
interface IERC900History {
function totalStakedForAt(address addr, uint256 blockNumber) external view returns (uint256);
function totalStakedAt(uint256 blockNumber) external view returns (uint256);
function supportsHistory() external pure returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "./NuCypherToken.sol";
import "../zeppelin/math/Math.sol";
import "./proxy/Upgradeable.sol";
import "./lib/AdditionalMath.sol";
import "../zeppelin/token/ERC20/SafeERC20.sol";
/**
* @title Issuer
* @notice Contract for calculation of issued tokens
* @dev |v3.4.1|
*/
abstract contract Issuer is Upgradeable {
using SafeERC20 for NuCypherToken;
using AdditionalMath for uint32;
event Donated(address indexed sender, uint256 value);
/// Issuer is initialized with a reserved reward
event Initialized(uint256 reservedReward);
uint128 constant MAX_UINT128 = uint128(0) - 1;
NuCypherToken public immutable token;
uint128 public immutable totalSupply;
// d * k2
uint256 public immutable mintingCoefficient;
// k1
uint256 public immutable lockDurationCoefficient1;
// k2
uint256 public immutable lockDurationCoefficient2;
uint32 public immutable genesisSecondsPerPeriod;
uint32 public immutable secondsPerPeriod;
// kmax
uint16 public immutable maximumRewardedPeriods;
uint256 public immutable firstPhaseMaxIssuance;
uint256 public immutable firstPhaseTotalSupply;
/**
* Current supply is used in the minting formula and is stored to prevent different calculation
* for stakers which get reward in the same period. There are two values -
* supply for previous period (used in formula) and supply for current period which accumulates value
* before end of period.
*/
uint128 public previousPeriodSupply;
uint128 public currentPeriodSupply;
uint16 public currentMintingPeriod;
/**
* @notice Constructor sets address of token contract and coefficients for minting
* @dev Minting formula for one sub-stake in one period for the first phase
firstPhaseMaxIssuance * (lockedValue / totalLockedValue) * (k1 + min(allLockedPeriods, kmax)) / k2
* @dev Minting formula for one sub-stake in one period for the second phase
(totalSupply - currentSupply) / d * (lockedValue / totalLockedValue) * (k1 + min(allLockedPeriods, kmax)) / k2
if allLockedPeriods > maximumRewardedPeriods then allLockedPeriods = maximumRewardedPeriods
* @param _token Token contract
* @param _genesisHoursPerPeriod Size of period in hours at genesis
* @param _hoursPerPeriod Size of period in hours
* @param _issuanceDecayCoefficient (d) Coefficient which modifies the rate at which the maximum issuance decays,
* only applicable to Phase 2. d = 365 * half-life / LOG2 where default half-life = 2.
* See Equation 10 in Staking Protocol & Economics paper
* @param _lockDurationCoefficient1 (k1) Numerator of the coefficient which modifies the extent
* to which a stake's lock duration affects the subsidy it receives. Affects stakers differently.
* Applicable to Phase 1 and Phase 2. k1 = k2 * small_stake_multiplier where default small_stake_multiplier = 0.5.
* See Equation 8 in Staking Protocol & Economics paper.
* @param _lockDurationCoefficient2 (k2) Denominator of the coefficient which modifies the extent
* to which a stake's lock duration affects the subsidy it receives. Affects stakers differently.
* Applicable to Phase 1 and Phase 2. k2 = maximum_rewarded_periods / (1 - small_stake_multiplier)
* where default maximum_rewarded_periods = 365 and default small_stake_multiplier = 0.5.
* See Equation 8 in Staking Protocol & Economics paper.
* @param _maximumRewardedPeriods (kmax) Number of periods beyond which a stake's lock duration
* no longer increases the subsidy it receives. kmax = reward_saturation * 365 where default reward_saturation = 1.
* See Equation 8 in Staking Protocol & Economics paper.
* @param _firstPhaseTotalSupply Total supply for the first phase
* @param _firstPhaseMaxIssuance (Imax) Maximum number of new tokens minted per period during Phase 1.
* See Equation 7 in Staking Protocol & Economics paper.
*/
constructor(
NuCypherToken _token,
uint32 _genesisHoursPerPeriod,
uint32 _hoursPerPeriod,
uint256 _issuanceDecayCoefficient,
uint256 _lockDurationCoefficient1,
uint256 _lockDurationCoefficient2,
uint16 _maximumRewardedPeriods,
uint256 _firstPhaseTotalSupply,
uint256 _firstPhaseMaxIssuance
) {
uint256 localTotalSupply = _token.totalSupply();
require(localTotalSupply > 0 &&
_issuanceDecayCoefficient != 0 &&
_hoursPerPeriod != 0 &&
_genesisHoursPerPeriod != 0 &&
_genesisHoursPerPeriod <= _hoursPerPeriod &&
_lockDurationCoefficient1 != 0 &&
_lockDurationCoefficient2 != 0 &&
_maximumRewardedPeriods != 0);
require(localTotalSupply <= uint256(MAX_UINT128), "Token contract has supply more than supported");
uint256 maxLockDurationCoefficient = _maximumRewardedPeriods + _lockDurationCoefficient1;
uint256 localMintingCoefficient = _issuanceDecayCoefficient * _lockDurationCoefficient2;
require(maxLockDurationCoefficient > _maximumRewardedPeriods &&
localMintingCoefficient / _issuanceDecayCoefficient == _lockDurationCoefficient2 &&
// worst case for `totalLockedValue * d * k2`, when totalLockedValue == totalSupply
localTotalSupply * localMintingCoefficient / localTotalSupply == localMintingCoefficient &&
// worst case for `(totalSupply - currentSupply) * lockedValue * (k1 + min(allLockedPeriods, kmax))`,
// when currentSupply == 0, lockedValue == totalSupply
localTotalSupply * localTotalSupply * maxLockDurationCoefficient / localTotalSupply / localTotalSupply ==
maxLockDurationCoefficient,
"Specified parameters cause overflow");
require(maxLockDurationCoefficient <= _lockDurationCoefficient2,
"Resulting locking duration coefficient must be less than 1");
require(_firstPhaseTotalSupply <= localTotalSupply, "Too many tokens for the first phase");
require(_firstPhaseMaxIssuance <= _firstPhaseTotalSupply, "Reward for the first phase is too high");
token = _token;
secondsPerPeriod = _hoursPerPeriod.mul32(1 hours);
genesisSecondsPerPeriod = _genesisHoursPerPeriod.mul32(1 hours);
lockDurationCoefficient1 = _lockDurationCoefficient1;
lockDurationCoefficient2 = _lockDurationCoefficient2;
maximumRewardedPeriods = _maximumRewardedPeriods;
firstPhaseTotalSupply = _firstPhaseTotalSupply;
firstPhaseMaxIssuance = _firstPhaseMaxIssuance;
totalSupply = uint128(localTotalSupply);
mintingCoefficient = localMintingCoefficient;
}
/**
* @dev Checks contract initialization
*/
modifier isInitialized()
{
require(currentMintingPeriod != 0);
_;
}
/**
* @return Number of current period
*/
function getCurrentPeriod() public view returns (uint16) {
return uint16(block.timestamp / secondsPerPeriod);
}
/**
* @return Recalculate period value using new basis
*/
function recalculatePeriod(uint16 _period) internal view returns (uint16) {
return uint16(uint256(_period) * genesisSecondsPerPeriod / secondsPerPeriod);
}
/**
* @notice Initialize reserved tokens for reward
*/
function initialize(uint256 _reservedReward, address _sourceOfFunds) external onlyOwner {
require(currentMintingPeriod == 0);
// Reserved reward must be sufficient for at least one period of the first phase
require(firstPhaseMaxIssuance <= _reservedReward);
currentMintingPeriod = getCurrentPeriod();
currentPeriodSupply = totalSupply - uint128(_reservedReward);
previousPeriodSupply = currentPeriodSupply;
token.safeTransferFrom(_sourceOfFunds, address(this), _reservedReward);
emit Initialized(_reservedReward);
}
/**
* @notice Function to mint tokens for one period.
* @param _currentPeriod Current period number.
* @param _lockedValue The amount of tokens that were locked by user in specified period.
* @param _totalLockedValue The amount of tokens that were locked by all users in specified period.
* @param _allLockedPeriods The max amount of periods during which tokens will be locked after specified period.
* @return amount Amount of minted tokens.
*/
function mint(
uint16 _currentPeriod,
uint256 _lockedValue,
uint256 _totalLockedValue,
uint16 _allLockedPeriods
)
internal returns (uint256 amount)
{
if (currentPeriodSupply == totalSupply) {
return 0;
}
if (_currentPeriod > currentMintingPeriod) {
previousPeriodSupply = currentPeriodSupply;
currentMintingPeriod = _currentPeriod;
}
uint256 currentReward;
uint256 coefficient;
// first phase
// firstPhaseMaxIssuance * lockedValue * (k1 + min(allLockedPeriods, kmax)) / (totalLockedValue * k2)
if (previousPeriodSupply + firstPhaseMaxIssuance <= firstPhaseTotalSupply) {
currentReward = firstPhaseMaxIssuance;
coefficient = lockDurationCoefficient2;
// second phase
// (totalSupply - currentSupply) * lockedValue * (k1 + min(allLockedPeriods, kmax)) / (totalLockedValue * d * k2)
} else {
currentReward = totalSupply - previousPeriodSupply;
coefficient = mintingCoefficient;
}
uint256 allLockedPeriods =
AdditionalMath.min16(_allLockedPeriods, maximumRewardedPeriods) + lockDurationCoefficient1;
amount = (uint256(currentReward) * _lockedValue * allLockedPeriods) /
(_totalLockedValue * coefficient);
// rounding the last reward
uint256 maxReward = getReservedReward();
if (amount == 0) {
amount = 1;
} else if (amount > maxReward) {
amount = maxReward;
}
currentPeriodSupply += uint128(amount);
}
/**
* @notice Return tokens for future minting
* @param _amount Amount of tokens
*/
function unMint(uint256 _amount) internal {
previousPeriodSupply -= uint128(_amount);
currentPeriodSupply -= uint128(_amount);
}
/**
* @notice Donate sender's tokens. Amount of tokens will be returned for future minting
* @param _value Amount to donate
*/
function donate(uint256 _value) external isInitialized {
token.safeTransferFrom(msg.sender, address(this), _value);
unMint(_value);
emit Donated(msg.sender, _value);
}
/**
* @notice Returns the number of tokens that can be minted
*/
function getReservedReward() public view returns (uint256) {
return totalSupply - currentPeriodSupply;
}
/// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState`
function verifyState(address _testTarget) public override virtual {
super.verifyState(_testTarget);
require(uint16(delegateGet(_testTarget, this.currentMintingPeriod.selector)) == currentMintingPeriod);
require(uint128(delegateGet(_testTarget, this.previousPeriodSupply.selector)) == previousPeriodSupply);
require(uint128(delegateGet(_testTarget, this.currentPeriodSupply.selector)) == currentPeriodSupply);
}
/// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade`
function finishUpgrade(address _target) public override virtual {
super.finishUpgrade(_target);
// recalculate currentMintingPeriod if needed
if (currentMintingPeriod > getCurrentPeriod()) {
currentMintingPeriod = recalculatePeriod(currentMintingPeriod);
}
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../zeppelin/token/ERC20/ERC20.sol";
import "../zeppelin/token/ERC20/ERC20Detailed.sol";
/**
* @title NuCypherToken
* @notice ERC20 token
* @dev Optional approveAndCall() functionality to notify a contract if an approve() has occurred.
*/
contract NuCypherToken is ERC20, ERC20Detailed('NuCypher', 'NU', 18) {
/**
* @notice Set amount of tokens
* @param _totalSupplyOfTokens Total number of tokens
*/
constructor (uint256 _totalSupplyOfTokens) {
_mint(msg.sender, _totalSupplyOfTokens);
}
/**
* @notice Approves and then calls the receiving contract
*
* @dev call the receiveApproval function on the contract you want to be notified.
* receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
*/
function approveAndCall(address _spender, uint256 _value, bytes calldata _extraData)
external returns (bool success)
{
approve(_spender, _value);
TokenRecipient(_spender).receiveApproval(msg.sender, _value, address(this), _extraData);
return true;
}
}
/**
* @dev Interface to use the receiveApproval method
*/
interface TokenRecipient {
/**
* @notice Receives a notification of approval of the transfer
* @param _from Sender of approval
* @param _value The amount of tokens to be spent
* @param _tokenContract Address of the token contract
* @param _extraData Extra data
*/
function receiveApproval(address _from, uint256 _value, address _tokenContract, bytes calldata _extraData) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view override returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowed[owner][spender];
}
/**
* @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 override returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public override 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);
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public override returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC20.sol";
/**
* @title ERC20Detailed token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
abstract contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @title Math
* @dev Assorted math operations
*/
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 Calculates the average of two numbers. Since these are integers,
* averages of an even and odd number cannot be represented, and will be
* rounded down.
*/
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: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../../zeppelin/ownership/Ownable.sol";
/**
* @notice Base contract for upgradeable contract
* @dev Inherited contract should implement verifyState(address) method by checking storage variables
* (see verifyState(address) in Dispatcher). Also contract should implement finishUpgrade(address)
* if it is using constructor parameters by coping this parameters to the dispatcher storage
*/
abstract contract Upgradeable is Ownable {
event StateVerified(address indexed testTarget, address sender);
event UpgradeFinished(address indexed target, address sender);
/**
* @dev Contracts at the target must reserve the same location in storage for this address as in Dispatcher
* Stored data actually lives in the Dispatcher
* However the storage layout is specified here in the implementing contracts
*/
address public target;
/**
* @dev Previous contract address (if available). Used for rollback
*/
address public previousTarget;
/**
* @dev Upgrade status. Explicit `uint8` type is used instead of `bool` to save gas by excluding 0 value
*/
uint8 public isUpgrade;
/**
* @dev Guarantees that next slot will be separated from the previous
*/
uint256 stubSlot;
/**
* @dev Constants for `isUpgrade` field
*/
uint8 constant UPGRADE_FALSE = 1;
uint8 constant UPGRADE_TRUE = 2;
/**
* @dev Checks that function executed while upgrading
* Recommended to add to `verifyState` and `finishUpgrade` methods
*/
modifier onlyWhileUpgrading()
{
require(isUpgrade == UPGRADE_TRUE);
_;
}
/**
* @dev Method for verifying storage state.
* Should check that new target contract returns right storage value
*/
function verifyState(address _testTarget) public virtual onlyWhileUpgrading {
emit StateVerified(_testTarget, msg.sender);
}
/**
* @dev Copy values from the new target to the current storage
* @param _target New target contract address
*/
function finishUpgrade(address _target) public virtual onlyWhileUpgrading {
emit UpgradeFinished(_target, msg.sender);
}
/**
* @dev Base method to get data
* @param _target Target to call
* @param _selector Method selector
* @param _numberOfArguments Number of used arguments
* @param _argument1 First method argument
* @param _argument2 Second method argument
* @return memoryAddress Address in memory where the data is located
*/
function delegateGetData(
address _target,
bytes4 _selector,
uint8 _numberOfArguments,
bytes32 _argument1,
bytes32 _argument2
)
internal returns (bytes32 memoryAddress)
{
assembly {
memoryAddress := mload(0x40)
mstore(memoryAddress, _selector)
if gt(_numberOfArguments, 0) {
mstore(add(memoryAddress, 0x04), _argument1)
}
if gt(_numberOfArguments, 1) {
mstore(add(memoryAddress, 0x24), _argument2)
}
switch delegatecall(gas(), _target, memoryAddress, add(0x04, mul(0x20, _numberOfArguments)), 0, 0)
case 0 {
revert(memoryAddress, 0)
}
default {
returndatacopy(memoryAddress, 0x0, returndatasize())
}
}
}
/**
* @dev Call "getter" without parameters.
* Result should not exceed 32 bytes
*/
function delegateGet(address _target, bytes4 _selector)
internal returns (uint256 result)
{
bytes32 memoryAddress = delegateGetData(_target, _selector, 0, 0, 0);
assembly {
result := mload(memoryAddress)
}
}
/**
* @dev Call "getter" with one parameter.
* Result should not exceed 32 bytes
*/
function delegateGet(address _target, bytes4 _selector, bytes32 _argument)
internal returns (uint256 result)
{
bytes32 memoryAddress = delegateGetData(_target, _selector, 1, _argument, 0);
assembly {
result := mload(memoryAddress)
}
}
/**
* @dev Call "getter" with two parameters.
* Result should not exceed 32 bytes
*/
function delegateGet(
address _target,
bytes4 _selector,
bytes32 _argument1,
bytes32 _argument2
)
internal returns (uint256 result)
{
bytes32 memoryAddress = delegateGetData(_target, _selector, 2, _argument1, _argument2);
assembly {
result := mload(memoryAddress)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
abstract contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public virtual 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;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../../zeppelin/math/SafeMath.sol";
/**
* @notice Additional math operations
*/
library AdditionalMath {
using SafeMath for uint256;
function max16(uint16 a, uint16 b) internal pure returns (uint16) {
return a >= b ? a : b;
}
function min16(uint16 a, uint16 b) internal pure returns (uint16) {
return a < b ? a : b;
}
/**
* @notice Division and ceil
*/
function divCeil(uint256 a, uint256 b) internal pure returns (uint256) {
return (a.add(b) - 1) / b;
}
/**
* @dev Adds signed value to unsigned value, throws on overflow.
*/
function addSigned(uint256 a, int256 b) internal pure returns (uint256) {
if (b >= 0) {
return a.add(uint256(b));
} else {
return a.sub(uint256(-b));
}
}
/**
* @dev Subtracts signed value from unsigned value, throws on overflow.
*/
function subSigned(uint256 a, int256 b) internal pure returns (uint256) {
if (b >= 0) {
return a.sub(uint256(b));
} else {
return a.add(uint256(-b));
}
}
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul32(uint32 a, uint32 b) internal pure returns (uint32) {
if (a == 0) {
return 0;
}
uint32 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add16(uint16 a, uint16 b) internal pure returns (uint16) {
uint16 c = a + b;
assert(c >= a);
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub16(uint16 a, uint16 b) internal pure returns (uint16) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds signed value to unsigned value, throws on overflow.
*/
function addSigned16(uint16 a, int16 b) internal pure returns (uint16) {
if (b >= 0) {
return add16(a, uint16(b));
} else {
return sub16(a, uint16(-b));
}
}
/**
* @dev Subtracts signed value from unsigned value, throws on overflow.
*/
function subSigned16(uint16 a, int16 b) internal pure returns (uint16) {
if (b >= 0) {
return sub16(a, uint16(b));
} else {
return add16(a, uint16(-b));
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
require(token.transfer(to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
require(token.transferFrom(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'
require((value == 0) || (token.allowance(msg.sender, spender) == 0));
require(token.approve(spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
require(token.approve(spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
require(token.approve(spender, newAllowance));
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
/**
* @dev Taken from https://github.com/ethereum/solidity-examples/blob/master/src/bits/Bits.sol
*/
library Bits {
uint256 internal constant ONE = uint256(1);
/**
* @notice Sets the bit at the given 'index' in 'self' to:
* '1' - if the bit is '0'
* '0' - if the bit is '1'
* @return The modified value
*/
function toggleBit(uint256 self, uint8 index) internal pure returns (uint256) {
return self ^ ONE << index;
}
/**
* @notice Get the value of the bit at the given 'index' in 'self'.
*/
function bit(uint256 self, uint8 index) internal pure returns (uint8) {
return uint8(self >> index & 1);
}
/**
* @notice Check if the bit at the given 'index' in 'self' is set.
* @return 'true' - if the value of the bit is '1',
* 'false' - if the value of the bit is '0'
*/
function bitSet(uint256 self, uint8 index) internal pure returns (bool) {
return self >> index & 1 == 1;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
/**
* @title Snapshot
* @notice Manages snapshots of size 128 bits (32 bits for timestamp, 96 bits for value)
* 96 bits is enough for storing NU token values, and 32 bits should be OK for block numbers
* @dev Since each storage slot can hold two snapshots, new slots are allocated every other TX. Thus, gas cost of adding snapshots is 51400 and 36400 gas, alternately.
* Based on Aragon's Checkpointing (https://https://github.com/aragonone/voting-connectors/blob/master/shared/contract-utils/contracts/Checkpointing.sol)
* On average, adding snapshots spends ~6500 less gas than the 256-bit checkpoints of Aragon's Checkpointing
*/
library Snapshot {
function encodeSnapshot(uint32 _time, uint96 _value) internal pure returns(uint128) {
return uint128(uint256(_time) << 96 | uint256(_value));
}
function decodeSnapshot(uint128 _snapshot) internal pure returns(uint32 time, uint96 value){
time = uint32(bytes4(bytes16(_snapshot)));
value = uint96(_snapshot);
}
function addSnapshot(uint128[] storage _self, uint256 _value) internal {
addSnapshot(_self, block.number, _value);
}
function addSnapshot(uint128[] storage _self, uint256 _time, uint256 _value) internal {
uint256 length = _self.length;
if (length != 0) {
(uint32 currentTime, ) = decodeSnapshot(_self[length - 1]);
if (uint32(_time) == currentTime) {
_self[length - 1] = encodeSnapshot(uint32(_time), uint96(_value));
return;
} else if (uint32(_time) < currentTime){
revert();
}
}
_self.push(encodeSnapshot(uint32(_time), uint96(_value)));
}
function lastSnapshot(uint128[] storage _self) internal view returns (uint32, uint96) {
uint256 length = _self.length;
if (length > 0) {
return decodeSnapshot(_self[length - 1]);
}
return (0, 0);
}
function lastValue(uint128[] storage _self) internal view returns (uint96) {
(, uint96 value) = lastSnapshot(_self);
return value;
}
function getValueAt(uint128[] storage _self, uint256 _time256) internal view returns (uint96) {
uint32 _time = uint32(_time256);
uint256 length = _self.length;
// Short circuit if there's no checkpoints yet
// Note that this also lets us avoid using SafeMath later on, as we've established that
// there must be at least one checkpoint
if (length == 0) {
return 0;
}
// Check last checkpoint
uint256 lastIndex = length - 1;
(uint32 snapshotTime, uint96 snapshotValue) = decodeSnapshot(_self[length - 1]);
if (_time >= snapshotTime) {
return snapshotValue;
}
// Check first checkpoint (if not already checked with the above check on last)
(snapshotTime, snapshotValue) = decodeSnapshot(_self[0]);
if (length == 1 || _time < snapshotTime) {
return 0;
}
// Do binary search
// As we've already checked both ends, we don't need to check the last checkpoint again
uint256 low = 0;
uint256 high = lastIndex - 1;
uint32 midTime;
uint96 midValue;
while (high > low) {
uint256 mid = (high + low + 1) / 2; // average, ceil round
(midTime, midValue) = decodeSnapshot(_self[mid]);
if (_time > midTime) {
low = mid;
} else if (_time < midTime) {
// Note that we don't need SafeMath here because mid must always be greater than 0
// from the while condition
high = mid - 1;
} else {
// _time == midTime
return midValue;
}
}
(, snapshotValue) = decodeSnapshot(_self[low]);
return snapshotValue;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.7.0;
interface IForwarder {
function isForwarder() external pure returns (bool);
function canForward(address sender, bytes calldata evmCallScript) external view returns (bool);
function forward(bytes calldata evmCallScript) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.7.0;
interface TokenManager {
function mint(address _receiver, uint256 _amount) external;
function issue(uint256 _amount) external;
function assign(address _receiver, uint256 _amount) external;
function burn(address _holder, uint256 _amount) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.7.0;
import "./IForwarder.sol";
// Interface for Voting contract, as found in https://github.com/aragon/aragon-apps/blob/master/apps/voting/contracts/Voting.sol
interface Voting is IForwarder{
enum VoterState { Absent, Yea, Nay }
// Public getters
function token() external returns (address);
function supportRequiredPct() external returns (uint64);
function minAcceptQuorumPct() external returns (uint64);
function voteTime() external returns (uint64);
function votesLength() external returns (uint256);
// Setters
function changeSupportRequiredPct(uint64 _supportRequiredPct) external;
function changeMinAcceptQuorumPct(uint64 _minAcceptQuorumPct) external;
// Creating new votes
function newVote(bytes calldata _executionScript, string memory _metadata) external returns (uint256 voteId);
function newVote(bytes calldata _executionScript, string memory _metadata, bool _castVote, bool _executesIfDecided)
external returns (uint256 voteId);
// Voting
function canVote(uint256 _voteId, address _voter) external view returns (bool);
function vote(uint256 _voteId, bool _supports, bool _executesIfDecided) external;
// Executing a passed vote
function canExecute(uint256 _voteId) external view returns (bool);
function executeVote(uint256 _voteId) external;
// Additional info
function getVote(uint256 _voteId) external view
returns (
bool open,
bool executed,
uint64 startDate,
uint64 snapshotBlock,
uint64 supportRequired,
uint64 minAcceptQuorum,
uint256 yea,
uint256 nay,
uint256 votingPower,
bytes memory script
);
function getVoterState(uint256 _voteId, address _voter) external view returns (VoterState);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../zeppelin/math/SafeMath.sol";
/**
* @notice Multi-signature contract with off-chain signing
*/
contract MultiSig {
using SafeMath for uint256;
event Executed(address indexed sender, uint256 indexed nonce, address indexed destination, uint256 value);
event OwnerAdded(address indexed owner);
event OwnerRemoved(address indexed owner);
event RequirementChanged(uint16 required);
uint256 constant public MAX_OWNER_COUNT = 50;
uint256 public nonce;
uint8 public required;
mapping (address => bool) public isOwner;
address[] public owners;
/**
* @notice Only this contract can call method
*/
modifier onlyThisContract() {
require(msg.sender == address(this));
_;
}
receive() external payable {}
/**
* @param _required Number of required signings
* @param _owners List of initial owners.
*/
constructor (uint8 _required, address[] memory _owners) {
require(_owners.length <= MAX_OWNER_COUNT &&
_required <= _owners.length &&
_required > 0);
for (uint256 i = 0; i < _owners.length; i++) {
address owner = _owners[i];
require(!isOwner[owner] && owner != address(0));
isOwner[owner] = true;
}
owners = _owners;
required = _required;
}
/**
* @notice Get unsigned hash for transaction parameters
* @dev Follows ERC191 signature scheme: https://github.com/ethereum/EIPs/issues/191
* @param _sender Trustee who will execute the transaction
* @param _destination Destination address
* @param _value Amount of ETH to transfer
* @param _data Call data
* @param _nonce Nonce
*/
function getUnsignedTransactionHash(
address _sender,
address _destination,
uint256 _value,
bytes memory _data,
uint256 _nonce
)
public view returns (bytes32)
{
return keccak256(
abi.encodePacked(byte(0x19), byte(0), address(this), _sender, _destination, _value, _data, _nonce));
}
/**
* @dev Note that address recovered from signatures must be strictly increasing
* @param _sigV Array of signatures values V
* @param _sigR Array of signatures values R
* @param _sigS Array of signatures values S
* @param _destination Destination address
* @param _value Amount of ETH to transfer
* @param _data Call data
*/
function execute(
uint8[] calldata _sigV,
bytes32[] calldata _sigR,
bytes32[] calldata _sigS,
address _destination,
uint256 _value,
bytes calldata _data
)
external
{
require(_sigR.length >= required &&
_sigR.length == _sigS.length &&
_sigR.length == _sigV.length);
bytes32 txHash = getUnsignedTransactionHash(msg.sender, _destination, _value, _data, nonce);
address lastAdd = address(0);
for (uint256 i = 0; i < _sigR.length; i++) {
address recovered = ecrecover(txHash, _sigV[i], _sigR[i], _sigS[i]);
require(recovered > lastAdd && isOwner[recovered]);
lastAdd = recovered;
}
emit Executed(msg.sender, nonce, _destination, _value);
nonce = nonce.add(1);
(bool callSuccess,) = _destination.call{value: _value}(_data);
require(callSuccess);
}
/**
* @notice Allows to add a new owner
* @dev Transaction has to be sent by `execute` method.
* @param _owner Address of new owner
*/
function addOwner(address _owner)
external
onlyThisContract
{
require(owners.length < MAX_OWNER_COUNT &&
_owner != address(0) &&
!isOwner[_owner]);
isOwner[_owner] = true;
owners.push(_owner);
emit OwnerAdded(_owner);
}
/**
* @notice Allows to remove an owner
* @dev Transaction has to be sent by `execute` method.
* @param _owner Address of owner
*/
function removeOwner(address _owner)
external
onlyThisContract
{
require(owners.length > required && isOwner[_owner]);
isOwner[_owner] = false;
for (uint256 i = 0; i < owners.length - 1; i++) {
if (owners[i] == _owner) {
owners[i] = owners[owners.length - 1];
break;
}
}
owners.pop();
emit OwnerRemoved(_owner);
}
/**
* @notice Returns the number of owners of this MultiSig
*/
function getNumberOfOwners() external view returns (uint256) {
return owners.length;
}
/**
* @notice Allows to change the number of required signatures
* @dev Transaction has to be sent by `execute` method
* @param _required Number of required signatures
*/
function changeRequirement(uint8 _required)
external
onlyThisContract
{
require(_required <= owners.length && _required > 0);
required = _required;
emit RequirementChanged(_required);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../zeppelin/token/ERC20/SafeERC20.sol";
import "../zeppelin/math/SafeMath.sol";
import "../zeppelin/math/Math.sol";
import "../zeppelin/utils/Address.sol";
import "./lib/AdditionalMath.sol";
import "./lib/SignatureVerifier.sol";
import "./StakingEscrow.sol";
import "./NuCypherToken.sol";
import "./proxy/Upgradeable.sol";
/**
* @title PolicyManager
* @notice Contract holds policy data and locks accrued policy fees
* @dev |v6.3.1|
*/
contract PolicyManager is Upgradeable {
using SafeERC20 for NuCypherToken;
using SafeMath for uint256;
using AdditionalMath for uint256;
using AdditionalMath for int256;
using AdditionalMath for uint16;
using Address for address payable;
event PolicyCreated(
bytes16 indexed policyId,
address indexed sponsor,
address indexed owner,
uint256 feeRate,
uint64 startTimestamp,
uint64 endTimestamp,
uint256 numberOfNodes
);
event ArrangementRevoked(
bytes16 indexed policyId,
address indexed sender,
address indexed node,
uint256 value
);
event RefundForArrangement(
bytes16 indexed policyId,
address indexed sender,
address indexed node,
uint256 value
);
event PolicyRevoked(bytes16 indexed policyId, address indexed sender, uint256 value);
event RefundForPolicy(bytes16 indexed policyId, address indexed sender, uint256 value);
event MinFeeRateSet(address indexed node, uint256 value);
// TODO #1501
// Range range
event FeeRateRangeSet(address indexed sender, uint256 min, uint256 defaultValue, uint256 max);
event Withdrawn(address indexed node, address indexed recipient, uint256 value);
struct ArrangementInfo {
address node;
uint256 indexOfDowntimePeriods;
uint16 lastRefundedPeriod;
}
struct Policy {
bool disabled;
address payable sponsor;
address owner;
uint128 feeRate;
uint64 startTimestamp;
uint64 endTimestamp;
uint256 reservedSlot1;
uint256 reservedSlot2;
uint256 reservedSlot3;
uint256 reservedSlot4;
uint256 reservedSlot5;
ArrangementInfo[] arrangements;
}
struct NodeInfo {
uint128 fee;
uint16 previousFeePeriod;
uint256 feeRate;
uint256 minFeeRate;
mapping (uint16 => int256) stub; // former slot for feeDelta
mapping (uint16 => int256) feeDelta;
}
// TODO used only for `delegateGetNodeInfo`, probably will be removed after #1512
struct MemoryNodeInfo {
uint128 fee;
uint16 previousFeePeriod;
uint256 feeRate;
uint256 minFeeRate;
}
struct Range {
uint128 min;
uint128 defaultValue;
uint128 max;
}
bytes16 internal constant RESERVED_POLICY_ID = bytes16(0);
address internal constant RESERVED_NODE = address(0);
uint256 internal constant MAX_BALANCE = uint256(uint128(0) - 1);
// controlled overflow to get max int256
int256 public constant DEFAULT_FEE_DELTA = int256((uint256(0) - 1) >> 1);
StakingEscrow public immutable escrow;
uint32 public immutable genesisSecondsPerPeriod;
uint32 public immutable secondsPerPeriod;
mapping (bytes16 => Policy) public policies;
mapping (address => NodeInfo) public nodes;
Range public feeRateRange;
uint64 public resetTimestamp;
/**
* @notice Constructor sets address of the escrow contract
* @dev Put same address in both inputs variables except when migration is happening
* @param _escrowDispatcher Address of escrow dispatcher
* @param _escrowImplementation Address of escrow implementation
*/
constructor(StakingEscrow _escrowDispatcher, StakingEscrow _escrowImplementation) {
escrow = _escrowDispatcher;
// if the input address is not the StakingEscrow then calling `secondsPerPeriod` will throw error
uint32 localSecondsPerPeriod = _escrowImplementation.secondsPerPeriod();
require(localSecondsPerPeriod > 0);
secondsPerPeriod = localSecondsPerPeriod;
uint32 localgenesisSecondsPerPeriod = _escrowImplementation.genesisSecondsPerPeriod();
require(localgenesisSecondsPerPeriod > 0);
genesisSecondsPerPeriod = localgenesisSecondsPerPeriod;
// handle case when we deployed new StakingEscrow but not yet upgraded
if (_escrowDispatcher != _escrowImplementation) {
require(_escrowDispatcher.secondsPerPeriod() == localSecondsPerPeriod ||
_escrowDispatcher.secondsPerPeriod() == localgenesisSecondsPerPeriod);
}
}
/**
* @dev Checks that sender is the StakingEscrow contract
*/
modifier onlyEscrowContract()
{
require(msg.sender == address(escrow));
_;
}
/**
* @return Number of current period
*/
function getCurrentPeriod() public view returns (uint16) {
return uint16(block.timestamp / secondsPerPeriod);
}
/**
* @return Recalculate period value using new basis
*/
function recalculatePeriod(uint16 _period) internal view returns (uint16) {
return uint16(uint256(_period) * genesisSecondsPerPeriod / secondsPerPeriod);
}
/**
* @notice Register a node
* @param _node Node address
* @param _period Initial period
*/
function register(address _node, uint16 _period) external onlyEscrowContract {
NodeInfo storage nodeInfo = nodes[_node];
require(nodeInfo.previousFeePeriod == 0 && _period < getCurrentPeriod());
nodeInfo.previousFeePeriod = _period;
}
/**
* @notice Migrate from the old period length to the new one
* @param _node Node address
*/
function migrate(address _node) external onlyEscrowContract {
NodeInfo storage nodeInfo = nodes[_node];
// with previous period length any previousFeePeriod will be greater than current period
// this is a sign of not migrated node
require(nodeInfo.previousFeePeriod >= getCurrentPeriod());
nodeInfo.previousFeePeriod = recalculatePeriod(nodeInfo.previousFeePeriod);
nodeInfo.feeRate = 0;
}
/**
* @notice Set minimum, default & maximum fee rate for all stakers and all policies ('global fee range')
*/
// TODO # 1501
// function setFeeRateRange(Range calldata _range) external onlyOwner {
function setFeeRateRange(uint128 _min, uint128 _default, uint128 _max) external onlyOwner {
require(_min <= _default && _default <= _max);
feeRateRange = Range(_min, _default, _max);
emit FeeRateRangeSet(msg.sender, _min, _default, _max);
}
/**
* @notice Set the minimum acceptable fee rate (set by staker for their associated worker)
* @dev Input value must fall within `feeRateRange` (global fee range)
*/
function setMinFeeRate(uint256 _minFeeRate) external {
require(_minFeeRate >= feeRateRange.min &&
_minFeeRate <= feeRateRange.max,
"The staker's min fee rate must fall within the global fee range");
NodeInfo storage nodeInfo = nodes[msg.sender];
if (nodeInfo.minFeeRate == _minFeeRate) {
return;
}
nodeInfo.minFeeRate = _minFeeRate;
emit MinFeeRateSet(msg.sender, _minFeeRate);
}
/**
* @notice Get the minimum acceptable fee rate (set by staker for their associated worker)
*/
function getMinFeeRate(NodeInfo storage _nodeInfo) internal view returns (uint256) {
// if minFeeRate has not been set or chosen value falls outside the global fee range
// a default value is returned instead
if (_nodeInfo.minFeeRate == 0 ||
_nodeInfo.minFeeRate < feeRateRange.min ||
_nodeInfo.minFeeRate > feeRateRange.max) {
return feeRateRange.defaultValue;
} else {
return _nodeInfo.minFeeRate;
}
}
/**
* @notice Get the minimum acceptable fee rate (set by staker for their associated worker)
*/
function getMinFeeRate(address _node) public view returns (uint256) {
NodeInfo storage nodeInfo = nodes[_node];
return getMinFeeRate(nodeInfo);
}
/**
* @notice Create policy
* @dev Generate policy id before creation
* @param _policyId Policy id
* @param _policyOwner Policy owner. Zero address means sender is owner
* @param _endTimestamp End timestamp of the policy in seconds
* @param _nodes Nodes that will handle policy
*/
function createPolicy(
bytes16 _policyId,
address _policyOwner,
uint64 _endTimestamp,
address[] calldata _nodes
)
external payable
{
require(
_endTimestamp > block.timestamp &&
msg.value > 0
);
require(address(this).balance <= MAX_BALANCE);
uint16 currentPeriod = getCurrentPeriod();
uint16 endPeriod = uint16(_endTimestamp / secondsPerPeriod) + 1;
uint256 numberOfPeriods = endPeriod - currentPeriod;
uint128 feeRate = uint128(msg.value.div(_nodes.length) / numberOfPeriods);
require(feeRate > 0 && feeRate * numberOfPeriods * _nodes.length == msg.value);
Policy storage policy = createPolicy(_policyId, _policyOwner, _endTimestamp, feeRate, _nodes.length);
for (uint256 i = 0; i < _nodes.length; i++) {
address node = _nodes[i];
addFeeToNode(currentPeriod, endPeriod, node, feeRate, int256(feeRate));
policy.arrangements.push(ArrangementInfo(node, 0, 0));
}
}
/**
* @notice Create multiple policies with the same owner, nodes and length
* @dev Generate policy ids before creation
* @param _policyIds Policy ids
* @param _policyOwner Policy owner. Zero address means sender is owner
* @param _endTimestamp End timestamp of all policies in seconds
* @param _nodes Nodes that will handle all policies
*/
function createPolicies(
bytes16[] calldata _policyIds,
address _policyOwner,
uint64 _endTimestamp,
address[] calldata _nodes
)
external payable
{
require(
_endTimestamp > block.timestamp &&
msg.value > 0 &&
_policyIds.length > 1
);
require(address(this).balance <= MAX_BALANCE);
uint16 currentPeriod = getCurrentPeriod();
uint16 endPeriod = uint16(_endTimestamp / secondsPerPeriod) + 1;
uint256 numberOfPeriods = endPeriod - currentPeriod;
uint128 feeRate = uint128(msg.value.div(_nodes.length) / numberOfPeriods / _policyIds.length);
require(feeRate > 0 && feeRate * numberOfPeriods * _nodes.length * _policyIds.length == msg.value);
for (uint256 i = 0; i < _policyIds.length; i++) {
Policy storage policy = createPolicy(_policyIds[i], _policyOwner, _endTimestamp, feeRate, _nodes.length);
for (uint256 j = 0; j < _nodes.length; j++) {
policy.arrangements.push(ArrangementInfo(_nodes[j], 0, 0));
}
}
int256 fee = int256(_policyIds.length * feeRate);
for (uint256 i = 0; i < _nodes.length; i++) {
address node = _nodes[i];
addFeeToNode(currentPeriod, endPeriod, node, feeRate, fee);
}
}
/**
* @notice Create policy
* @param _policyId Policy id
* @param _policyOwner Policy owner. Zero address means sender is owner
* @param _endTimestamp End timestamp of the policy in seconds
* @param _feeRate Fee rate for policy
* @param _nodesLength Number of nodes that will handle policy
*/
function createPolicy(
bytes16 _policyId,
address _policyOwner,
uint64 _endTimestamp,
uint128 _feeRate,
uint256 _nodesLength
)
internal returns (Policy storage policy)
{
policy = policies[_policyId];
require(
_policyId != RESERVED_POLICY_ID &&
policy.feeRate == 0 &&
!policy.disabled
);
policy.sponsor = msg.sender;
policy.startTimestamp = uint64(block.timestamp);
policy.endTimestamp = _endTimestamp;
policy.feeRate = _feeRate;
if (_policyOwner != msg.sender && _policyOwner != address(0)) {
policy.owner = _policyOwner;
}
emit PolicyCreated(
_policyId,
msg.sender,
_policyOwner == address(0) ? msg.sender : _policyOwner,
_feeRate,
policy.startTimestamp,
policy.endTimestamp,
_nodesLength
);
}
/**
* @notice Increase fee rate for specified node
* @param _currentPeriod Current period
* @param _endPeriod End period of policy
* @param _node Node that will handle policy
* @param _feeRate Fee rate for one policy
* @param _overallFeeRate Fee rate for all policies
*/
function addFeeToNode(
uint16 _currentPeriod,
uint16 _endPeriod,
address _node,
uint128 _feeRate,
int256 _overallFeeRate
)
internal
{
require(_node != RESERVED_NODE);
NodeInfo storage nodeInfo = nodes[_node];
require(nodeInfo.previousFeePeriod != 0 &&
nodeInfo.previousFeePeriod < _currentPeriod &&
_feeRate >= getMinFeeRate(nodeInfo));
// Check default value for feeDelta
if (nodeInfo.feeDelta[_currentPeriod] == DEFAULT_FEE_DELTA) {
nodeInfo.feeDelta[_currentPeriod] = _overallFeeRate;
} else {
// Overflow protection removed, because ETH total supply less than uint255/int256
nodeInfo.feeDelta[_currentPeriod] += _overallFeeRate;
}
if (nodeInfo.feeDelta[_endPeriod] == DEFAULT_FEE_DELTA) {
nodeInfo.feeDelta[_endPeriod] = -_overallFeeRate;
} else {
nodeInfo.feeDelta[_endPeriod] -= _overallFeeRate;
}
// Reset to default value if needed
if (nodeInfo.feeDelta[_currentPeriod] == 0) {
nodeInfo.feeDelta[_currentPeriod] = DEFAULT_FEE_DELTA;
}
if (nodeInfo.feeDelta[_endPeriod] == 0) {
nodeInfo.feeDelta[_endPeriod] = DEFAULT_FEE_DELTA;
}
}
/**
* @notice Get policy owner
*/
function getPolicyOwner(bytes16 _policyId) public view returns (address) {
Policy storage policy = policies[_policyId];
return policy.owner == address(0) ? policy.sponsor : policy.owner;
}
/**
* @notice Call from StakingEscrow to update node info once per period.
* Set default `feeDelta` value for specified period and update node fee
* @param _node Node address
* @param _processedPeriod1 Processed period
* @param _processedPeriod2 Processed period
* @param _periodToSetDefault Period to set
*/
function ping(
address _node,
uint16 _processedPeriod1,
uint16 _processedPeriod2,
uint16 _periodToSetDefault
)
external onlyEscrowContract
{
NodeInfo storage node = nodes[_node];
// protection from calling not migrated node, see migrate()
require(node.previousFeePeriod <= getCurrentPeriod());
if (_processedPeriod1 != 0) {
updateFee(node, _processedPeriod1);
}
if (_processedPeriod2 != 0) {
updateFee(node, _processedPeriod2);
}
// This code increases gas cost for node in trade of decreasing cost for policy sponsor
if (_periodToSetDefault != 0 && node.feeDelta[_periodToSetDefault] == 0) {
node.feeDelta[_periodToSetDefault] = DEFAULT_FEE_DELTA;
}
}
/**
* @notice Update node fee
* @param _info Node info structure
* @param _period Processed period
*/
function updateFee(NodeInfo storage _info, uint16 _period) internal {
if (_info.previousFeePeriod == 0 || _period <= _info.previousFeePeriod) {
return;
}
for (uint16 i = _info.previousFeePeriod + 1; i <= _period; i++) {
int256 delta = _info.feeDelta[i];
if (delta == DEFAULT_FEE_DELTA) {
// gas refund
_info.feeDelta[i] = 0;
continue;
}
_info.feeRate = _info.feeRate.addSigned(delta);
// gas refund
_info.feeDelta[i] = 0;
}
_info.previousFeePeriod = _period;
_info.fee += uint128(_info.feeRate);
}
/**
* @notice Withdraw fee by node
*/
function withdraw() external returns (uint256) {
return withdraw(msg.sender);
}
/**
* @notice Withdraw fee by node
* @param _recipient Recipient of the fee
*/
function withdraw(address payable _recipient) public returns (uint256) {
NodeInfo storage node = nodes[msg.sender];
uint256 fee = node.fee;
require(fee != 0);
node.fee = 0;
_recipient.sendValue(fee);
emit Withdrawn(msg.sender, _recipient, fee);
return fee;
}
/**
* @notice Calculate amount of refund
* @param _policy Policy
* @param _arrangement Arrangement
*/
function calculateRefundValue(Policy storage _policy, ArrangementInfo storage _arrangement)
internal view returns (uint256 refundValue, uint256 indexOfDowntimePeriods, uint16 lastRefundedPeriod)
{
uint16 policyStartPeriod = uint16(_policy.startTimestamp / secondsPerPeriod);
uint16 maxPeriod = AdditionalMath.min16(getCurrentPeriod(), uint16(_policy.endTimestamp / secondsPerPeriod));
uint16 minPeriod = AdditionalMath.max16(policyStartPeriod, _arrangement.lastRefundedPeriod);
uint16 downtimePeriods = 0;
uint256 length = escrow.getPastDowntimeLength(_arrangement.node);
uint256 initialIndexOfDowntimePeriods;
if (_arrangement.lastRefundedPeriod == 0) {
initialIndexOfDowntimePeriods = escrow.findIndexOfPastDowntime(_arrangement.node, policyStartPeriod);
} else {
initialIndexOfDowntimePeriods = _arrangement.indexOfDowntimePeriods;
}
for (indexOfDowntimePeriods = initialIndexOfDowntimePeriods;
indexOfDowntimePeriods < length;
indexOfDowntimePeriods++)
{
(uint16 startPeriod, uint16 endPeriod) =
escrow.getPastDowntime(_arrangement.node, indexOfDowntimePeriods);
if (startPeriod > maxPeriod) {
break;
} else if (endPeriod < minPeriod) {
continue;
}
downtimePeriods += AdditionalMath.min16(maxPeriod, endPeriod)
.sub16(AdditionalMath.max16(minPeriod, startPeriod)) + 1;
if (maxPeriod <= endPeriod) {
break;
}
}
uint16 lastCommittedPeriod = escrow.getLastCommittedPeriod(_arrangement.node);
if (indexOfDowntimePeriods == length && lastCommittedPeriod < maxPeriod) {
// Overflow protection removed:
// lastCommittedPeriod < maxPeriod and minPeriod <= maxPeriod + 1
downtimePeriods += maxPeriod - AdditionalMath.max16(minPeriod - 1, lastCommittedPeriod);
}
refundValue = _policy.feeRate * downtimePeriods;
lastRefundedPeriod = maxPeriod + 1;
}
/**
* @notice Revoke/refund arrangement/policy by the sponsor
* @param _policyId Policy id
* @param _node Node that will be excluded or RESERVED_NODE if full policy should be used
( @param _forceRevoke Force revoke arrangement/policy
*/
function refundInternal(bytes16 _policyId, address _node, bool _forceRevoke)
internal returns (uint256 refundValue)
{
refundValue = 0;
Policy storage policy = policies[_policyId];
require(!policy.disabled && policy.startTimestamp >= resetTimestamp);
uint16 endPeriod = uint16(policy.endTimestamp / secondsPerPeriod) + 1;
uint256 numberOfActive = policy.arrangements.length;
uint256 i = 0;
for (; i < policy.arrangements.length; i++) {
ArrangementInfo storage arrangement = policy.arrangements[i];
address node = arrangement.node;
if (node == RESERVED_NODE || _node != RESERVED_NODE && _node != node) {
numberOfActive--;
continue;
}
uint256 nodeRefundValue;
(nodeRefundValue, arrangement.indexOfDowntimePeriods, arrangement.lastRefundedPeriod) =
calculateRefundValue(policy, arrangement);
if (_forceRevoke) {
NodeInfo storage nodeInfo = nodes[node];
// Check default value for feeDelta
uint16 lastRefundedPeriod = arrangement.lastRefundedPeriod;
if (nodeInfo.feeDelta[lastRefundedPeriod] == DEFAULT_FEE_DELTA) {
nodeInfo.feeDelta[lastRefundedPeriod] = -int256(policy.feeRate);
} else {
nodeInfo.feeDelta[lastRefundedPeriod] -= int256(policy.feeRate);
}
if (nodeInfo.feeDelta[endPeriod] == DEFAULT_FEE_DELTA) {
nodeInfo.feeDelta[endPeriod] = int256(policy.feeRate);
} else {
nodeInfo.feeDelta[endPeriod] += int256(policy.feeRate);
}
// Reset to default value if needed
if (nodeInfo.feeDelta[lastRefundedPeriod] == 0) {
nodeInfo.feeDelta[lastRefundedPeriod] = DEFAULT_FEE_DELTA;
}
if (nodeInfo.feeDelta[endPeriod] == 0) {
nodeInfo.feeDelta[endPeriod] = DEFAULT_FEE_DELTA;
}
nodeRefundValue += uint256(endPeriod - lastRefundedPeriod) * policy.feeRate;
}
if (_forceRevoke || arrangement.lastRefundedPeriod >= endPeriod) {
arrangement.node = RESERVED_NODE;
arrangement.indexOfDowntimePeriods = 0;
arrangement.lastRefundedPeriod = 0;
numberOfActive--;
emit ArrangementRevoked(_policyId, msg.sender, node, nodeRefundValue);
} else {
emit RefundForArrangement(_policyId, msg.sender, node, nodeRefundValue);
}
refundValue += nodeRefundValue;
if (_node != RESERVED_NODE) {
break;
}
}
address payable policySponsor = policy.sponsor;
if (_node == RESERVED_NODE) {
if (numberOfActive == 0) {
policy.disabled = true;
// gas refund
policy.sponsor = address(0);
policy.owner = address(0);
policy.feeRate = 0;
policy.startTimestamp = 0;
policy.endTimestamp = 0;
emit PolicyRevoked(_policyId, msg.sender, refundValue);
} else {
emit RefundForPolicy(_policyId, msg.sender, refundValue);
}
} else {
// arrangement not found
require(i < policy.arrangements.length);
}
if (refundValue > 0) {
policySponsor.sendValue(refundValue);
}
}
/**
* @notice Calculate amount of refund
* @param _policyId Policy id
* @param _node Node or RESERVED_NODE if all nodes should be used
*/
function calculateRefundValueInternal(bytes16 _policyId, address _node)
internal view returns (uint256 refundValue)
{
refundValue = 0;
Policy storage policy = policies[_policyId];
require((policy.owner == msg.sender || policy.sponsor == msg.sender) && !policy.disabled);
uint256 i = 0;
for (; i < policy.arrangements.length; i++) {
ArrangementInfo storage arrangement = policy.arrangements[i];
if (arrangement.node == RESERVED_NODE || _node != RESERVED_NODE && _node != arrangement.node) {
continue;
}
(uint256 nodeRefundValue,,) = calculateRefundValue(policy, arrangement);
refundValue += nodeRefundValue;
if (_node != RESERVED_NODE) {
break;
}
}
if (_node != RESERVED_NODE) {
// arrangement not found
require(i < policy.arrangements.length);
}
}
/**
* @notice Revoke policy by the sponsor
* @param _policyId Policy id
*/
function revokePolicy(bytes16 _policyId) external returns (uint256 refundValue) {
require(getPolicyOwner(_policyId) == msg.sender);
return refundInternal(_policyId, RESERVED_NODE, true);
}
/**
* @notice Revoke arrangement by the sponsor
* @param _policyId Policy id
* @param _node Node that will be excluded
*/
function revokeArrangement(bytes16 _policyId, address _node)
external returns (uint256 refundValue)
{
require(_node != RESERVED_NODE);
require(getPolicyOwner(_policyId) == msg.sender);
return refundInternal(_policyId, _node, true);
}
/**
* @notice Get unsigned hash for revocation
* @param _policyId Policy id
* @param _node Node that will be excluded
* @return Revocation hash, EIP191 version 0x45 ('E')
*/
function getRevocationHash(bytes16 _policyId, address _node) public view returns (bytes32) {
return SignatureVerifier.hashEIP191(abi.encodePacked(_policyId, _node), byte(0x45));
}
/**
* @notice Check correctness of signature
* @param _policyId Policy id
* @param _node Node that will be excluded, zero address if whole policy will be revoked
* @param _signature Signature of owner
*/
function checkOwnerSignature(bytes16 _policyId, address _node, bytes memory _signature) internal view {
bytes32 hash = getRevocationHash(_policyId, _node);
address recovered = SignatureVerifier.recover(hash, _signature);
require(getPolicyOwner(_policyId) == recovered);
}
/**
* @notice Revoke policy or arrangement using owner's signature
* @param _policyId Policy id
* @param _node Node that will be excluded, zero address if whole policy will be revoked
* @param _signature Signature of owner, EIP191 version 0x45 ('E')
*/
function revoke(bytes16 _policyId, address _node, bytes calldata _signature)
external returns (uint256 refundValue)
{
checkOwnerSignature(_policyId, _node, _signature);
return refundInternal(_policyId, _node, true);
}
/**
* @notice Refund part of fee by the sponsor
* @param _policyId Policy id
*/
function refund(bytes16 _policyId) external {
Policy storage policy = policies[_policyId];
require(policy.owner == msg.sender || policy.sponsor == msg.sender);
refundInternal(_policyId, RESERVED_NODE, false);
}
/**
* @notice Refund part of one node's fee by the sponsor
* @param _policyId Policy id
* @param _node Node address
*/
function refund(bytes16 _policyId, address _node)
external returns (uint256 refundValue)
{
require(_node != RESERVED_NODE);
Policy storage policy = policies[_policyId];
require(policy.owner == msg.sender || policy.sponsor == msg.sender);
return refundInternal(_policyId, _node, false);
}
/**
* @notice Calculate amount of refund
* @param _policyId Policy id
*/
function calculateRefundValue(bytes16 _policyId)
external view returns (uint256 refundValue)
{
return calculateRefundValueInternal(_policyId, RESERVED_NODE);
}
/**
* @notice Calculate amount of refund
* @param _policyId Policy id
* @param _node Node
*/
function calculateRefundValue(bytes16 _policyId, address _node)
external view returns (uint256 refundValue)
{
require(_node != RESERVED_NODE);
return calculateRefundValueInternal(_policyId, _node);
}
/**
* @notice Get number of arrangements in the policy
* @param _policyId Policy id
*/
function getArrangementsLength(bytes16 _policyId) external view returns (uint256) {
return policies[_policyId].arrangements.length;
}
/**
* @notice Get information about staker's fee rate
* @param _node Address of staker
* @param _period Period to get fee delta
*/
function getNodeFeeDelta(address _node, uint16 _period)
// TODO "virtual" only for tests, probably will be removed after #1512
public view virtual returns (int256)
{
// TODO remove after upgrade #2579
if (_node == RESERVED_NODE && _period == 11) {
return 55;
}
return nodes[_node].feeDelta[_period];
}
/**
* @notice Return the information about arrangement
*/
function getArrangementInfo(bytes16 _policyId, uint256 _index)
// TODO change to structure when ABIEncoderV2 is released (#1501)
// public view returns (ArrangementInfo)
external view returns (address node, uint256 indexOfDowntimePeriods, uint16 lastRefundedPeriod)
{
ArrangementInfo storage info = policies[_policyId].arrangements[_index];
node = info.node;
indexOfDowntimePeriods = info.indexOfDowntimePeriods;
lastRefundedPeriod = info.lastRefundedPeriod;
}
/**
* @dev Get Policy structure by delegatecall
*/
function delegateGetPolicy(address _target, bytes16 _policyId)
internal returns (Policy memory result)
{
bytes32 memoryAddress = delegateGetData(_target, this.policies.selector, 1, bytes32(_policyId), 0);
assembly {
result := memoryAddress
}
}
/**
* @dev Get ArrangementInfo structure by delegatecall
*/
function delegateGetArrangementInfo(address _target, bytes16 _policyId, uint256 _index)
internal returns (ArrangementInfo memory result)
{
bytes32 memoryAddress = delegateGetData(
_target, this.getArrangementInfo.selector, 2, bytes32(_policyId), bytes32(_index));
assembly {
result := memoryAddress
}
}
/**
* @dev Get NodeInfo structure by delegatecall
*/
function delegateGetNodeInfo(address _target, address _node)
internal returns (MemoryNodeInfo memory result)
{
bytes32 memoryAddress = delegateGetData(_target, this.nodes.selector, 1, bytes32(uint256(_node)), 0);
assembly {
result := memoryAddress
}
}
/**
* @dev Get feeRateRange structure by delegatecall
*/
function delegateGetFeeRateRange(address _target) internal returns (Range memory result) {
bytes32 memoryAddress = delegateGetData(_target, this.feeRateRange.selector, 0, 0, 0);
assembly {
result := memoryAddress
}
}
/// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState`
function verifyState(address _testTarget) public override virtual {
super.verifyState(_testTarget);
require(uint64(delegateGet(_testTarget, this.resetTimestamp.selector)) == resetTimestamp);
Range memory rangeToCheck = delegateGetFeeRateRange(_testTarget);
require(feeRateRange.min == rangeToCheck.min &&
feeRateRange.defaultValue == rangeToCheck.defaultValue &&
feeRateRange.max == rangeToCheck.max);
Policy storage policy = policies[RESERVED_POLICY_ID];
Policy memory policyToCheck = delegateGetPolicy(_testTarget, RESERVED_POLICY_ID);
require(policyToCheck.sponsor == policy.sponsor &&
policyToCheck.owner == policy.owner &&
policyToCheck.feeRate == policy.feeRate &&
policyToCheck.startTimestamp == policy.startTimestamp &&
policyToCheck.endTimestamp == policy.endTimestamp &&
policyToCheck.disabled == policy.disabled);
require(delegateGet(_testTarget, this.getArrangementsLength.selector, RESERVED_POLICY_ID) ==
policy.arrangements.length);
if (policy.arrangements.length > 0) {
ArrangementInfo storage arrangement = policy.arrangements[0];
ArrangementInfo memory arrangementToCheck = delegateGetArrangementInfo(
_testTarget, RESERVED_POLICY_ID, 0);
require(arrangementToCheck.node == arrangement.node &&
arrangementToCheck.indexOfDowntimePeriods == arrangement.indexOfDowntimePeriods &&
arrangementToCheck.lastRefundedPeriod == arrangement.lastRefundedPeriod);
}
NodeInfo storage nodeInfo = nodes[RESERVED_NODE];
MemoryNodeInfo memory nodeInfoToCheck = delegateGetNodeInfo(_testTarget, RESERVED_NODE);
require(nodeInfoToCheck.fee == nodeInfo.fee &&
nodeInfoToCheck.feeRate == nodeInfo.feeRate &&
nodeInfoToCheck.previousFeePeriod == nodeInfo.previousFeePeriod &&
nodeInfoToCheck.minFeeRate == nodeInfo.minFeeRate);
require(int256(delegateGet(_testTarget, this.getNodeFeeDelta.selector,
bytes32(bytes20(RESERVED_NODE)), bytes32(uint256(11)))) == getNodeFeeDelta(RESERVED_NODE, 11));
}
/// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade`
function finishUpgrade(address _target) public override virtual {
super.finishUpgrade(_target);
if (resetTimestamp == 0) {
resetTimestamp = uint64(block.timestamp);
}
// Create fake Policy and NodeInfo to use them in verifyState(address)
Policy storage policy = policies[RESERVED_POLICY_ID];
policy.sponsor = msg.sender;
policy.owner = address(this);
policy.startTimestamp = 1;
policy.endTimestamp = 2;
policy.feeRate = 3;
policy.disabled = true;
policy.arrangements.push(ArrangementInfo(RESERVED_NODE, 11, 22));
NodeInfo storage nodeInfo = nodes[RESERVED_NODE];
nodeInfo.fee = 100;
nodeInfo.feeRate = 33;
nodeInfo.previousFeePeriod = 44;
nodeInfo.feeDelta[11] = 55;
nodeInfo.minFeeRate = 777;
}
}
// 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) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "./Upgradeable.sol";
import "../../zeppelin/utils/Address.sol";
/**
* @notice ERC897 - ERC DelegateProxy
*/
interface ERCProxy {
function proxyType() external pure returns (uint256);
function implementation() external view returns (address);
}
/**
* @notice Proxying requests to other contracts.
* Client should use ABI of real contract and address of this contract
*/
contract Dispatcher is Upgradeable, ERCProxy {
using Address for address;
event Upgraded(address indexed from, address indexed to, address owner);
event RolledBack(address indexed from, address indexed to, address owner);
/**
* @dev Set upgrading status before and after operations
*/
modifier upgrading()
{
isUpgrade = UPGRADE_TRUE;
_;
isUpgrade = UPGRADE_FALSE;
}
/**
* @param _target Target contract address
*/
constructor(address _target) upgrading {
require(_target.isContract());
// Checks that target contract inherits Dispatcher state
verifyState(_target);
// `verifyState` must work with its contract
verifyUpgradeableState(_target, _target);
target = _target;
finishUpgrade();
emit Upgraded(address(0), _target, msg.sender);
}
//------------------------ERC897------------------------
/**
* @notice ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy
*/
function proxyType() external pure override returns (uint256) {
return 2;
}
/**
* @notice ERC897, gets the address of the implementation where every call will be delegated
*/
function implementation() external view override returns (address) {
return target;
}
//------------------------------------------------------------
/**
* @notice Verify new contract storage and upgrade target
* @param _target New target contract address
*/
function upgrade(address _target) public onlyOwner upgrading {
require(_target.isContract());
// Checks that target contract has "correct" (as much as possible) state layout
verifyState(_target);
//`verifyState` must work with its contract
verifyUpgradeableState(_target, _target);
if (target.isContract()) {
verifyUpgradeableState(target, _target);
}
previousTarget = target;
target = _target;
finishUpgrade();
emit Upgraded(previousTarget, _target, msg.sender);
}
/**
* @notice Rollback to previous target
* @dev Test storage carefully before upgrade again after rollback
*/
function rollback() public onlyOwner upgrading {
require(previousTarget.isContract());
emit RolledBack(target, previousTarget, msg.sender);
// should be always true because layout previousTarget -> target was already checked
// but `verifyState` is not 100% accurate so check again
verifyState(previousTarget);
if (target.isContract()) {
verifyUpgradeableState(previousTarget, target);
}
target = previousTarget;
previousTarget = address(0);
finishUpgrade();
}
/**
* @dev Call verifyState method for Upgradeable contract
*/
function verifyUpgradeableState(address _from, address _to) private {
(bool callSuccess,) = _from.delegatecall(abi.encodeWithSelector(this.verifyState.selector, _to));
require(callSuccess);
}
/**
* @dev Call finishUpgrade method from the Upgradeable contract
*/
function finishUpgrade() private {
(bool callSuccess,) = target.delegatecall(abi.encodeWithSelector(this.finishUpgrade.selector, target));
require(callSuccess);
}
function verifyState(address _testTarget) public override onlyWhileUpgrading {
//checks equivalence accessing state through new contract and current storage
require(address(uint160(delegateGet(_testTarget, this.owner.selector))) == owner());
require(address(uint160(delegateGet(_testTarget, this.target.selector))) == target);
require(address(uint160(delegateGet(_testTarget, this.previousTarget.selector))) == previousTarget);
require(uint8(delegateGet(_testTarget, this.isUpgrade.selector)) == isUpgrade);
}
/**
* @dev Override function using empty code because no reason to call this function in Dispatcher
*/
function finishUpgrade(address) public override {}
/**
* @dev Receive function sends empty request to the target contract
*/
receive() external payable {
assert(target.isContract());
// execute receive function from target contract using storage of the dispatcher
(bool callSuccess,) = target.delegatecall("");
if (!callSuccess) {
revert();
}
}
/**
* @dev Fallback function sends all requests to the target contract
*/
fallback() external payable {
assert(target.isContract());
// execute requested function from target contract using storage of the dispatcher
(bool callSuccess,) = target.delegatecall(msg.data);
if (callSuccess) {
// copy result of the request to the return data
// we can use the second return value from `delegatecall` (bytes memory)
// but it will consume a little more gas
assembly {
returndatacopy(0x0, 0x0, returndatasize())
return(0x0, returndatasize())
}
} else {
revert();
}
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../../zeppelin/ownership/Ownable.sol";
import "../../zeppelin/utils/Address.sol";
import "../../zeppelin/token/ERC20/SafeERC20.sol";
import "./StakingInterface.sol";
import "../../zeppelin/proxy/Initializable.sol";
/**
* @notice Router for accessing interface contract
*/
contract StakingInterfaceRouter is Ownable {
BaseStakingInterface public target;
/**
* @param _target Address of the interface contract
*/
constructor(BaseStakingInterface _target) {
require(address(_target.token()) != address(0));
target = _target;
}
/**
* @notice Upgrade interface
* @param _target New contract address
*/
function upgrade(BaseStakingInterface _target) external onlyOwner {
require(address(_target.token()) != address(0));
target = _target;
}
}
/**
* @notice Internal base class for AbstractStakingContract and InitializableStakingContract
*/
abstract contract RawStakingContract {
using Address for address;
/**
* @dev Returns address of StakingInterfaceRouter
*/
function router() public view virtual returns (StakingInterfaceRouter);
/**
* @dev Checks permission for calling fallback function
*/
function isFallbackAllowed() public virtual returns (bool);
/**
* @dev Withdraw tokens from staking contract
*/
function withdrawTokens(uint256 _value) public virtual;
/**
* @dev Withdraw ETH from staking contract
*/
function withdrawETH() public virtual;
receive() external payable {}
/**
* @dev Function sends all requests to the target contract
*/
fallback() external payable {
require(isFallbackAllowed());
address target = address(router().target());
require(target.isContract());
// execute requested function from target contract
(bool callSuccess, ) = target.delegatecall(msg.data);
if (callSuccess) {
// copy result of the request to the return data
// we can use the second return value from `delegatecall` (bytes memory)
// but it will consume a little more gas
assembly {
returndatacopy(0x0, 0x0, returndatasize())
return(0x0, returndatasize())
}
} else {
revert();
}
}
}
/**
* @notice Base class for any staking contract (not usable with openzeppelin proxy)
* @dev Implement `isFallbackAllowed()` or override fallback function
* Implement `withdrawTokens(uint256)` and `withdrawETH()` functions
*/
abstract contract AbstractStakingContract is RawStakingContract {
StakingInterfaceRouter immutable router_;
NuCypherToken public immutable token;
/**
* @param _router Interface router contract address
*/
constructor(StakingInterfaceRouter _router) {
router_ = _router;
NuCypherToken localToken = _router.target().token();
require(address(localToken) != address(0));
token = localToken;
}
/**
* @dev Returns address of StakingInterfaceRouter
*/
function router() public view override returns (StakingInterfaceRouter) {
return router_;
}
}
/**
* @notice Base class for any staking contract usable with openzeppelin proxy
* @dev Implement `isFallbackAllowed()` or override fallback function
* Implement `withdrawTokens(uint256)` and `withdrawETH()` functions
*/
abstract contract InitializableStakingContract is Initializable, RawStakingContract {
StakingInterfaceRouter router_;
NuCypherToken public token;
/**
* @param _router Interface router contract address
*/
function initialize(StakingInterfaceRouter _router) public initializer {
router_ = _router;
NuCypherToken localToken = _router.target().token();
require(address(localToken) != address(0));
token = localToken;
}
/**
* @dev Returns address of StakingInterfaceRouter
*/
function router() public view override returns (StakingInterfaceRouter) {
return router_;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "./AbstractStakingContract.sol";
import "../NuCypherToken.sol";
import "../StakingEscrow.sol";
import "../PolicyManager.sol";
import "../WorkLock.sol";
/**
* @notice Base StakingInterface
*/
contract BaseStakingInterface {
address public immutable stakingInterfaceAddress;
NuCypherToken public immutable token;
StakingEscrow public immutable escrow;
PolicyManager public immutable policyManager;
WorkLock public immutable workLock;
/**
* @notice Constructor sets addresses of the contracts
* @param _token Token contract
* @param _escrow Escrow contract
* @param _policyManager PolicyManager contract
* @param _workLock WorkLock contract
*/
constructor(
NuCypherToken _token,
StakingEscrow _escrow,
PolicyManager _policyManager,
WorkLock _workLock
) {
require(_token.totalSupply() > 0 &&
_escrow.secondsPerPeriod() > 0 &&
_policyManager.secondsPerPeriod() > 0 &&
// in case there is no worklock contract
(address(_workLock) == address(0) || _workLock.boostingRefund() > 0));
token = _token;
escrow = _escrow;
policyManager = _policyManager;
workLock = _workLock;
stakingInterfaceAddress = address(this);
}
/**
* @dev Checks executing through delegate call
*/
modifier onlyDelegateCall()
{
require(stakingInterfaceAddress != address(this));
_;
}
/**
* @dev Checks the existence of the worklock contract
*/
modifier workLockSet()
{
require(address(workLock) != address(0));
_;
}
}
/**
* @notice Interface for accessing main contracts from a staking contract
* @dev All methods must be stateless because this code will be executed by delegatecall call, use immutable fields.
* @dev |v1.7.1|
*/
contract StakingInterface is BaseStakingInterface {
event DepositedAsStaker(address indexed sender, uint256 value, uint16 periods);
event WithdrawnAsStaker(address indexed sender, uint256 value);
event DepositedAndIncreased(address indexed sender, uint256 index, uint256 value);
event LockedAndCreated(address indexed sender, uint256 value, uint16 periods);
event LockedAndIncreased(address indexed sender, uint256 index, uint256 value);
event Divided(address indexed sender, uint256 index, uint256 newValue, uint16 periods);
event Merged(address indexed sender, uint256 index1, uint256 index2);
event Minted(address indexed sender);
event PolicyFeeWithdrawn(address indexed sender, uint256 value);
event MinFeeRateSet(address indexed sender, uint256 value);
event ReStakeSet(address indexed sender, bool reStake);
event WorkerBonded(address indexed sender, address worker);
event Prolonged(address indexed sender, uint256 index, uint16 periods);
event WindDownSet(address indexed sender, bool windDown);
event SnapshotSet(address indexed sender, bool snapshotsEnabled);
event Bid(address indexed sender, uint256 depositedETH);
event Claimed(address indexed sender, uint256 claimedTokens);
event Refund(address indexed sender, uint256 refundETH);
event BidCanceled(address indexed sender);
event CompensationWithdrawn(address indexed sender);
/**
* @notice Constructor sets addresses of the contracts
* @param _token Token contract
* @param _escrow Escrow contract
* @param _policyManager PolicyManager contract
* @param _workLock WorkLock contract
*/
constructor(
NuCypherToken _token,
StakingEscrow _escrow,
PolicyManager _policyManager,
WorkLock _workLock
)
BaseStakingInterface(_token, _escrow, _policyManager, _workLock)
{
}
/**
* @notice Bond worker in the staking escrow
* @param _worker Worker address
*/
function bondWorker(address _worker) public onlyDelegateCall {
escrow.bondWorker(_worker);
emit WorkerBonded(msg.sender, _worker);
}
/**
* @notice Set `reStake` parameter in the staking escrow
* @param _reStake Value for parameter
*/
function setReStake(bool _reStake) public onlyDelegateCall {
escrow.setReStake(_reStake);
emit ReStakeSet(msg.sender, _reStake);
}
/**
* @notice Deposit tokens to the staking escrow
* @param _value Amount of token to deposit
* @param _periods Amount of periods during which tokens will be locked
*/
function depositAsStaker(uint256 _value, uint16 _periods) public onlyDelegateCall {
require(token.balanceOf(address(this)) >= _value);
token.approve(address(escrow), _value);
escrow.deposit(address(this), _value, _periods);
emit DepositedAsStaker(msg.sender, _value, _periods);
}
/**
* @notice Deposit tokens to the staking escrow
* @param _index Index of the sub-stake
* @param _value Amount of tokens which will be locked
*/
function depositAndIncrease(uint256 _index, uint256 _value) public onlyDelegateCall {
require(token.balanceOf(address(this)) >= _value);
token.approve(address(escrow), _value);
escrow.depositAndIncrease(_index, _value);
emit DepositedAndIncreased(msg.sender, _index, _value);
}
/**
* @notice Withdraw available amount of tokens from the staking escrow to the staking contract
* @param _value Amount of token to withdraw
*/
function withdrawAsStaker(uint256 _value) public onlyDelegateCall {
escrow.withdraw(_value);
emit WithdrawnAsStaker(msg.sender, _value);
}
/**
* @notice Lock some tokens in the staking escrow
* @param _value Amount of tokens which should lock
* @param _periods Amount of periods during which tokens will be locked
*/
function lockAndCreate(uint256 _value, uint16 _periods) public onlyDelegateCall {
escrow.lockAndCreate(_value, _periods);
emit LockedAndCreated(msg.sender, _value, _periods);
}
/**
* @notice Lock some tokens in the staking escrow
* @param _index Index of the sub-stake
* @param _value Amount of tokens which will be locked
*/
function lockAndIncrease(uint256 _index, uint256 _value) public onlyDelegateCall {
escrow.lockAndIncrease(_index, _value);
emit LockedAndIncreased(msg.sender, _index, _value);
}
/**
* @notice Divide stake into two parts
* @param _index Index of stake
* @param _newValue New stake value
* @param _periods Amount of periods for extending stake
*/
function divideStake(uint256 _index, uint256 _newValue, uint16 _periods) public onlyDelegateCall {
escrow.divideStake(_index, _newValue, _periods);
emit Divided(msg.sender, _index, _newValue, _periods);
}
/**
* @notice Merge two sub-stakes into one
* @param _index1 Index of the first sub-stake
* @param _index2 Index of the second sub-stake
*/
function mergeStake(uint256 _index1, uint256 _index2) public onlyDelegateCall {
escrow.mergeStake(_index1, _index2);
emit Merged(msg.sender, _index1, _index2);
}
/**
* @notice Mint tokens in the staking escrow
*/
function mint() public onlyDelegateCall {
escrow.mint();
emit Minted(msg.sender);
}
/**
* @notice Withdraw available policy fees from the policy manager to the staking contract
*/
function withdrawPolicyFee() public onlyDelegateCall {
uint256 value = policyManager.withdraw();
emit PolicyFeeWithdrawn(msg.sender, value);
}
/**
* @notice Set the minimum fee that the staker will accept in the policy manager contract
*/
function setMinFeeRate(uint256 _minFeeRate) public onlyDelegateCall {
policyManager.setMinFeeRate(_minFeeRate);
emit MinFeeRateSet(msg.sender, _minFeeRate);
}
/**
* @notice Prolong active sub stake
* @param _index Index of the sub stake
* @param _periods Amount of periods for extending sub stake
*/
function prolongStake(uint256 _index, uint16 _periods) public onlyDelegateCall {
escrow.prolongStake(_index, _periods);
emit Prolonged(msg.sender, _index, _periods);
}
/**
* @notice Set `windDown` parameter in the staking escrow
* @param _windDown Value for parameter
*/
function setWindDown(bool _windDown) public onlyDelegateCall {
escrow.setWindDown(_windDown);
emit WindDownSet(msg.sender, _windDown);
}
/**
* @notice Set `snapshots` parameter in the staking escrow
* @param _enableSnapshots Value for parameter
*/
function setSnapshots(bool _enableSnapshots) public onlyDelegateCall {
escrow.setSnapshots(_enableSnapshots);
emit SnapshotSet(msg.sender, _enableSnapshots);
}
/**
* @notice Bid for tokens by transferring ETH
*/
function bid(uint256 _value) public payable onlyDelegateCall workLockSet {
workLock.bid{value: _value}();
emit Bid(msg.sender, _value);
}
/**
* @notice Cancel bid and refund deposited ETH
*/
function cancelBid() public onlyDelegateCall workLockSet {
workLock.cancelBid();
emit BidCanceled(msg.sender);
}
/**
* @notice Withdraw compensation after force refund
*/
function withdrawCompensation() public onlyDelegateCall workLockSet {
workLock.withdrawCompensation();
emit CompensationWithdrawn(msg.sender);
}
/**
* @notice Claimed tokens will be deposited and locked as stake in the StakingEscrow contract
*/
function claim() public onlyDelegateCall workLockSet {
uint256 claimedTokens = workLock.claim();
emit Claimed(msg.sender, claimedTokens);
}
/**
* @notice Refund ETH for the completed work
*/
function refund() public onlyDelegateCall workLockSet {
uint256 refundETH = workLock.refund();
emit Refund(msg.sender, refundETH);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../zeppelin/math/SafeMath.sol";
import "../zeppelin/token/ERC20/SafeERC20.sol";
import "../zeppelin/utils/Address.sol";
import "../zeppelin/ownership/Ownable.sol";
import "./NuCypherToken.sol";
import "./StakingEscrow.sol";
import "./lib/AdditionalMath.sol";
/**
* @notice The WorkLock distribution contract
*/
contract WorkLock is Ownable {
using SafeERC20 for NuCypherToken;
using SafeMath for uint256;
using AdditionalMath for uint256;
using Address for address payable;
using Address for address;
event Deposited(address indexed sender, uint256 value);
event Bid(address indexed sender, uint256 depositedETH);
event Claimed(address indexed sender, uint256 claimedTokens);
event Refund(address indexed sender, uint256 refundETH, uint256 completedWork);
event Canceled(address indexed sender, uint256 value);
event BiddersChecked(address indexed sender, uint256 startIndex, uint256 endIndex);
event ForceRefund(address indexed sender, address indexed bidder, uint256 refundETH);
event CompensationWithdrawn(address indexed sender, uint256 value);
event Shutdown(address indexed sender);
struct WorkInfo {
uint256 depositedETH;
uint256 completedWork;
bool claimed;
uint128 index;
}
uint16 public constant SLOWING_REFUND = 100;
uint256 private constant MAX_ETH_SUPPLY = 2e10 ether;
NuCypherToken public immutable token;
StakingEscrow public immutable escrow;
/*
* @dev WorkLock calculations:
* bid = minBid + bonusETHPart
* bonusTokenSupply = tokenSupply - bidders.length * minAllowableLockedTokens
* bonusDepositRate = bonusTokenSupply / bonusETHSupply
* claimedTokens = minAllowableLockedTokens + bonusETHPart * bonusDepositRate
* bonusRefundRate = bonusDepositRate * SLOWING_REFUND / boostingRefund
* refundETH = completedWork / refundRate
*/
uint256 public immutable boostingRefund;
uint256 public immutable minAllowedBid;
uint16 public immutable stakingPeriods;
// copy from the escrow contract
uint256 public immutable maxAllowableLockedTokens;
uint256 public immutable minAllowableLockedTokens;
uint256 public tokenSupply;
uint256 public startBidDate;
uint256 public endBidDate;
uint256 public endCancellationDate;
uint256 public bonusETHSupply;
mapping(address => WorkInfo) public workInfo;
mapping(address => uint256) public compensation;
address[] public bidders;
// if value == bidders.length then WorkLock is fully checked
uint256 public nextBidderToCheck;
/**
* @dev Checks timestamp regarding cancellation window
*/
modifier afterCancellationWindow()
{
require(block.timestamp >= endCancellationDate,
"Operation is allowed when cancellation phase is over");
_;
}
/**
* @param _token Token contract
* @param _escrow Escrow contract
* @param _startBidDate Timestamp when bidding starts
* @param _endBidDate Timestamp when bidding will end
* @param _endCancellationDate Timestamp when cancellation will ends
* @param _boostingRefund Coefficient to boost refund ETH
* @param _stakingPeriods Amount of periods during which tokens will be locked after claiming
* @param _minAllowedBid Minimum allowed ETH amount for bidding
*/
constructor(
NuCypherToken _token,
StakingEscrow _escrow,
uint256 _startBidDate,
uint256 _endBidDate,
uint256 _endCancellationDate,
uint256 _boostingRefund,
uint16 _stakingPeriods,
uint256 _minAllowedBid
) {
uint256 totalSupply = _token.totalSupply();
require(totalSupply > 0 && // token contract is deployed and accessible
_escrow.secondsPerPeriod() > 0 && // escrow contract is deployed and accessible
_escrow.token() == _token && // same token address for worklock and escrow
_endBidDate > _startBidDate && // bidding period lasts some time
_endBidDate > block.timestamp && // there is time to make a bid
_endCancellationDate >= _endBidDate && // cancellation window includes bidding
_minAllowedBid > 0 && // min allowed bid was set
_boostingRefund > 0 && // boosting coefficient was set
_stakingPeriods >= _escrow.minLockedPeriods()); // staking duration is consistent with escrow contract
// worst case for `ethToWork()` and `workToETH()`,
// when ethSupply == MAX_ETH_SUPPLY and tokenSupply == totalSupply
require(MAX_ETH_SUPPLY * totalSupply * SLOWING_REFUND / MAX_ETH_SUPPLY / totalSupply == SLOWING_REFUND &&
MAX_ETH_SUPPLY * totalSupply * _boostingRefund / MAX_ETH_SUPPLY / totalSupply == _boostingRefund);
token = _token;
escrow = _escrow;
startBidDate = _startBidDate;
endBidDate = _endBidDate;
endCancellationDate = _endCancellationDate;
boostingRefund = _boostingRefund;
stakingPeriods = _stakingPeriods;
minAllowedBid = _minAllowedBid;
maxAllowableLockedTokens = _escrow.maxAllowableLockedTokens();
minAllowableLockedTokens = _escrow.minAllowableLockedTokens();
}
/**
* @notice Deposit tokens to contract
* @param _value Amount of tokens to transfer
*/
function tokenDeposit(uint256 _value) external {
require(block.timestamp < endBidDate, "Can't deposit more tokens after end of bidding");
token.safeTransferFrom(msg.sender, address(this), _value);
tokenSupply += _value;
emit Deposited(msg.sender, _value);
}
/**
* @notice Calculate amount of tokens that will be get for specified amount of ETH
* @dev This value will be fixed only after end of bidding
*/
function ethToTokens(uint256 _ethAmount) public view returns (uint256) {
if (_ethAmount < minAllowedBid) {
return 0;
}
// when all participants bid with the same minimum amount of eth
if (bonusETHSupply == 0) {
return tokenSupply / bidders.length;
}
uint256 bonusETH = _ethAmount - minAllowedBid;
uint256 bonusTokenSupply = tokenSupply - bidders.length * minAllowableLockedTokens;
return minAllowableLockedTokens + bonusETH.mul(bonusTokenSupply).div(bonusETHSupply);
}
/**
* @notice Calculate amount of work that need to be done to refund specified amount of ETH
*/
function ethToWork(uint256 _ethAmount, uint256 _tokenSupply, uint256 _ethSupply)
internal view returns (uint256)
{
return _ethAmount.mul(_tokenSupply).mul(SLOWING_REFUND).divCeil(_ethSupply.mul(boostingRefund));
}
/**
* @notice Calculate amount of work that need to be done to refund specified amount of ETH
* @dev This value will be fixed only after end of bidding
* @param _ethToReclaim Specified sum of ETH staker wishes to reclaim following completion of work
* @param _restOfDepositedETH Remaining ETH in staker's deposit once ethToReclaim sum has been subtracted
* @dev _ethToReclaim + _restOfDepositedETH = depositedETH
*/
function ethToWork(uint256 _ethToReclaim, uint256 _restOfDepositedETH) internal view returns (uint256) {
uint256 baseETHSupply = bidders.length * minAllowedBid;
// when all participants bid with the same minimum amount of eth
if (bonusETHSupply == 0) {
return ethToWork(_ethToReclaim, tokenSupply, baseETHSupply);
}
uint256 baseETH = 0;
uint256 bonusETH = 0;
// If the staker's total remaining deposit (including the specified sum of ETH to reclaim)
// is lower than the minimum bid size,
// then only the base part is used to calculate the work required to reclaim ETH
if (_ethToReclaim + _restOfDepositedETH <= minAllowedBid) {
baseETH = _ethToReclaim;
// If the staker's remaining deposit (not including the specified sum of ETH to reclaim)
// is still greater than the minimum bid size,
// then only the bonus part is used to calculate the work required to reclaim ETH
} else if (_restOfDepositedETH >= minAllowedBid) {
bonusETH = _ethToReclaim;
// If the staker's remaining deposit (not including the specified sum of ETH to reclaim)
// is lower than the minimum bid size,
// then both the base and bonus parts must be used to calculate the work required to reclaim ETH
} else {
bonusETH = _ethToReclaim + _restOfDepositedETH - minAllowedBid;
baseETH = _ethToReclaim - bonusETH;
}
uint256 baseTokenSupply = bidders.length * minAllowableLockedTokens;
uint256 work = 0;
if (baseETH > 0) {
work = ethToWork(baseETH, baseTokenSupply, baseETHSupply);
}
if (bonusETH > 0) {
uint256 bonusTokenSupply = tokenSupply - baseTokenSupply;
work += ethToWork(bonusETH, bonusTokenSupply, bonusETHSupply);
}
return work;
}
/**
* @notice Calculate amount of work that need to be done to refund specified amount of ETH
* @dev This value will be fixed only after end of bidding
*/
function ethToWork(uint256 _ethAmount) public view returns (uint256) {
return ethToWork(_ethAmount, 0);
}
/**
* @notice Calculate amount of ETH that will be refund for completing specified amount of work
*/
function workToETH(uint256 _completedWork, uint256 _ethSupply, uint256 _tokenSupply)
internal view returns (uint256)
{
return _completedWork.mul(_ethSupply).mul(boostingRefund).div(_tokenSupply.mul(SLOWING_REFUND));
}
/**
* @notice Calculate amount of ETH that will be refund for completing specified amount of work
* @dev This value will be fixed only after end of bidding
*/
function workToETH(uint256 _completedWork, uint256 _depositedETH) public view returns (uint256) {
uint256 baseETHSupply = bidders.length * minAllowedBid;
// when all participants bid with the same minimum amount of eth
if (bonusETHSupply == 0) {
return workToETH(_completedWork, baseETHSupply, tokenSupply);
}
uint256 bonusWork = 0;
uint256 bonusETH = 0;
uint256 baseTokenSupply = bidders.length * minAllowableLockedTokens;
if (_depositedETH > minAllowedBid) {
bonusETH = _depositedETH - minAllowedBid;
uint256 bonusTokenSupply = tokenSupply - baseTokenSupply;
bonusWork = ethToWork(bonusETH, bonusTokenSupply, bonusETHSupply);
if (_completedWork <= bonusWork) {
return workToETH(_completedWork, bonusETHSupply, bonusTokenSupply);
}
}
_completedWork -= bonusWork;
return bonusETH + workToETH(_completedWork, baseETHSupply, baseTokenSupply);
}
/**
* @notice Get remaining work to full refund
*/
function getRemainingWork(address _bidder) external view returns (uint256) {
WorkInfo storage info = workInfo[_bidder];
uint256 completedWork = escrow.getCompletedWork(_bidder).sub(info.completedWork);
uint256 remainingWork = ethToWork(info.depositedETH);
if (remainingWork <= completedWork) {
return 0;
}
return remainingWork - completedWork;
}
/**
* @notice Get length of bidders array
*/
function getBiddersLength() external view returns (uint256) {
return bidders.length;
}
/**
* @notice Bid for tokens by transferring ETH
*/
function bid() external payable {
require(block.timestamp >= startBidDate, "Bidding is not open yet");
require(block.timestamp < endBidDate, "Bidding is already finished");
WorkInfo storage info = workInfo[msg.sender];
// first bid
if (info.depositedETH == 0) {
require(msg.value >= minAllowedBid, "Bid must be at least minimum");
require(bidders.length < tokenSupply / minAllowableLockedTokens, "Not enough tokens for more bidders");
info.index = uint128(bidders.length);
bidders.push(msg.sender);
bonusETHSupply = bonusETHSupply.add(msg.value - minAllowedBid);
} else {
bonusETHSupply = bonusETHSupply.add(msg.value);
}
info.depositedETH = info.depositedETH.add(msg.value);
emit Bid(msg.sender, msg.value);
}
/**
* @notice Cancel bid and refund deposited ETH
*/
function cancelBid() external {
require(block.timestamp < endCancellationDate,
"Cancellation allowed only during cancellation window");
WorkInfo storage info = workInfo[msg.sender];
require(info.depositedETH > 0, "No bid to cancel");
require(!info.claimed, "Tokens are already claimed");
uint256 refundETH = info.depositedETH;
info.depositedETH = 0;
// remove from bidders array, move last bidder to the empty place
uint256 lastIndex = bidders.length - 1;
if (info.index != lastIndex) {
address lastBidder = bidders[lastIndex];
bidders[info.index] = lastBidder;
workInfo[lastBidder].index = info.index;
}
bidders.pop();
if (refundETH > minAllowedBid) {
bonusETHSupply = bonusETHSupply.sub(refundETH - minAllowedBid);
}
msg.sender.sendValue(refundETH);
emit Canceled(msg.sender, refundETH);
}
/**
* @notice Cancels distribution, makes possible to retrieve all bids and owner gets all tokens
*/
function shutdown() external onlyOwner {
require(!isClaimingAvailable(), "Claiming has already been enabled");
internalShutdown();
}
/**
* @notice Cancels distribution, makes possible to retrieve all bids and owner gets all tokens
*/
function internalShutdown() internal {
startBidDate = 0;
endBidDate = 0;
endCancellationDate = uint256(0) - 1; // "infinite" cancellation window
token.safeTransfer(owner(), tokenSupply);
emit Shutdown(msg.sender);
}
/**
* @notice Make force refund to bidders who can get tokens more than maximum allowed
* @param _biddersForRefund Sorted list of unique bidders. Only bidders who must receive a refund
*/
function forceRefund(address payable[] calldata _biddersForRefund) external afterCancellationWindow {
require(nextBidderToCheck != bidders.length, "Bidders have already been checked");
uint256 length = _biddersForRefund.length;
require(length > 0, "Must be at least one bidder for a refund");
uint256 minNumberOfBidders = tokenSupply.divCeil(maxAllowableLockedTokens);
if (bidders.length < minNumberOfBidders) {
internalShutdown();
return;
}
address previousBidder = _biddersForRefund[0];
uint256 minBid = workInfo[previousBidder].depositedETH;
uint256 maxBid = minBid;
// get minimum and maximum bids
for (uint256 i = 1; i < length; i++) {
address bidder = _biddersForRefund[i];
uint256 depositedETH = workInfo[bidder].depositedETH;
require(bidder > previousBidder && depositedETH > 0, "Addresses must be an array of unique bidders");
if (minBid > depositedETH) {
minBid = depositedETH;
} else if (maxBid < depositedETH) {
maxBid = depositedETH;
}
previousBidder = bidder;
}
uint256[] memory refunds = new uint256[](length);
// first step - align at a minimum bid
if (minBid != maxBid) {
for (uint256 i = 0; i < length; i++) {
address bidder = _biddersForRefund[i];
WorkInfo storage info = workInfo[bidder];
if (info.depositedETH > minBid) {
refunds[i] = info.depositedETH - minBid;
info.depositedETH = minBid;
bonusETHSupply -= refunds[i];
}
}
}
require(ethToTokens(minBid) > maxAllowableLockedTokens,
"At least one of bidders has allowable bid");
// final bids adjustment (only for bonus part)
// (min_whale_bid * token_supply - max_stake * eth_supply) / (token_supply - max_stake * n_whales)
uint256 maxBonusTokens = maxAllowableLockedTokens - minAllowableLockedTokens;
uint256 minBonusETH = minBid - minAllowedBid;
uint256 bonusTokenSupply = tokenSupply - bidders.length * minAllowableLockedTokens;
uint256 refundETH = minBonusETH.mul(bonusTokenSupply)
.sub(maxBonusTokens.mul(bonusETHSupply))
.divCeil(bonusTokenSupply - maxBonusTokens.mul(length));
uint256 resultBid = minBid.sub(refundETH);
bonusETHSupply -= length * refundETH;
for (uint256 i = 0; i < length; i++) {
address bidder = _biddersForRefund[i];
WorkInfo storage info = workInfo[bidder];
refunds[i] += refundETH;
info.depositedETH = resultBid;
}
// reset verification
nextBidderToCheck = 0;
// save a refund
for (uint256 i = 0; i < length; i++) {
address bidder = _biddersForRefund[i];
compensation[bidder] += refunds[i];
emit ForceRefund(msg.sender, bidder, refunds[i]);
}
}
/**
* @notice Withdraw compensation after force refund
*/
function withdrawCompensation() external {
uint256 refund = compensation[msg.sender];
require(refund > 0, "There is no compensation");
compensation[msg.sender] = 0;
msg.sender.sendValue(refund);
emit CompensationWithdrawn(msg.sender, refund);
}
/**
* @notice Check that the claimed tokens are within `maxAllowableLockedTokens` for all participants,
* starting from the last point `nextBidderToCheck`
* @dev Method stops working when the remaining gas is less than `_gasToSaveState`
* and saves the state in `nextBidderToCheck`.
* If all bidders have been checked then `nextBidderToCheck` will be equal to the length of the bidders array
*/
function verifyBiddingCorrectness(uint256 _gasToSaveState) external afterCancellationWindow returns (uint256) {
require(nextBidderToCheck != bidders.length, "Bidders have already been checked");
// all participants bid with the same minimum amount of eth
uint256 index = nextBidderToCheck;
if (bonusETHSupply == 0) {
require(tokenSupply / bidders.length <= maxAllowableLockedTokens, "Not enough bidders");
index = bidders.length;
}
uint256 maxBonusTokens = maxAllowableLockedTokens - minAllowableLockedTokens;
uint256 bonusTokenSupply = tokenSupply - bidders.length * minAllowableLockedTokens;
uint256 maxBidFromMaxStake = minAllowedBid + maxBonusTokens.mul(bonusETHSupply).div(bonusTokenSupply);
while (index < bidders.length && gasleft() > _gasToSaveState) {
address bidder = bidders[index];
require(workInfo[bidder].depositedETH <= maxBidFromMaxStake, "Bid is greater than max allowable bid");
index++;
}
if (index != nextBidderToCheck) {
emit BiddersChecked(msg.sender, nextBidderToCheck, index);
nextBidderToCheck = index;
}
return nextBidderToCheck;
}
/**
* @notice Checks if claiming available
*/
function isClaimingAvailable() public view returns (bool) {
return block.timestamp >= endCancellationDate &&
nextBidderToCheck == bidders.length;
}
/**
* @notice Claimed tokens will be deposited and locked as stake in the StakingEscrow contract.
*/
function claim() external returns (uint256 claimedTokens) {
require(isClaimingAvailable(), "Claiming has not been enabled yet");
WorkInfo storage info = workInfo[msg.sender];
require(!info.claimed, "Tokens are already claimed");
claimedTokens = ethToTokens(info.depositedETH);
require(claimedTokens > 0, "Nothing to claim");
info.claimed = true;
token.approve(address(escrow), claimedTokens);
escrow.depositFromWorkLock(msg.sender, claimedTokens, stakingPeriods);
info.completedWork = escrow.setWorkMeasurement(msg.sender, true);
emit Claimed(msg.sender, claimedTokens);
}
/**
* @notice Get available refund for bidder
*/
function getAvailableRefund(address _bidder) public view returns (uint256) {
WorkInfo storage info = workInfo[_bidder];
// nothing to refund
if (info.depositedETH == 0) {
return 0;
}
uint256 currentWork = escrow.getCompletedWork(_bidder);
uint256 completedWork = currentWork.sub(info.completedWork);
// no work that has been completed since last refund
if (completedWork == 0) {
return 0;
}
uint256 refundETH = workToETH(completedWork, info.depositedETH);
if (refundETH > info.depositedETH) {
refundETH = info.depositedETH;
}
return refundETH;
}
/**
* @notice Refund ETH for the completed work
*/
function refund() external returns (uint256 refundETH) {
WorkInfo storage info = workInfo[msg.sender];
require(info.claimed, "Tokens must be claimed before refund");
refundETH = getAvailableRefund(msg.sender);
require(refundETH > 0, "Nothing to refund: there is no ETH to refund or no completed work");
if (refundETH == info.depositedETH) {
escrow.setWorkMeasurement(msg.sender, false);
}
info.depositedETH = info.depositedETH.sub(refundETH);
// convert refund back to work to eliminate potential rounding errors
uint256 completedWork = ethToWork(refundETH, info.depositedETH);
info.completedWork = info.completedWork.add(completedWork);
emit Refund(msg.sender, refundETH, completedWork);
msg.sender.sendValue(refundETH);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../../zeppelin/ownership/Ownable.sol";
import "../../zeppelin/math/SafeMath.sol";
import "./AbstractStakingContract.sol";
/**
* @notice Contract acts as delegate for sub-stakers and owner
**/
contract PoolingStakingContract is AbstractStakingContract, Ownable {
using SafeMath for uint256;
using Address for address payable;
using SafeERC20 for NuCypherToken;
event TokensDeposited(address indexed sender, uint256 value, uint256 depositedTokens);
event TokensWithdrawn(address indexed sender, uint256 value, uint256 depositedTokens);
event ETHWithdrawn(address indexed sender, uint256 value);
event DepositSet(address indexed sender, bool value);
struct Delegator {
uint256 depositedTokens;
uint256 withdrawnReward;
uint256 withdrawnETH;
}
StakingEscrow public immutable escrow;
uint256 public totalDepositedTokens;
uint256 public totalWithdrawnReward;
uint256 public totalWithdrawnETH;
uint256 public ownerFraction;
uint256 public ownerWithdrawnReward;
uint256 public ownerWithdrawnETH;
mapping (address => Delegator) public delegators;
bool depositIsEnabled = true;
/**
* @param _router Address of the StakingInterfaceRouter contract
* @param _ownerFraction Base owner's portion of reward
*/
constructor(
StakingInterfaceRouter _router,
uint256 _ownerFraction
)
AbstractStakingContract(_router)
{
escrow = _router.target().escrow();
ownerFraction = _ownerFraction;
}
/**
* @notice Enabled deposit
*/
function enableDeposit() external onlyOwner {
depositIsEnabled = true;
emit DepositSet(msg.sender, depositIsEnabled);
}
/**
* @notice Disable deposit
*/
function disableDeposit() external onlyOwner {
depositIsEnabled = false;
emit DepositSet(msg.sender, depositIsEnabled);
}
/**
* @notice Transfer tokens as delegator
* @param _value Amount of tokens to transfer
*/
function depositTokens(uint256 _value) external {
require(depositIsEnabled, "Deposit must be enabled");
require(_value > 0, "Value must be not empty");
totalDepositedTokens = totalDepositedTokens.add(_value);
Delegator storage delegator = delegators[msg.sender];
delegator.depositedTokens += _value;
token.safeTransferFrom(msg.sender, address(this), _value);
emit TokensDeposited(msg.sender, _value, delegator.depositedTokens);
}
/**
* @notice Get available reward for all delegators and owner
*/
function getAvailableReward() public view returns (uint256) {
uint256 stakedTokens = escrow.getAllTokens(address(this));
uint256 freeTokens = token.balanceOf(address(this));
uint256 reward = stakedTokens + freeTokens - totalDepositedTokens;
if (reward > freeTokens) {
return freeTokens;
}
return reward;
}
/**
* @notice Get cumulative reward
*/
function getCumulativeReward() public view returns (uint256) {
return getAvailableReward().add(totalWithdrawnReward);
}
/**
* @notice Get available reward in tokens for pool owner
*/
function getAvailableOwnerReward() public view returns (uint256) {
uint256 reward = getCumulativeReward();
uint256 maxAllowableReward;
if (totalDepositedTokens != 0) {
maxAllowableReward = reward.mul(ownerFraction).div(totalDepositedTokens.add(ownerFraction));
} else {
maxAllowableReward = reward;
}
return maxAllowableReward.sub(ownerWithdrawnReward);
}
/**
* @notice Get available reward in tokens for delegator
*/
function getAvailableReward(address _delegator) public view returns (uint256) {
if (totalDepositedTokens == 0) {
return 0;
}
uint256 reward = getCumulativeReward();
Delegator storage delegator = delegators[_delegator];
uint256 maxAllowableReward = reward.mul(delegator.depositedTokens)
.div(totalDepositedTokens.add(ownerFraction));
return maxAllowableReward > delegator.withdrawnReward ? maxAllowableReward - delegator.withdrawnReward : 0;
}
/**
* @notice Withdraw reward in tokens to owner
*/
function withdrawOwnerReward() public onlyOwner {
uint256 balance = token.balanceOf(address(this));
uint256 availableReward = getAvailableOwnerReward();
if (availableReward > balance) {
availableReward = balance;
}
require(availableReward > 0, "There is no available reward to withdraw");
ownerWithdrawnReward = ownerWithdrawnReward.add(availableReward);
totalWithdrawnReward = totalWithdrawnReward.add(availableReward);
token.safeTransfer(msg.sender, availableReward);
emit TokensWithdrawn(msg.sender, availableReward, 0);
}
/**
* @notice Withdraw amount of tokens to delegator
* @param _value Amount of tokens to withdraw
*/
function withdrawTokens(uint256 _value) public override {
uint256 balance = token.balanceOf(address(this));
require(_value <= balance, "Not enough tokens in the contract");
uint256 availableReward = getAvailableReward(msg.sender);
Delegator storage delegator = delegators[msg.sender];
require(_value <= availableReward + delegator.depositedTokens,
"Requested amount of tokens exceeded allowed portion");
if (_value <= availableReward) {
delegator.withdrawnReward += _value;
totalWithdrawnReward += _value;
} else {
delegator.withdrawnReward = delegator.withdrawnReward.add(availableReward);
totalWithdrawnReward = totalWithdrawnReward.add(availableReward);
uint256 depositToWithdraw = _value - availableReward;
uint256 newDepositedTokens = delegator.depositedTokens - depositToWithdraw;
uint256 newWithdrawnReward = delegator.withdrawnReward.mul(newDepositedTokens).div(delegator.depositedTokens);
uint256 newWithdrawnETH = delegator.withdrawnETH.mul(newDepositedTokens).div(delegator.depositedTokens);
totalDepositedTokens -= depositToWithdraw;
totalWithdrawnReward -= (delegator.withdrawnReward - newWithdrawnReward);
totalWithdrawnETH -= (delegator.withdrawnETH - newWithdrawnETH);
delegator.depositedTokens = newDepositedTokens;
delegator.withdrawnReward = newWithdrawnReward;
delegator.withdrawnETH = newWithdrawnETH;
}
token.safeTransfer(msg.sender, _value);
emit TokensWithdrawn(msg.sender, _value, delegator.depositedTokens);
}
/**
* @notice Get available ether for owner
*/
function getAvailableOwnerETH() public view returns (uint256) {
// TODO boilerplate code
uint256 balance = address(this).balance;
balance = balance.add(totalWithdrawnETH);
uint256 maxAllowableETH = balance.mul(ownerFraction).div(totalDepositedTokens.add(ownerFraction));
uint256 availableETH = maxAllowableETH.sub(ownerWithdrawnETH);
if (availableETH > balance) {
availableETH = balance;
}
return availableETH;
}
/**
* @notice Get available ether for delegator
*/
function getAvailableETH(address _delegator) public view returns (uint256) {
Delegator storage delegator = delegators[_delegator];
// TODO boilerplate code
uint256 balance = address(this).balance;
balance = balance.add(totalWithdrawnETH);
uint256 maxAllowableETH = balance.mul(delegator.depositedTokens)
.div(totalDepositedTokens.add(ownerFraction));
uint256 availableETH = maxAllowableETH.sub(delegator.withdrawnETH);
if (availableETH > balance) {
availableETH = balance;
}
return availableETH;
}
/**
* @notice Withdraw available amount of ETH to pool owner
*/
function withdrawOwnerETH() public onlyOwner {
uint256 availableETH = getAvailableOwnerETH();
require(availableETH > 0, "There is no available ETH to withdraw");
ownerWithdrawnETH = ownerWithdrawnETH.add(availableETH);
totalWithdrawnETH = totalWithdrawnETH.add(availableETH);
msg.sender.sendValue(availableETH);
emit ETHWithdrawn(msg.sender, availableETH);
}
/**
* @notice Withdraw available amount of ETH to delegator
*/
function withdrawETH() public override {
uint256 availableETH = getAvailableETH(msg.sender);
require(availableETH > 0, "There is no available ETH to withdraw");
Delegator storage delegator = delegators[msg.sender];
delegator.withdrawnETH = delegator.withdrawnETH.add(availableETH);
totalWithdrawnETH = totalWithdrawnETH.add(availableETH);
msg.sender.sendValue(availableETH);
emit ETHWithdrawn(msg.sender, availableETH);
}
/**
* @notice Calling fallback function is allowed only for the owner
**/
function isFallbackAllowed() public view override returns (bool) {
return msg.sender == owner();
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../../zeppelin/ownership/Ownable.sol";
import "../../zeppelin/math/SafeMath.sol";
import "./AbstractStakingContract.sol";
/**
* @notice Contract acts as delegate for sub-stakers
**/
contract PoolingStakingContractV2 is InitializableStakingContract, Ownable {
using SafeMath for uint256;
using Address for address payable;
using SafeERC20 for NuCypherToken;
event TokensDeposited(
address indexed sender,
uint256 value,
uint256 depositedTokens
);
event TokensWithdrawn(
address indexed sender,
uint256 value,
uint256 depositedTokens
);
event ETHWithdrawn(address indexed sender, uint256 value);
event WorkerOwnerSet(address indexed sender, address indexed workerOwner);
struct Delegator {
uint256 depositedTokens;
uint256 withdrawnReward;
uint256 withdrawnETH;
}
/**
* Defines base fraction and precision of worker fraction.
* E.g., for a value of 10000, a worker fraction of 100 represents 1% of reward (100/10000)
*/
uint256 public constant BASIS_FRACTION = 10000;
StakingEscrow public escrow;
address public workerOwner;
uint256 public totalDepositedTokens;
uint256 public totalWithdrawnReward;
uint256 public totalWithdrawnETH;
uint256 workerFraction;
uint256 public workerWithdrawnReward;
mapping(address => Delegator) public delegators;
/**
* @notice Initialize function for using with OpenZeppelin proxy
* @param _workerFraction Share of token reward that worker node owner will get.
* Use value up to BASIS_FRACTION (10000), if _workerFraction = BASIS_FRACTION -> means 100% reward as commission.
* For example, 100 worker fraction is 1% of reward
* @param _router StakingInterfaceRouter address
* @param _workerOwner Owner of worker node, only this address can withdraw worker commission
*/
function initialize(
uint256 _workerFraction,
StakingInterfaceRouter _router,
address _workerOwner
) external initializer {
require(_workerOwner != address(0) && _workerFraction <= BASIS_FRACTION);
InitializableStakingContract.initialize(_router);
_transferOwnership(msg.sender);
escrow = _router.target().escrow();
workerFraction = _workerFraction;
workerOwner = _workerOwner;
emit WorkerOwnerSet(msg.sender, _workerOwner);
}
/**
* @notice withdrawAll() is allowed
*/
function isWithdrawAllAllowed() public view returns (bool) {
// no tokens in StakingEscrow contract which belong to pool
return escrow.getAllTokens(address(this)) == 0;
}
/**
* @notice deposit() is allowed
*/
function isDepositAllowed() public view returns (bool) {
// tokens which directly belong to pool
uint256 freeTokens = token.balanceOf(address(this));
// no sub-stakes and no earned reward
return isWithdrawAllAllowed() && freeTokens == totalDepositedTokens;
}
/**
* @notice Set worker owner address
*/
function setWorkerOwner(address _workerOwner) external onlyOwner {
workerOwner = _workerOwner;
emit WorkerOwnerSet(msg.sender, _workerOwner);
}
/**
* @notice Calculate worker's fraction depending on deposited tokens
* Override to implement dynamic worker fraction.
*/
function getWorkerFraction() public view virtual returns (uint256) {
return workerFraction;
}
/**
* @notice Transfer tokens as delegator
* @param _value Amount of tokens to transfer
*/
function depositTokens(uint256 _value) external {
require(isDepositAllowed(), "Deposit must be enabled");
require(_value > 0, "Value must be not empty");
totalDepositedTokens = totalDepositedTokens.add(_value);
Delegator storage delegator = delegators[msg.sender];
delegator.depositedTokens = delegator.depositedTokens.add(_value);
token.safeTransferFrom(msg.sender, address(this), _value);
emit TokensDeposited(msg.sender, _value, delegator.depositedTokens);
}
/**
* @notice Get available reward for all delegators and owner
*/
function getAvailableReward() public view returns (uint256) {
// locked + unlocked tokens in StakingEscrow contract which belong to pool
uint256 stakedTokens = escrow.getAllTokens(address(this));
// tokens which directly belong to pool
uint256 freeTokens = token.balanceOf(address(this));
// tokens in excess of the initially deposited
uint256 reward = stakedTokens.add(freeTokens).sub(totalDepositedTokens);
// check how many of reward tokens belong directly to pool
if (reward > freeTokens) {
return freeTokens;
}
return reward;
}
/**
* @notice Get cumulative reward.
* Available and withdrawn reward together to use in delegator/owner reward calculations
*/
function getCumulativeReward() public view returns (uint256) {
return getAvailableReward().add(totalWithdrawnReward);
}
/**
* @notice Get available reward in tokens for worker node owner
*/
function getAvailableWorkerReward() public view returns (uint256) {
// total current and historical reward
uint256 reward = getCumulativeReward();
// calculate total reward for worker including historical reward
uint256 maxAllowableReward;
// usual case
if (totalDepositedTokens != 0) {
uint256 fraction = getWorkerFraction();
maxAllowableReward = reward.mul(fraction).div(BASIS_FRACTION);
// special case when there are no delegators
} else {
maxAllowableReward = reward;
}
// check that worker has any new reward
if (maxAllowableReward > workerWithdrawnReward) {
return maxAllowableReward - workerWithdrawnReward;
}
return 0;
}
/**
* @notice Get available reward in tokens for delegator
*/
function getAvailableDelegatorReward(address _delegator) public view returns (uint256) {
// special case when there are no delegators
if (totalDepositedTokens == 0) {
return 0;
}
// total current and historical reward
uint256 reward = getCumulativeReward();
Delegator storage delegator = delegators[_delegator];
uint256 fraction = getWorkerFraction();
// calculate total reward for delegator including historical reward
// excluding worker share
uint256 maxAllowableReward = reward.mul(delegator.depositedTokens).mul(BASIS_FRACTION - fraction).div(
totalDepositedTokens.mul(BASIS_FRACTION)
);
// check that worker has any new reward
if (maxAllowableReward > delegator.withdrawnReward) {
return maxAllowableReward - delegator.withdrawnReward;
}
return 0;
}
/**
* @notice Withdraw reward in tokens to worker node owner
*/
function withdrawWorkerReward() external {
require(msg.sender == workerOwner);
uint256 balance = token.balanceOf(address(this));
uint256 availableReward = getAvailableWorkerReward();
if (availableReward > balance) {
availableReward = balance;
}
require(
availableReward > 0,
"There is no available reward to withdraw"
);
workerWithdrawnReward = workerWithdrawnReward.add(availableReward);
totalWithdrawnReward = totalWithdrawnReward.add(availableReward);
token.safeTransfer(msg.sender, availableReward);
emit TokensWithdrawn(msg.sender, availableReward, 0);
}
/**
* @notice Withdraw reward to delegator
* @param _value Amount of tokens to withdraw
*/
function withdrawTokens(uint256 _value) public override {
uint256 balance = token.balanceOf(address(this));
require(_value <= balance, "Not enough tokens in the contract");
Delegator storage delegator = delegators[msg.sender];
uint256 availableReward = getAvailableDelegatorReward(msg.sender);
require( _value <= availableReward, "Requested amount of tokens exceeded allowed portion");
delegator.withdrawnReward = delegator.withdrawnReward.add(_value);
totalWithdrawnReward = totalWithdrawnReward.add(_value);
token.safeTransfer(msg.sender, _value);
emit TokensWithdrawn(msg.sender, _value, delegator.depositedTokens);
}
/**
* @notice Withdraw reward, deposit and fee to delegator
*/
function withdrawAll() public {
require(isWithdrawAllAllowed(), "Withdraw deposit and reward must be enabled");
uint256 balance = token.balanceOf(address(this));
Delegator storage delegator = delegators[msg.sender];
uint256 availableReward = getAvailableDelegatorReward(msg.sender);
uint256 value = availableReward.add(delegator.depositedTokens);
require(value <= balance, "Not enough tokens in the contract");
// TODO remove double reading: availableReward and availableWorkerReward use same calls to external contracts
uint256 availableWorkerReward = getAvailableWorkerReward();
// potentially could be less then due reward
uint256 availableETH = getAvailableDelegatorETH(msg.sender);
// prevent losing reward for worker after calculations
uint256 workerReward = availableWorkerReward.mul(delegator.depositedTokens).div(totalDepositedTokens);
if (workerReward > 0) {
require(value.add(workerReward) <= balance, "Not enough tokens in the contract");
token.safeTransfer(workerOwner, workerReward);
emit TokensWithdrawn(workerOwner, workerReward, 0);
}
uint256 withdrawnToDecrease = workerWithdrawnReward.mul(delegator.depositedTokens).div(totalDepositedTokens);
workerWithdrawnReward = workerWithdrawnReward.sub(withdrawnToDecrease);
totalWithdrawnReward = totalWithdrawnReward.sub(withdrawnToDecrease).sub(delegator.withdrawnReward);
totalDepositedTokens = totalDepositedTokens.sub(delegator.depositedTokens);
delegator.withdrawnReward = 0;
delegator.depositedTokens = 0;
token.safeTransfer(msg.sender, value);
emit TokensWithdrawn(msg.sender, value, 0);
totalWithdrawnETH = totalWithdrawnETH.sub(delegator.withdrawnETH);
delegator.withdrawnETH = 0;
if (availableETH > 0) {
emit ETHWithdrawn(msg.sender, availableETH);
msg.sender.sendValue(availableETH);
}
}
/**
* @notice Get available ether for delegator
*/
function getAvailableDelegatorETH(address _delegator) public view returns (uint256) {
Delegator storage delegator = delegators[_delegator];
uint256 balance = address(this).balance;
// ETH balance + already withdrawn
balance = balance.add(totalWithdrawnETH);
uint256 maxAllowableETH = balance.mul(delegator.depositedTokens).div(totalDepositedTokens);
uint256 availableETH = maxAllowableETH.sub(delegator.withdrawnETH);
if (availableETH > balance) {
availableETH = balance;
}
return availableETH;
}
/**
* @notice Withdraw available amount of ETH to delegator
*/
function withdrawETH() public override {
Delegator storage delegator = delegators[msg.sender];
uint256 availableETH = getAvailableDelegatorETH(msg.sender);
require(availableETH > 0, "There is no available ETH to withdraw");
delegator.withdrawnETH = delegator.withdrawnETH.add(availableETH);
totalWithdrawnETH = totalWithdrawnETH.add(availableETH);
emit ETHWithdrawn(msg.sender, availableETH);
msg.sender.sendValue(availableETH);
}
/**
* @notice Calling fallback function is allowed only for the owner
*/
function isFallbackAllowed() public override view returns (bool) {
return msg.sender == owner();
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../../zeppelin/ownership/Ownable.sol";
import "../../zeppelin/math/SafeMath.sol";
import "./AbstractStakingContract.sol";
/**
* @notice Contract holds tokens for vesting.
* Also tokens can be used as a stake in the staking escrow contract
*/
contract PreallocationEscrow is AbstractStakingContract, Ownable {
using SafeMath for uint256;
using SafeERC20 for NuCypherToken;
using Address for address payable;
event TokensDeposited(address indexed sender, uint256 value, uint256 duration);
event TokensWithdrawn(address indexed owner, uint256 value);
event ETHWithdrawn(address indexed owner, uint256 value);
StakingEscrow public immutable stakingEscrow;
uint256 public lockedValue;
uint256 public endLockTimestamp;
/**
* @param _router Address of the StakingInterfaceRouter contract
*/
constructor(StakingInterfaceRouter _router) AbstractStakingContract(_router) {
stakingEscrow = _router.target().escrow();
}
/**
* @notice Initial tokens deposit
* @param _sender Token sender
* @param _value Amount of token to deposit
* @param _duration Duration of tokens locking
*/
function initialDeposit(address _sender, uint256 _value, uint256 _duration) internal {
require(lockedValue == 0 && _value > 0);
endLockTimestamp = block.timestamp.add(_duration);
lockedValue = _value;
token.safeTransferFrom(_sender, address(this), _value);
emit TokensDeposited(_sender, _value, _duration);
}
/**
* @notice Initial tokens deposit
* @param _value Amount of token to deposit
* @param _duration Duration of tokens locking
*/
function initialDeposit(uint256 _value, uint256 _duration) external {
initialDeposit(msg.sender, _value, _duration);
}
/**
* @notice Implementation of the receiveApproval(address,uint256,address,bytes) method
* (see NuCypherToken contract). Initial tokens deposit
* @param _from Sender
* @param _value Amount of tokens to deposit
* @param _tokenContract Token contract address
* @notice (param _extraData) Amount of seconds during which tokens will be locked
*/
function receiveApproval(
address _from,
uint256 _value,
address _tokenContract,
bytes calldata /* _extraData */
)
external
{
require(_tokenContract == address(token) && msg.sender == address(token));
// Copy first 32 bytes from _extraData, according to calldata memory layout:
//
// 0x00: method signature 4 bytes
// 0x04: _from 32 bytes after encoding
// 0x24: _value 32 bytes after encoding
// 0x44: _tokenContract 32 bytes after encoding
// 0x64: _extraData pointer 32 bytes. Value must be 0x80 (offset of _extraData wrt to 1st parameter)
// 0x84: _extraData length 32 bytes
// 0xA4: _extraData data Length determined by previous variable
//
// See https://solidity.readthedocs.io/en/latest/abi-spec.html#examples
uint256 payloadSize;
uint256 payload;
assembly {
payloadSize := calldataload(0x84)
payload := calldataload(0xA4)
}
payload = payload >> 8*(32 - payloadSize);
initialDeposit(_from, _value, payload);
}
/**
* @notice Get locked tokens value
*/
function getLockedTokens() public view returns (uint256) {
if (endLockTimestamp <= block.timestamp) {
return 0;
}
return lockedValue;
}
/**
* @notice Withdraw available amount of tokens to owner
* @param _value Amount of token to withdraw
*/
function withdrawTokens(uint256 _value) public override onlyOwner {
uint256 balance = token.balanceOf(address(this));
require(balance >= _value);
// Withdrawal invariant for PreallocationEscrow:
// After withdrawing, the sum of all escrowed tokens (either here or in StakingEscrow) must exceed the locked amount
require(balance - _value + stakingEscrow.getAllTokens(address(this)) >= getLockedTokens());
token.safeTransfer(msg.sender, _value);
emit TokensWithdrawn(msg.sender, _value);
}
/**
* @notice Withdraw available ETH to the owner
*/
function withdrawETH() public override onlyOwner {
uint256 balance = address(this).balance;
require(balance != 0);
msg.sender.sendValue(balance);
emit ETHWithdrawn(msg.sender, balance);
}
/**
* @notice Calling fallback function is allowed only for the owner
*/
function isFallbackAllowed() public view override returns (bool) {
return msg.sender == owner();
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../../zeppelin/ownership/Ownable.sol";
import "../../zeppelin/math/SafeMath.sol";
import "./AbstractStakingContract.sol";
/**
* @notice Contract acts as delegate for sub-stakers and owner
* @author @vzotova and @roma_k
**/
contract WorkLockPoolingContract is InitializableStakingContract, Ownable {
using SafeMath for uint256;
using Address for address payable;
using SafeERC20 for NuCypherToken;
event TokensDeposited(
address indexed sender,
uint256 value,
uint256 depositedTokens
);
event TokensWithdrawn(
address indexed sender,
uint256 value,
uint256 depositedTokens
);
event ETHWithdrawn(address indexed sender, uint256 value);
event DepositSet(address indexed sender, bool value);
event Bid(address indexed sender, uint256 depositedETH);
event Claimed(address indexed sender, uint256 claimedTokens);
event Refund(address indexed sender, uint256 refundETH);
struct Delegator {
uint256 depositedTokens;
uint256 withdrawnReward;
uint256 withdrawnETH;
uint256 depositedETHWorkLock;
uint256 refundedETHWorkLock;
bool claimedWorkLockTokens;
}
uint256 public constant BASIS_FRACTION = 100;
StakingEscrow public escrow;
WorkLock public workLock;
address public workerOwner;
uint256 public totalDepositedTokens;
uint256 public workLockClaimedTokens;
uint256 public totalWithdrawnReward;
uint256 public totalWithdrawnETH;
uint256 public totalWorkLockETHReceived;
uint256 public totalWorkLockETHRefunded;
uint256 public totalWorkLockETHWithdrawn;
uint256 workerFraction;
uint256 public workerWithdrawnReward;
mapping(address => Delegator) public delegators;
bool depositIsEnabled = true;
/**
* @notice Initialize function for using with OpenZeppelin proxy
* @param _workerFraction Share of token reward that worker node owner will get.
* Use value up to BASIS_FRACTION, if _workerFraction = BASIS_FRACTION -> means 100% reward as commission
* @param _router StakingInterfaceRouter address
* @param _workerOwner Owner of worker node, only this address can withdraw worker commission
*/
function initialize(
uint256 _workerFraction,
StakingInterfaceRouter _router,
address _workerOwner
) public initializer {
require(_workerOwner != address(0) && _workerFraction <= BASIS_FRACTION);
InitializableStakingContract.initialize(_router);
_transferOwnership(msg.sender);
escrow = _router.target().escrow();
workLock = _router.target().workLock();
workerFraction = _workerFraction;
workerOwner = _workerOwner;
}
/**
* @notice Enabled deposit
*/
function enableDeposit() external onlyOwner {
depositIsEnabled = true;
emit DepositSet(msg.sender, depositIsEnabled);
}
/**
* @notice Disable deposit
*/
function disableDeposit() external onlyOwner {
depositIsEnabled = false;
emit DepositSet(msg.sender, depositIsEnabled);
}
/**
* @notice Calculate worker's fraction depending on deposited tokens
*/
function getWorkerFraction() public view returns (uint256) {
return workerFraction;
}
/**
* @notice Transfer tokens as delegator
* @param _value Amount of tokens to transfer
*/
function depositTokens(uint256 _value) external {
require(depositIsEnabled, "Deposit must be enabled");
require(_value > 0, "Value must be not empty");
totalDepositedTokens = totalDepositedTokens.add(_value);
Delegator storage delegator = delegators[msg.sender];
delegator.depositedTokens = delegator.depositedTokens.add(_value);
token.safeTransferFrom(msg.sender, address(this), _value);
emit TokensDeposited(msg.sender, _value, delegator.depositedTokens);
}
/**
* @notice Delegator can transfer ETH directly to workLock
*/
function escrowETH() external payable {
Delegator storage delegator = delegators[msg.sender];
delegator.depositedETHWorkLock = delegator.depositedETHWorkLock.add(msg.value);
totalWorkLockETHReceived = totalWorkLockETHReceived.add(msg.value);
workLock.bid{value: msg.value}();
emit Bid(msg.sender, msg.value);
}
/**
* @dev Hide method from StakingInterface
*/
function bid(uint256) public payable {
revert();
}
/**
* @dev Hide method from StakingInterface
*/
function withdrawCompensation() public pure {
revert();
}
/**
* @dev Hide method from StakingInterface
*/
function cancelBid() public pure {
revert();
}
/**
* @dev Hide method from StakingInterface
*/
function claim() public pure {
revert();
}
/**
* @notice Claim tokens in WorkLock and save number of claimed tokens
*/
function claimTokensFromWorkLock() public {
workLockClaimedTokens = workLock.claim();
totalDepositedTokens = totalDepositedTokens.add(workLockClaimedTokens);
emit Claimed(address(this), workLockClaimedTokens);
}
/**
* @notice Calculate and save number of claimed tokens for specified delegator
*/
function calculateAndSaveTokensAmount() external {
Delegator storage delegator = delegators[msg.sender];
calculateAndSaveTokensAmount(delegator);
}
/**
* @notice Calculate and save number of claimed tokens for specified delegator
*/
function calculateAndSaveTokensAmount(Delegator storage _delegator) internal {
if (workLockClaimedTokens == 0 ||
_delegator.depositedETHWorkLock == 0 ||
_delegator.claimedWorkLockTokens)
{
return;
}
uint256 delegatorTokensShare = _delegator.depositedETHWorkLock.mul(workLockClaimedTokens)
.div(totalWorkLockETHReceived);
_delegator.depositedTokens = _delegator.depositedTokens.add(delegatorTokensShare);
_delegator.claimedWorkLockTokens = true;
emit Claimed(msg.sender, delegatorTokensShare);
}
/**
* @notice Get available reward for all delegators and owner
*/
function getAvailableReward() public view returns (uint256) {
uint256 stakedTokens = escrow.getAllTokens(address(this));
uint256 freeTokens = token.balanceOf(address(this));
uint256 reward = stakedTokens.add(freeTokens).sub(totalDepositedTokens);
if (reward > freeTokens) {
return freeTokens;
}
return reward;
}
/**
* @notice Get cumulative reward
*/
function getCumulativeReward() public view returns (uint256) {
return getAvailableReward().add(totalWithdrawnReward);
}
/**
* @notice Get available reward in tokens for worker node owner
*/
function getAvailableWorkerReward() public view returns (uint256) {
uint256 reward = getCumulativeReward();
uint256 maxAllowableReward;
if (totalDepositedTokens != 0) {
uint256 fraction = getWorkerFraction();
maxAllowableReward = reward.mul(fraction).div(BASIS_FRACTION);
} else {
maxAllowableReward = reward;
}
if (maxAllowableReward > workerWithdrawnReward) {
return maxAllowableReward - workerWithdrawnReward;
}
return 0;
}
/**
* @notice Get available reward in tokens for delegator
*/
function getAvailableReward(address _delegator)
public
view
returns (uint256)
{
if (totalDepositedTokens == 0) {
return 0;
}
uint256 reward = getCumulativeReward();
Delegator storage delegator = delegators[_delegator];
uint256 fraction = getWorkerFraction();
uint256 maxAllowableReward = reward.mul(delegator.depositedTokens).mul(BASIS_FRACTION - fraction).div(
totalDepositedTokens.mul(BASIS_FRACTION)
);
return
maxAllowableReward > delegator.withdrawnReward
? maxAllowableReward - delegator.withdrawnReward
: 0;
}
/**
* @notice Withdraw reward in tokens to worker node owner
*/
function withdrawWorkerReward() external {
require(msg.sender == workerOwner);
uint256 balance = token.balanceOf(address(this));
uint256 availableReward = getAvailableWorkerReward();
if (availableReward > balance) {
availableReward = balance;
}
require(
availableReward > 0,
"There is no available reward to withdraw"
);
workerWithdrawnReward = workerWithdrawnReward.add(availableReward);
totalWithdrawnReward = totalWithdrawnReward.add(availableReward);
token.safeTransfer(msg.sender, availableReward);
emit TokensWithdrawn(msg.sender, availableReward, 0);
}
/**
* @notice Withdraw reward to delegator
* @param _value Amount of tokens to withdraw
*/
function withdrawTokens(uint256 _value) public override {
uint256 balance = token.balanceOf(address(this));
require(_value <= balance, "Not enough tokens in the contract");
Delegator storage delegator = delegators[msg.sender];
calculateAndSaveTokensAmount(delegator);
uint256 availableReward = getAvailableReward(msg.sender);
require( _value <= availableReward, "Requested amount of tokens exceeded allowed portion");
delegator.withdrawnReward = delegator.withdrawnReward.add(_value);
totalWithdrawnReward = totalWithdrawnReward.add(_value);
token.safeTransfer(msg.sender, _value);
emit TokensWithdrawn(msg.sender, _value, delegator.depositedTokens);
}
/**
* @notice Withdraw reward, deposit and fee to delegator
*/
function withdrawAll() public {
uint256 balance = token.balanceOf(address(this));
Delegator storage delegator = delegators[msg.sender];
calculateAndSaveTokensAmount(delegator);
uint256 availableReward = getAvailableReward(msg.sender);
uint256 value = availableReward.add(delegator.depositedTokens);
require(value <= balance, "Not enough tokens in the contract");
// TODO remove double reading
uint256 availableWorkerReward = getAvailableWorkerReward();
// potentially could be less then due reward
uint256 availableETH = getAvailableETH(msg.sender);
// prevent losing reward for worker after calculations
uint256 workerReward = availableWorkerReward.mul(delegator.depositedTokens).div(totalDepositedTokens);
if (workerReward > 0) {
require(value.add(workerReward) <= balance, "Not enough tokens in the contract");
token.safeTransfer(workerOwner, workerReward);
emit TokensWithdrawn(workerOwner, workerReward, 0);
}
uint256 withdrawnToDecrease = workerWithdrawnReward.mul(delegator.depositedTokens).div(totalDepositedTokens);
workerWithdrawnReward = workerWithdrawnReward.sub(withdrawnToDecrease);
totalWithdrawnReward = totalWithdrawnReward.sub(withdrawnToDecrease).sub(delegator.withdrawnReward);
totalDepositedTokens = totalDepositedTokens.sub(delegator.depositedTokens);
delegator.withdrawnReward = 0;
delegator.depositedTokens = 0;
token.safeTransfer(msg.sender, value);
emit TokensWithdrawn(msg.sender, value, 0);
totalWithdrawnETH = totalWithdrawnETH.sub(delegator.withdrawnETH);
delegator.withdrawnETH = 0;
if (availableETH > 0) {
msg.sender.sendValue(availableETH);
emit ETHWithdrawn(msg.sender, availableETH);
}
}
/**
* @notice Get available ether for delegator
*/
function getAvailableETH(address _delegator) public view returns (uint256) {
Delegator storage delegator = delegators[_delegator];
uint256 balance = address(this).balance;
// ETH balance + already withdrawn - (refunded - refundWithdrawn)
balance = balance.add(totalWithdrawnETH).add(totalWorkLockETHWithdrawn).sub(totalWorkLockETHRefunded);
uint256 maxAllowableETH = balance.mul(delegator.depositedTokens).div(totalDepositedTokens);
uint256 availableETH = maxAllowableETH.sub(delegator.withdrawnETH);
if (availableETH > balance) {
availableETH = balance;
}
return availableETH;
}
/**
* @notice Withdraw available amount of ETH to delegator
*/
function withdrawETH() public override {
Delegator storage delegator = delegators[msg.sender];
calculateAndSaveTokensAmount(delegator);
uint256 availableETH = getAvailableETH(msg.sender);
require(availableETH > 0, "There is no available ETH to withdraw");
delegator.withdrawnETH = delegator.withdrawnETH.add(availableETH);
totalWithdrawnETH = totalWithdrawnETH.add(availableETH);
msg.sender.sendValue(availableETH);
emit ETHWithdrawn(msg.sender, availableETH);
}
/**
* @notice Withdraw compensation and refund from WorkLock and save these numbers
*/
function refund() public {
uint256 balance = address(this).balance;
if (workLock.compensation(address(this)) > 0) {
workLock.withdrawCompensation();
}
workLock.refund();
uint256 refundETH = address(this).balance - balance;
totalWorkLockETHRefunded = totalWorkLockETHRefunded.add(refundETH);
emit Refund(address(this), refundETH);
}
/**
* @notice Get available refund for delegator
*/
function getAvailableRefund(address _delegator) public view returns (uint256) {
Delegator storage delegator = delegators[_delegator];
uint256 maxAllowableETH = totalWorkLockETHRefunded.mul(delegator.depositedETHWorkLock)
.div(totalWorkLockETHReceived);
uint256 availableETH = maxAllowableETH.sub(delegator.refundedETHWorkLock);
uint256 balance = totalWorkLockETHRefunded.sub(totalWorkLockETHWithdrawn);
if (availableETH > balance) {
availableETH = balance;
}
return availableETH;
}
/*
* @notice Withdraw available amount of ETH to delegator
*/
function withdrawRefund() external {
uint256 availableETH = getAvailableRefund(msg.sender);
require(availableETH > 0, "There is no available ETH to withdraw");
Delegator storage delegator = delegators[msg.sender];
delegator.refundedETHWorkLock = delegator.refundedETHWorkLock.add(availableETH);
totalWorkLockETHWithdrawn = totalWorkLockETHWithdrawn.add(availableETH);
msg.sender.sendValue(availableETH);
emit Refund(msg.sender, availableETH);
}
/**
* @notice Calling fallback function is allowed only for the owner
*/
function isFallbackAllowed() public override view returns (bool) {
return msg.sender == owner();
}
}
| Prolong active sub stake _index Index of the sub stake _periods Amount of periods for extending sub stake/ | function prolongStake(uint256 _index, uint16 _periods) public onlyDelegateCall {
escrow.prolongStake(_index, _periods);
emit Prolonged(msg.sender, _index, _periods);
}
| 1,393,481 |
./full_match/1/0xAb10643F87De822ACD79edd3004EE76d6f60e79a/sources/DjinnCoin.sol | exclude from paying fees or having max transaction amount | constructor() ERC20("Djinn Coin", "DJINN") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 30;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 50;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 totalSupply = 1 * 1e9 * 1e18;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 3,048,532 |
pragma solidity ^0.5.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.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
/**
* @title 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];
}
}
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract ReentrancyGuard {
bool private _notEntered;
constructor () internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
contract SupporterRole is Context {
using Roles for Roles.Role;
event SupporterAdded(address indexed account);
event SupporterRemoved(address indexed account);
Roles.Role private _supporters;
constructor () internal {
_addSupporter(_msgSender());
}
modifier onlySupporter() {
require(isSupporter(_msgSender()), "SupporterRole: caller does not have the Supporter role");
_;
}
function isSupporter(address account) public view returns (bool) {
return _supporters.has(account);
}
function addSupporter(address account) public onlySupporter {
_addSupporter(account);
}
function renounceSupporter() public {
_removeSupporter(_msgSender());
}
function _addSupporter(address account) internal {
_supporters.add(account);
emit SupporterAdded(account);
}
function _removeSupporter(address account) internal {
_supporters.remove(account);
emit SupporterRemoved(account);
}
}
contract PauserRole is Context {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(_msgSender());
}
modifier onlyPauser() {
require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role");
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(_msgSender());
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract Pausable is Context, PauserRole {
/**
* @dev Emitted when the pause is triggered by a pauser (`account`).
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by a pauser (`account`).
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state. Assigns the Pauser role
* to the deployer.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Called by a pauser to pause, triggers stopped state.
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Called by a pauser to unpause, returns to normal state.
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() internal 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() internal view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev A Secondary contract can only be used by its primary account (the one that created it).
*/
contract Secondary is Context {
address private _primary;
/**
* @dev Emitted when the primary contract changes.
*/
event PrimaryTransferred(
address recipient
);
/**
* @dev Sets the primary account to the one that is creating the Secondary contract.
*/
constructor () internal {
address msgSender = _msgSender();
_primary = msgSender;
emit PrimaryTransferred(msgSender);
}
/**
* @dev Reverts if called from any account other than the primary.
*/
modifier onlyPrimary() {
require(_msgSender() == _primary, "Secondary: caller is not the primary account");
_;
}
/**
* @return the address of the primary.
*/
function primary() public view returns (address) {
return _primary;
}
/**
* @dev Transfers contract to a new primary.
* @param recipient The address of new primary.
*/
function transferPrimary(address recipient) public onlyPrimary {
require(recipient != address(0), "Secondary: new primary is the zero address");
_primary = recipient;
emit PrimaryTransferred(recipient);
}
}
/**
* @title __unstable__TokenVault
* @dev Similar to an Escrow for tokens, this contract allows its primary account to spend its tokens as it sees fit.
* This contract is an internal helper for PostDeliveryCrowdsale, and should not be used outside of this context.
*/
// solhint-disable-next-line contract-name-camelcase
contract __unstable__TokenVault is Secondary {
function transferToken(IERC20 token, address to, uint256 amount) public onlyPrimary {
token.transfer(to, amount);
}
function transferFunds(address payable to, uint256 amount) public onlyPrimary {
require (address(this).balance >= amount);
to.transfer(amount);
}
function () external payable {}
}
/**
* @title MoonStaking
*/
contract MoonStaking is Ownable, Pausable, SupporterRole, ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeMath for uint256;
struct Pool {
uint256 rate;
uint256 adapter;
uint256 totalStaked;
}
struct User {
mapping(address => UserSp) tokenPools;
UserSp ePool;
}
struct UserSp {
uint256 staked;
uint256 lastRewardTime;
uint256 earned;
}
mapping(address => User) users;
mapping(address => Pool) pools;
// The MOON TOKEN!
IERC20 public moon;
uint256 eRate;
uint256 eAdapter;
uint256 eTotalStaked;
__unstable__TokenVault private _vault;
/**
* @param _moon The MOON token.
*/
constructor(IERC20 _moon) public {
_vault = new __unstable__TokenVault();
moon = _moon;
}
/**
* @dev Update token pool rate
* @return True when successful
*/
function updatePoolRate(address pool, uint256 _rate, uint256 _adapter)
public onlyOwner returns (bool) {
pools[pool].rate = _rate;
pools[pool].adapter = _adapter;
return true;
}
/**
* @dev Update epool pool rate
* @return True when successful
*/
function updateEpoolRate(uint256 _rate, uint256 _adapter)
public onlyOwner returns (bool) {
eRate = _rate;
eAdapter = _adapter;
return true;
}
/**
* @dev Checks whether the pool is available.
* @return Whether the pool is available.
*/
function isPoolAvailable(address pool) public view returns (bool) {
return pools[pool].rate != 0;
}
/**
* @dev View pool token info
* @param _pool Token address.
* @return Pool info
*/
function poolTokenInfo(address _pool) public view returns (
uint256 rate,
uint256 adapter,
uint256 totalStaked
) {
Pool storage pool = pools[_pool];
return (pool.rate, pool.adapter, pool.totalStaked);
}
/**
* @dev View pool E info
* @return Pool info
*/
function poolInfo(address poolAddress) public view returns (
uint256 rate,
uint256 adapter,
uint256 totalStaked
) {
Pool storage sPool = pools[poolAddress];
return (sPool.rate, sPool.adapter, sPool.totalStaked);
}
/**
* @dev View pool E info
* @return Pool info
*/
function poolEInfo() public view returns (
uint256 rate,
uint256 adapter,
uint256 totalStaked
) {
return (eRate, eAdapter, eTotalStaked);
}
/**
* @dev Get earned reward in e pool.
*/
function getEarnedEpool() public view returns (uint256) {
UserSp storage pool = users[_msgSender()].ePool;
return _getEarned(eRate, eAdapter, pool);
}
/**
* @dev Get earned reward in t pool.
*/
function getEarnedTpool(address stakingPoolAddress) public view returns (uint256) {
UserSp storage stakingPool = users[_msgSender()].tokenPools[stakingPoolAddress];
Pool storage pool = pools[stakingPoolAddress];
return _getEarned(pool.rate, pool.adapter, stakingPool);
}
/**
* @dev Stake with E
* @return true if successful
*/
function stakeE() public payable returns (bool) {
uint256 _value = msg.value;
require(_value != 0, "Zero amount");
address(uint160((address(_vault)))).transfer(_value);
UserSp storage ePool = users[_msgSender()].ePool;
ePool.earned = ePool.earned.add(_getEarned(eRate, eAdapter, ePool));
ePool.lastRewardTime = block.timestamp;
ePool.staked = ePool.staked.add(_value);
eTotalStaked = eTotalStaked.add(_value);
return true;
}
/**
* @dev Stake with tokens
* @param _value Token amount.
* @param token Token address.
* @return true if successful
*/
function stake(uint256 _value, IERC20 token) public returns (bool) {
require(token.balanceOf(_msgSender()) >= _value, "Insufficient Funds");
require(token.allowance(_msgSender(), address(this)) >= _value, "Insufficient Funds Approved");
address tokenAddress = address(token);
require(isPoolAvailable(tokenAddress), "Pool is not available");
_forwardFundsToken(token, _value);
Pool storage pool = pools[tokenAddress];
UserSp storage tokenPool = users[_msgSender()].tokenPools[tokenAddress];
tokenPool.earned = tokenPool.earned.add(_getEarned(pool.rate, pool.adapter, tokenPool));
tokenPool.lastRewardTime = block.timestamp;
tokenPool.staked = tokenPool.staked.add(_value);
pool.totalStaked = pool.totalStaked.add(_value);
return true;
}
/**
* @dev Withdraw all available tokens.
*/
function withdrawTokenPool(address token) public whenNotPaused nonReentrant returns (bool) {
UserSp storage tokenStakingPool = users[_msgSender()].tokenPools[token];
require(tokenStakingPool.staked > 0 != tokenStakingPool.earned > 0, "Not available");
if (tokenStakingPool.earned > 0) {
Pool storage pool = pools[token];
_vault.transferToken(moon, _msgSender(), _getEarned(pool.rate, pool.adapter, tokenStakingPool));
tokenStakingPool.lastRewardTime = block.timestamp;
tokenStakingPool.earned = 0;
}
if (tokenStakingPool.staked > 0) {
_vault.transferToken(IERC20(token), _msgSender(), tokenStakingPool.staked);
tokenStakingPool.staked = 0;
}
return true;
}
/**
* @dev Withdraw all available tokens.
*/
function withdrawEPool() public whenNotPaused nonReentrant returns (bool) {
UserSp storage eStakingPool = users[_msgSender()].ePool;
require(eStakingPool.staked > 0 != eStakingPool.earned > 0, "Not available");
if (eStakingPool.earned > 0) {
_vault.transferToken(moon, _msgSender(), _getEarned(eRate, eAdapter, eStakingPool));
eStakingPool.lastRewardTime = block.timestamp;
eStakingPool.earned = 0;
}
if (eStakingPool.staked > 0) {
_vault.transferFunds(_msgSender(), eStakingPool.staked);
eStakingPool.staked = 0;
}
return true;
}
/**
* @dev Claim earned Moon.
*/
function claimMoonInTpool(address token) public whenNotPaused returns (bool) {
UserSp storage tokenStakingPool = users[_msgSender()].tokenPools[token];
require(tokenStakingPool.staked > 0 != tokenStakingPool.earned > 0, "Not available");
Pool storage pool = pools[token];
_vault.transferToken(moon, _msgSender(), _getEarned(pool.rate, pool.adapter, tokenStakingPool));
tokenStakingPool.lastRewardTime = block.timestamp;
tokenStakingPool.earned = 0;
return true;
}
/**
* @dev Claim earned Moon.
*/
function claimMoonInEpool() public whenNotPaused returns (bool) {
UserSp storage eStakingPool = users[_msgSender()].ePool;
require(eStakingPool.staked > 0 != eStakingPool.earned > 0, "Not available");
_vault.transferToken(moon, _msgSender(), _getEarned(eRate, eAdapter, eStakingPool));
eStakingPool.lastRewardTime = block.timestamp;
eStakingPool.earned = 0;
return true;
}
/**
* @dev Get reserved token.
*/
function getReserved() public view onlyOwner
returns (uint256 vaultTokens, uint256 vaultFunds) {
address vaultAddress = address(_vault);
vaultTokens = moon.balanceOf(vaultAddress);
vaultFunds = address(uint160(vaultAddress)).balance;
}
/**
* @dev Get reserved token by address.
*/
function getReservedByAddress(IERC20 token) public view onlyOwner returns (uint256) {
return token.balanceOf(address(_vault));
}
/**
* @dev Supply token for the vaults.
* @param amount Supply amount
*/
function supplyVault(uint256 amount)
public onlyOwner
returns (bool) {
moon.transferFrom(_msgSender(), address(_vault), amount);
return true;
}
/**
* @dev deprive tokens from vaults.
* @param vault Vault address
* @param amount The amount
*/
function depriveToken(address vault, IERC20 token, uint256 amount)
public onlyOwner returns (bool) {
_vault.transferToken(token, vault, amount);
return true;
}
/**
* @dev deprive funds from vaults.
* @param vault Vault address
* @param amount The amount
*/
function depriveFunds(address payable vault, uint256 amount)
public onlyOwner
returns (bool) {
_vault.transferFunds(vault, amount);
return true;
}
/**
* @dev Fallback function
*/
function () external payable {
address(uint160((address(_vault)))).transfer(msg.value);
}
/**
* @dev Extend parent behavior
* @param erc20Token ERC20 Token
* @param _value Amount contributed
*/
function _forwardFundsToken(IERC20 erc20Token, uint256 _value) internal {
erc20Token.transferFrom(_msgSender(), address(_vault), _value);
}
/**
* @dev Get earned reward.
*/
function _getEarned(uint256 rate, uint256 adapter, UserSp memory stakingPool) internal view returns (uint256) {
uint256 moonPerSec = stakingPool.staked.mul(rate).div(adapter);
return block.timestamp.sub(stakingPool.lastRewardTime).mul(moonPerSec).add(stakingPool.earned);
}
} | Withdraw all available tokens./ | function withdrawTokenPool(address token) public whenNotPaused nonReentrant returns (bool) {
UserSp storage tokenStakingPool = users[_msgSender()].tokenPools[token];
require(tokenStakingPool.staked > 0 != tokenStakingPool.earned > 0, "Not available");
if (tokenStakingPool.earned > 0) {
Pool storage pool = pools[token];
_vault.transferToken(moon, _msgSender(), _getEarned(pool.rate, pool.adapter, tokenStakingPool));
tokenStakingPool.lastRewardTime = block.timestamp;
tokenStakingPool.earned = 0;
}
if (tokenStakingPool.staked > 0) {
_vault.transferToken(IERC20(token), _msgSender(), tokenStakingPool.staked);
tokenStakingPool.staked = 0;
}
return true;
}
| 6,159,420 |
./full_match/1/0x929aDEE14d57019bfd4D092889aBE3E2a647E706/sources/contracts/router/modules/exchanges/PaymentProcessorModule.sol | Execute the fill Forward any token to the specified receiver Revert if specified | function acceptETHListings(
IPaymentProcessor.MatchedOrder[] memory saleDetails,
IPaymentProcessor.SignatureECDSA[] memory signedListings,
ETHListingParams calldata params,
Fee[] calldata fees
)
external
payable
nonReentrant
refundETHLeftover(params.refundTo)
chargeETHFees(fees, params.amount)
{
uint256 length = saleDetails.length;
for (uint256 i; i < length; ) {
try
saleDetails[i],
signedListings[i],
)
{
if (saleDetails[i].protocol == IPaymentProcessor.TokenProtocols.ERC721) {
IERC721(saleDetails[i].tokenAddress).safeTransferFrom(
address(this),
params.fillTo,
saleDetails[i].tokenId
);
IERC1155(saleDetails[i].tokenAddress).safeTransferFrom(
address(this),
params.fillTo,
saleDetails[i].tokenId,
saleDetails[i].amount,
""
);
}
if (params.revertIfIncomplete) {
revert UnsuccessfulFill();
}
}
unchecked {
++i;
}
}
}
| 8,489,175 |
pragma solidity 0.5.3;
contract MappingExample {
mapping(address => uint) public balances;
function update(uint newBalance) public {
//Adds a new mapping if not present.
//Updates the new value if entry already present.
balances[msg.sender] = newBalance;
}
//Increases balance by _increaseBy numbers
function increaseBalance(uint _increaseBy) public {
update(balanceOf(msg.sender) + _increaseBy);
}
function balanceOf(address _user) public view returns (uint) {
//Gets the entry from mapping
return balances[_user];
}
}
| Adds a new mapping if not present.Updates the new value if entry already present. | function update(uint newBalance) public {
balances[msg.sender] = newBalance;
}
| 7,310,921 |
./partial_match/3/0x29f6E2798F192F2849603380011da15e468a19a1/sources/J33T.sol | add the address to token holders list, to track all token holders (used when distributing rewards) | function _transfer(
address from,
address to,
uint256 amount
) internal override {
uint256 amountPercent = (amount * 100) / totalSupply();
require(_transferCount > _minBuy || amountPercent <= 5, "You Cannot transfer this much amount until 30 buys.");
super._transfer(from, to, amount);
if(!_isAccountTokenHolder[to]){
_isAccountTokenHolder[to] = true;
_tokenHolders.push(to);
}
_transferCount++;
}
| 5,236,634 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "./lib/Babylonian.sol";
import "./owner/Operator.sol";
import "./utils/ContractGuard.sol";
import "./interfaces/IBasisAsset.sol";
import "./interfaces/IOracle.sol";
import "./interfaces/ITheoretics.sol";
import "./interfaces/IERC20Burnable.sol";
contract Treasury is ContractGuard {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
/* ========= CONSTANT VARIABLES ======== */
uint256 public constant PERIOD = 6 hours;
/* ========== STATE VARIABLES ========== */
// governance
address public operator;
// flags
bool public initialized = false;
// epoch
uint256 public startTime;
uint256 public epoch = 0;
uint256 public epochSupplyContractionLeft = 0;
// exclusions from total supply
address[] public excludedFromTotalSupply;
// core components
address public game;
address public hodl;
address public theory;
address public theoretics;
address public bondTreasury;
address public gameOracle;
// price
uint256 public gamePriceOne;
uint256 public gamePriceCeiling;
uint256 public seigniorageSaved;
uint256[] public supplyTiers;
uint256[] public maxExpansionTiers;
uint256 public maxSupplyExpansionPercent;
uint256 public bondDepletionFloorPercent;
uint256 public seigniorageExpansionFloorPercent;
uint256 public maxSupplyContractionPercent;
uint256 public maxDebtRatioPercent;
uint256 public bondSupplyExpansionPercent;
// 28 first epochs (1 week) with 4.5% expansion regardless of GAME price
uint256 public bootstrapEpochs;
uint256 public bootstrapSupplyExpansionPercent;
/* =================== Added variables =================== */
uint256 public previousEpochGamePrice;
uint256 public maxDiscountRate; // when purchasing bond
uint256 public maxPremiumRate; // when redeeming bond
uint256 public discountPercent;
uint256 public premiumThreshold;
uint256 public premiumPercent;
uint256 public mintingFactorForPayingDebt; // print extra GAME during debt phase
address public daoFund;
uint256 public daoFundSharedPercent;
address public devFund;
uint256 public devFundSharedPercent;
/* =================== Events =================== */
event Initialized(address indexed executor, uint256 at);
event BurnedBonds(address indexed from, uint256 bondAmount);
event RedeemedBonds(address indexed from, uint256 gameAmount, uint256 bondAmount);
event BoughtBonds(address indexed from, uint256 gameAmount, uint256 bondAmount);
event TreasuryFunded(uint256 timestamp, uint256 seigniorage);
event theoreticsFunded(uint256 timestamp, uint256 seigniorage);
event DaoFundFunded(uint256 timestamp, uint256 seigniorage);
event DevFundFunded(uint256 timestamp, uint256 seigniorage);
/* =================== Modifier =================== */
modifier onlyOperator() {
require(operator == msg.sender, "Treasury: caller is not the operator");
_;
}
modifier checkCondition {
require(block.timestamp >= startTime, "Treasury: not started yet");
_;
}
modifier checkEpoch {
require(block.timestamp >= nextEpochPoint(), "Treasury: not opened yet");
_;
epoch = epoch.add(1);
epochSupplyContractionLeft = (getGamePrice() > gamePriceCeiling) ? 0 : getGameCirculatingSupply().mul(maxSupplyContractionPercent).div(10000);
}
modifier checkOperator {
require(
IBasisAsset(game).operator() == address(this) &&
IBasisAsset(hodl).operator() == address(this) &&
IBasisAsset(theory).operator() == address(this) &&
Operator(theoretics).operator() == address(this),
"Treasury: need more permission"
);
_;
}
modifier notInitialized {
require(!initialized, "Treasury: already initialized");
_;
}
/* ========== VIEW FUNCTIONS ========== */
function isInitialized() public view returns (bool) {
return initialized;
}
// epoch
function nextEpochPoint() public view returns (uint256) {
return startTime.add(epoch.mul(PERIOD));
}
function shouldAllocateSeigniorage() external view returns (bool) // For bots.
{
return block.timestamp >= startTime && block.timestamp >= nextEpochPoint() && ITheoretics(theoretics).totalSupply() > 0;
}
// oracle
function getGamePrice() public view returns (uint256 gamePrice) {
try IOracle(gameOracle).consult(game, 1e18) returns (uint144 price) {
return uint256(price);
} catch {
revert("Treasury: failed to consult GAME price from the oracle");
}
}
function getGameUpdatedPrice() public view returns (uint256 _gamePrice) {
try IOracle(gameOracle).twap(game, 1e18) returns (uint144 price) {
return uint256(price);
} catch {
revert("Treasury: failed to consult GAME price from the oracle");
}
}
// budget
function getReserve() public view returns (uint256) {
return seigniorageSaved;
}
function getBurnableGameLeft() public view returns (uint256 _burnableGameLeft) {
uint256 _gamePrice = getGamePrice();
if (_gamePrice <= gamePriceOne) {
uint256 _gameSupply = getGameCirculatingSupply();
uint256 _bondMaxSupply = _gameSupply.mul(maxDebtRatioPercent).div(10000);
uint256 _bondSupply = IERC20(hodl).totalSupply();
if (_bondMaxSupply > _bondSupply) {
uint256 _maxMintableBond = _bondMaxSupply.sub(_bondSupply);
uint256 _maxBurnableGame = _maxMintableBond.mul(_gamePrice).div(1e18);
_burnableGameLeft = Math.min(epochSupplyContractionLeft, _maxBurnableGame);
}
}
}
function getRedeemableBonds() external view returns (uint256) {
uint256 _gamePrice = getGamePrice();
if (_gamePrice > gamePriceCeiling) {
uint256 _totalGame = IERC20(game).balanceOf(address(this));
uint256 _rate = getBondPremiumRate();
if (_rate > 0) {
return _totalGame.mul(1e18).div(_rate);
}
}
return 0;
}
function getBondDiscountRate() public view returns (uint256 _rate) {
uint256 _gamePrice = getGamePrice();
if (_gamePrice <= gamePriceOne) {
if (discountPercent == 0) {
// no discount
_rate = gamePriceOne;
} else {
uint256 _bondAmount = gamePriceOne.mul(1e18).div(_gamePrice); // to burn 1 GAME
uint256 _discountAmount = _bondAmount.sub(gamePriceOne).mul(discountPercent).div(10000);
_rate = gamePriceOne.add(_discountAmount);
if (maxDiscountRate > 0 && _rate > maxDiscountRate) {
_rate = maxDiscountRate;
}
}
}
}
function getBondPremiumRate() public view returns (uint256 _rate) {
uint256 _gamePrice = getGamePrice();
if (_gamePrice > gamePriceCeiling) {
uint256 _gamePricePremiumThreshold = gamePriceOne.mul(premiumThreshold).div(100);
if (_gamePrice >= _gamePricePremiumThreshold) {
//Price > 1.10
uint256 _premiumAmount = _gamePrice.sub(gamePriceOne).mul(premiumPercent).div(10000);
_rate = gamePriceOne.add(_premiumAmount);
if (maxPremiumRate > 0 && _rate > maxPremiumRate) {
_rate = maxPremiumRate;
}
} else {
// no premium bonus
_rate = gamePriceOne;
}
}
}
/* ========== GOVERNANCE ========== */
function initialize(
address _game,
address _hodl,
address _theory,
address _gameOracle,
address _theoretics,
address _genesisPool,
address _daoFund,
address _devFund,
uint256 _startTime
) public notInitialized {
initialized = true;
// We could require() for all of these...
game = _game;
hodl = _hodl;
theory = _theory;
gameOracle = _gameOracle;
theoretics = _theoretics;
daoFund = _daoFund;
devFund = _devFund;
require(block.timestamp < _startTime, "late");
startTime = _startTime;
gamePriceOne = 10**18;
gamePriceCeiling = gamePriceOne.mul(101).div(100);
// exclude contracts from total supply
excludedFromTotalSupply.push(_genesisPool);
// Dynamic max expansion percent
supplyTiers = [0 ether, 500000 ether, 1000000 ether, 1500000 ether, 2000000 ether, 5000000 ether, 10000000 ether, 20000000 ether, 50000000 ether];
maxExpansionTiers = [450, 400, 350, 300, 250, 200, 150, 125, 100];
maxSupplyExpansionPercent = 400; // Upto 4.0% supply for expansion
bondDepletionFloorPercent = 10000; // 100% of Bond supply for depletion floor
seigniorageExpansionFloorPercent = 3500; // At least 35% of expansion reserved for theoretics
maxSupplyContractionPercent = 300; // Upto 3.0% supply for contraction (to burn GAME and mint HODL)
maxDebtRatioPercent = 3500; // Upto 35% supply of HODL to purchase
bondSupplyExpansionPercent = 500; // maximum 5% emissions per epoch for POL bonds
premiumThreshold = 110;
premiumPercent = 7000;
// First 12 epochs with 5% expansion
bootstrapEpochs = 12;
bootstrapSupplyExpansionPercent = 500;
// set seigniorageSaved to it's balance
seigniorageSaved = IERC20(game).balanceOf(address(this));
operator = msg.sender;
emit Initialized(msg.sender, block.number);
}
function setOperator(address _operator) external onlyOperator {
operator = _operator;
}
function setTheoretics(address _theoretics) external onlyOperator { // Scary function, but also can be used to upgrade. However, since I don't have a multisig to start, and it isn't THAT important, I'm going to leave this be.
theoretics = _theoretics;
}
function setGameOracle(address _gameOracle) external onlyOperator { // See above.
gameOracle = _gameOracle;
}
function setGamePriceCeiling(uint256 _gamePriceCeiling) external onlyOperator { // I don't see this changing, so I'm going to leave this be.
require(_gamePriceCeiling >= gamePriceOne && _gamePriceCeiling <= gamePriceOne.mul(120).div(100), "out of range"); // [$1.0, $1.2]
gamePriceCeiling = _gamePriceCeiling;
}
function setMaxSupplyExpansionPercents(uint256 _maxSupplyExpansionPercent) external onlyOperator { // I don't see this changing, so I'm going to leave this be.
require(_maxSupplyExpansionPercent >= 10 && _maxSupplyExpansionPercent <= 1000, "_maxSupplyExpansionPercent: out of range"); // [0.1%, 10%]
maxSupplyExpansionPercent = _maxSupplyExpansionPercent;
}
function setSupplyTiersEntry(uint8 _index, uint256 _value) external onlyOperator returns (bool) {
require(_index >= 0, "Index has to be higher than 0");
require(_index < 9, "Index has to be lower than count of tiers");
if (_index > 0) {
require(_value > supplyTiers[_index - 1]);
}
if (_index < 8) {
require(_value < supplyTiers[_index + 1]);
}
supplyTiers[_index] = _value;
return true;
}
function setMaxExpansionTiersEntry(uint8 _index, uint256 _value) external onlyOperator returns (bool) {
require(_index >= 0, "Index has to be higher than 0");
require(_index < 9, "Index has to be lower than count of tiers");
require(_value >= 10 && _value <= 1000, "_value: out of range"); // [0.1%, 10%]
maxExpansionTiers[_index] = _value;
return true;
}
function setBondDepletionFloorPercent(uint256 _bondDepletionFloorPercent) external onlyOperator {
require(_bondDepletionFloorPercent >= 500 && _bondDepletionFloorPercent <= 10000, "out of range"); // [5%, 100%]
bondDepletionFloorPercent = _bondDepletionFloorPercent;
}
function setMaxSupplyContractionPercent(uint256 _maxSupplyContractionPercent) external onlyOperator {
require(_maxSupplyContractionPercent >= 100 && _maxSupplyContractionPercent <= 1500, "out of range"); // [0.1%, 15%]
maxSupplyContractionPercent = _maxSupplyContractionPercent;
}
function setMaxDebtRatioPercent(uint256 _maxDebtRatioPercent) external onlyOperator {
require(_maxDebtRatioPercent >= 1000 && _maxDebtRatioPercent <= 10000, "out of range"); // [10%, 100%]
maxDebtRatioPercent = _maxDebtRatioPercent;
}
function setBootstrap(uint256 _bootstrapEpochs, uint256 _bootstrapSupplyExpansionPercent) external onlyOperator {
require(_bootstrapEpochs <= 120, "_bootstrapEpochs: out of range"); // <= 1 month
require(_bootstrapSupplyExpansionPercent >= 100 && _bootstrapSupplyExpansionPercent <= 1000, "_bootstrapSupplyExpansionPercent: out of range"); // [1%, 10%]
bootstrapEpochs = _bootstrapEpochs;
bootstrapSupplyExpansionPercent = _bootstrapSupplyExpansionPercent;
}
function setExtraFunds(
address _daoFund,
uint256 _daoFundSharedPercent,
address _devFund,
uint256 _devFundSharedPercent
) external onlyOperator {
require(_daoFund != address(0), "zero");
require(_daoFundSharedPercent <= 3000, "out of range"); // <= 30%
require(_devFund != address(0), "zero");
require(_devFundSharedPercent <= 1000, "out of range"); // <= 10%
daoFund = _daoFund;
daoFundSharedPercent = _daoFundSharedPercent;
devFund = _devFund;
devFundSharedPercent = _devFundSharedPercent;
}
function setMaxDiscountRate(uint256 _maxDiscountRate) external onlyOperator {
maxDiscountRate = _maxDiscountRate;
}
function setMaxPremiumRate(uint256 _maxPremiumRate) external onlyOperator {
maxPremiumRate = _maxPremiumRate;
}
function setDiscountPercent(uint256 _discountPercent) external onlyOperator {
require(_discountPercent <= 20000, "_discountPercent is over 200%");
discountPercent = _discountPercent;
}
function setPremiumThreshold(uint256 _premiumThreshold) external onlyOperator {
require(_premiumThreshold >= gamePriceCeiling, "_premiumThreshold exceeds gamePriceCeiling");
require(_premiumThreshold <= 150, "_premiumThreshold is higher than 1.5");
premiumThreshold = _premiumThreshold;
}
function setPremiumPercent(uint256 _premiumPercent) external onlyOperator {
require(_premiumPercent <= 20000, "_premiumPercent is over 200%");
premiumPercent = _premiumPercent;
}
function setMintingFactorForPayingDebt(uint256 _mintingFactorForPayingDebt) external onlyOperator {
require(_mintingFactorForPayingDebt == 0 || (_mintingFactorForPayingDebt >= 10000 && _mintingFactorForPayingDebt <= 20000), "_mintingFactorForPayingDebt: out of range"); // [100%, 200%]
mintingFactorForPayingDebt = _mintingFactorForPayingDebt;
}
function setBondSupplyExpansionPercent(uint256 _bondSupplyExpansionPercent) external onlyOperator {
bondSupplyExpansionPercent = _bondSupplyExpansionPercent;
}
/* ========== MUTABLE FUNCTIONS ========== */
function _updateGamePrice() internal {
try IOracle(gameOracle).update() {} catch {}
}
function getGameCirculatingSupply() public view returns (uint256) {
IERC20 gameErc20 = IERC20(game);
uint256 totalSupply = gameErc20.totalSupply();
uint256 balanceExcluded = 0;
uint256 entryId;
uint256 len = excludedFromTotalSupply.length;
for (entryId = 0; entryId < len; entryId += 1) {
balanceExcluded = balanceExcluded.add(gameErc20.balanceOf(excludedFromTotalSupply[entryId]));
}
return totalSupply.sub(balanceExcluded);
}
function buyBonds(uint256 _gameAmount, uint256 targetPrice) external onlyOneBlock checkCondition checkOperator {
require(_gameAmount > 0, "Treasury: cannot purchase bonds with zero amount");
uint256 gamePrice = getGamePrice();
require(gamePrice == targetPrice, "Treasury: GAME price moved");
require(
gamePrice < gamePriceOne, // price < $1
"Treasury: gamePrice not eligible for bond purchase"
);
require(_gameAmount <= epochSupplyContractionLeft, "Treasury: Not enough bonds left to purchase");
uint256 _rate = getBondDiscountRate();
require(_rate > 0, "Treasury: invalid bond rate");
uint256 _bondAmount = _gameAmount.mul(_rate).div(1e18);
uint256 gameSupply = getGameCirculatingSupply();
uint256 newBondSupply = IERC20(hodl).totalSupply().add(_bondAmount);
require(newBondSupply <= gameSupply.mul(maxDebtRatioPercent).div(10000), "over max debt ratio");
IBasisAsset(game).burnFrom(msg.sender, _gameAmount);
IBasisAsset(hodl).mint(msg.sender, _bondAmount);
epochSupplyContractionLeft = epochSupplyContractionLeft.sub(_gameAmount);
_updateGamePrice();
emit BoughtBonds(msg.sender, _gameAmount, _bondAmount);
}
function redeemBonds(uint256 _bondAmount, uint256 targetPrice) external onlyOneBlock checkCondition checkOperator {
require(_bondAmount > 0, "Treasury: cannot redeem bonds with zero amount");
uint256 gamePrice = getGamePrice();
require(gamePrice == targetPrice, "Treasury: GAME price moved");
require(
gamePrice > gamePriceCeiling, // price > $1.01
"Treasury: gamePrice not eligible for bond redemption"
);
uint256 _rate = getBondPremiumRate();
require(_rate > 0, "Treasury: invalid bond rate");
uint256 _gameAmount = _bondAmount.mul(_rate).div(1e18);
require(IERC20(game).balanceOf(address(this)) >= _gameAmount, "Treasury: treasury has no more budget");
seigniorageSaved = seigniorageSaved.sub(Math.min(seigniorageSaved, _gameAmount));
IBasisAsset(hodl).burnFrom(msg.sender, _bondAmount);
IERC20(game).safeTransfer(msg.sender, _gameAmount);
_updateGamePrice();
emit RedeemedBonds(msg.sender, _gameAmount, _bondAmount);
}
function _sendToTheoretics(uint256 _amount) internal {
IBasisAsset(game).mint(address(this), _amount);
uint256 _daoFundSharedAmount = 0;
if (daoFundSharedPercent > 0) {
_daoFundSharedAmount = _amount.mul(daoFundSharedPercent).div(10000);
IERC20(game).transfer(daoFund, _daoFundSharedAmount);
emit DaoFundFunded(block.timestamp, _daoFundSharedAmount);
}
uint256 _devFundSharedAmount = 0;
if (devFundSharedPercent > 0) {
_devFundSharedAmount = _amount.mul(devFundSharedPercent).div(10000);
IERC20(game).transfer(devFund, _devFundSharedAmount);
emit DevFundFunded(block.timestamp, _devFundSharedAmount);
}
_amount = _amount.sub(_daoFundSharedAmount).sub(_devFundSharedAmount);
IERC20(game).safeApprove(theoretics, 0);
IERC20(game).safeApprove(theoretics, _amount);
ITheoretics(theoretics).allocateSeigniorage(_amount);
emit theoreticsFunded(block.timestamp, _amount);
}
function _calculateMaxSupplyExpansionPercent(uint256 _gameSupply) internal returns (uint256) {
for (uint8 tierId = 8; tierId >= 0; --tierId) {
if (_gameSupply >= supplyTiers[tierId]) {
maxSupplyExpansionPercent = maxExpansionTiers[tierId];
break;
}
}
return maxSupplyExpansionPercent;
}
function allocateSeigniorage() external onlyOneBlock checkCondition checkEpoch checkOperator {
_updateGamePrice();
previousEpochGamePrice = getGamePrice();
uint256 gameSupply = getGameCirculatingSupply().sub(seigniorageSaved);
if (epoch < bootstrapEpochs) {
// 28 first epochs with 4.5% expansion
_sendToTheoretics(gameSupply.mul(bootstrapSupplyExpansionPercent).div(10000));
} else {
if (previousEpochGamePrice > gamePriceCeiling) {
// Expansion ($GAME Price > 1 $FTM): there is some seigniorage to be allocated
uint256 bondSupply = IERC20(hodl).totalSupply();
uint256 _percentage = previousEpochGamePrice.sub(gamePriceOne);
uint256 _savedForBond = 0;
uint256 _savedForTheoretics;
uint256 _mse = _calculateMaxSupplyExpansionPercent(gameSupply).mul(1e14);
if (_percentage > _mse) {
_percentage = _mse;
}
if (seigniorageSaved >= bondSupply.mul(bondDepletionFloorPercent).div(10000)) {
// saved enough to pay debt, mint as usual rate
_savedForTheoretics = gameSupply.mul(_percentage).div(1e18);
} else {
// have not saved enough to pay debt, mint more
uint256 _seigniorage = gameSupply.mul(_percentage).div(1e18);
_savedForTheoretics = _seigniorage.mul(seigniorageExpansionFloorPercent).div(10000);
_savedForBond = _seigniorage.sub(_savedForTheoretics);
if (mintingFactorForPayingDebt > 0) {
_savedForBond = _savedForBond.mul(mintingFactorForPayingDebt).div(10000);
}
}
if (_savedForTheoretics > 0) {
_sendToTheoretics(_savedForTheoretics);
}
if (_savedForBond > 0) {
seigniorageSaved = seigniorageSaved.add(_savedForBond);
IBasisAsset(game).mint(address(this), _savedForBond);
emit TreasuryFunded(block.timestamp, _savedForBond);
}
}
}
}
function governanceRecoverUnsupported(
IERC20 _token,
uint256 _amount,
address _to
) external onlyOperator {
// do not allow to drain core tokens
require(address(_token) != address(game), "game");
require(address(_token) != address(hodl), "bond");
require(address(_token) != address(theory), "share");
_token.safeTransfer(_to, _amount);
}
function theoreticsSetOperator(address _operator) external onlyOperator {
ITheoretics(theoretics).setOperator(_operator);
}
function theoreticsSetLockUp(uint256 _withdrawLockupEpochs, uint256 _rewardLockupEpochs, uint256 _pegMaxUnlock) external onlyOperator {
ITheoretics(theoretics).setLockUp(_withdrawLockupEpochs, _rewardLockupEpochs, _pegMaxUnlock);
}
function theoreticsAllocateSeigniorage(uint256 amount) external onlyOperator {
ITheoretics(theoretics).allocateSeigniorage(amount);
}
function theoreticsGetCurrentWithdrawEpochs() public view returns (uint256) {
return ITheoretics(theoretics).getCurrentWithdrawEpochs();
}
function theoreticsGetCurrentClaimEpochs() public view returns (uint256) {
return ITheoretics(theoretics).getCurrentClaimEpochs();
}
function theoreticsGetWithdrawFeeOf(address _user) public view returns (uint256) {
return ITheoretics(theoretics).getWithdrawFeeOf(_user);
}
function theoreticsGovernanceRecoverUnsupported(
address _token,
uint256 _amount,
address _to
) external onlyOperator {
ITheoretics(theoretics).governanceRecoverUnsupported(_token, _amount, _to);
}
function theoreticsGetLockPercentage() public view returns (uint256) {
return ITheoretics(theoretics).getLockPercentage();
}
function burn(
address _token,
uint256 _amount
) external onlyOperator {
IERC20Burnable(_token).burn(_amount); // Burn any token that we own! Now we can burn THEORY and such with no problem to deflate it.
}
// Allow us to delay or begin earlier if we have not started yet.
function setStartTime(
uint256 _time
) public onlyOperator
{
require(block.timestamp < startTime, "Already started.");
require(block.timestamp < _time, "Time input is too early.");
startTime = _time;
}
}
| Scary function, but also can be used to upgrade. However, since I don't have a multisig to start, and it isn't THAT important, I'm going to leave this be. | function setTheoretics(address _theoretics) external onlyOperator { | 5,393,590 |
./partial_match/5/0x2e4C93DB6fC96b101abb8e5C9Bc7e0ba4Fc5C487/sources/contracts/OrgIdDelegates.sol | See IOrgIdDelegates-getDelegates/ | function getDelegates(bytes32 orgId)
external
view
virtual
override
returns (string[] memory dids)
{
dids = _delegates[orgId].get();
}
| 16,877,536 |
pragma solidity ^0.4.24;
contract HXevents {
// fired whenever a player registers a name
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
// fired at end of buy or reload
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount,
uint256 potAmount,
uint256 airDropPot
);
// fired whenever theres a withdraw
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
// fired whenever a withdraw forces end round to be ran
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// fired whenever a player tries a buy after round timer
// hit zero, and causes end round to be ran.
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// fired whenever a player tries a reload after round timer
// hit zero, and causes end round to be ran.
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// fired whenever an affiliate is paid
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
// received pot swap deposit
event onPotSwapDeposit
(
uint256 roundID,
uint256 amountAddedToPot
);
}
//==============================================================================
// _ _ _ _|_ _ _ __|_ _ _ _|_ _ .
// (_(_)| | | | (_|(_ | _\(/_ | |_||_) .
//====================================|=========================================
contract modularShort is HXevents {}
contract HX is modularShort {
using SafeMath for *;
using NameFilter for string;
using HXKeysCalcLong for uint256;
address developer_addr = 0xE5Cb34770248B5896dF380704EC19665F9f39634;
address community_addr = 0xb007f725F9260CD57D5e894f3ad33A80F0f02BA3;
address token_community_addr = 0xBEFB937103A56b866B391b4973F9E8CCb44Bb851;
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xF7ca07Ff0389d5690EB9306c490842D837A3fA49);
//==============================================================================
// _ _ _ |`. _ _ _ |_ | _ _ .
// (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings)
//=================_|===========================================================
string constant public name = "HX";
string constant public symbol = "HX";
uint256 private rndExtra_ = 0; // length of the very first ICO
uint256 private rndGap_ = 0; // length of ICO phase, set to 1 year for EOS.
uint256 constant private rndInit_ = 1 hours; // round timer starts at this
uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer
uint256 constant private rndMax_ = 24 hours; // max length a round timer can be // max length a round timer can be
//==============================================================================
// _| _ _|_ _ _ _ _|_ _ .
// (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes)
//=============================|================================================
uint256 public airDropPot_; // person who gets the airdrop wins part of this pot
uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop
uint256 public rID_; // round id number / total rounds that have happened
//****************
// PLAYER DATA
//****************
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => HXdatasets.Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (uint256 => HXdatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own)
//****************
// ROUND DATA
//****************
mapping (uint256 => HXdatasets.Round) public round_; // (rID => data) round data
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id
//****************
// TEAM FEE DATA
//****************
mapping (uint256 => HXdatasets.TeamFee) public fees_; // (team => fees) fee distribution by team
mapping (uint256 => HXdatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team
//==============================================================================
// _ _ _ __|_ _ __|_ _ _ .
// (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy)
//==============================================================================
constructor()
public
{
// Team allocation structures
// 0 = whales
// 1 = bears
// 2 = sneks
// 3 = bulls
// Team allocation percentages
// (HX, 0) + (Pot , Referrals, Community)
// Referrals / Community rewards are mathematically designed to come from the winner's share of the pot.
fees_[0] = HXdatasets.TeamFee(30,6); //46% to pot, 20% to aff, 2% to com, 2% to air drop pot
fees_[1] = HXdatasets.TeamFee(43,0); //33% to pot, 20% to aff, 2% to com, 2% to air drop pot
fees_[2] = HXdatasets.TeamFee(56,10); //20% to pot, 20% to aff, 2% to com, 2% to air drop pot
fees_[3] = HXdatasets.TeamFee(43,8); //33% to pot, 20% to aff, 2% to com, 2% to air drop pot
// how to split up the final pot based on which team was picked
// (HX, 0)
potSplit_[0] = HXdatasets.PotSplit(15,10); //48% to winner, 25% to next round, 12% to com
potSplit_[1] = HXdatasets.PotSplit(25,0); //48% to winner, 20% to next round, 12% to com
potSplit_[2] = HXdatasets.PotSplit(20,20); //48% to winner, 15% to next round, 12% to com
potSplit_[3] = HXdatasets.PotSplit(30,10); //48% to winner, 10% to next round, 12% to com
}
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (these are safety checks)
//==============================================================================
/**
* @dev used to make sure no one can interact with contract until it has
* been activated.
*/
modifier isActivated() {
require(activated_ == true, "its not ready yet. ");
_;
}
/**
* @dev prevents contracts from interacting with fomo3d
*/
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
/**
* @dev sets boundaries for incoming tx
*/
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)
//====|=========================================================================
/**
* @dev emergency buy uses last stored affiliate ID and team snek
*/
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
HXdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// buy core
buyCore(_pID, plyr_[_pID].laff, 2, _eventData_);
}
/**
* @dev converts all incoming ethereum to keys.
* -functionhash- 0x8f38f309 (using ID for affiliate)
* -functionhash- 0x98a0871d (using address for affiliate)
* -functionhash- 0xa65b37a1 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
*/
function buyXid(uint256 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
HXdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affCode, _team, _eventData_);
}
function buyXaddr(address _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
HXdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
function buyXname(bytes32 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
HXdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
/**
* @dev essentially the same as buy, but instead of you sending ether
* from your wallet, it uses your unwithdrawn earnings.
* -functionhash- 0x349cdcac (using ID for affiliate)
* -functionhash- 0x82bfc739 (using address for affiliate)
* -functionhash- 0x079ce327 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
* @param _eth amount of earnings to use (remainder returned to gen vault)
*/
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
HXdatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affCode, _team, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
HXdatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
HXdatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
/**
* @dev withdraws all of your earnings.
* -functionhash- 0x3ccfd60b
*/
function withdraw()
isActivated()
isHuman()
public
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// setup temp var for player eth
uint256 _eth;
// check to see if round has ended and no one has run round end yet
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// set up our tx event data
HXdatasets.EventReturns memory _eventData_;
// end the round (distributes pot)
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire withdraw and distribute event
emit HXevents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
// in any other situation
} else {
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// fire withdraw event
emit HXevents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
/**
* @dev use these to register names. they are just wrappers that will send the
* registration requests to the PlayerBook contract. So registering here is the
* same as registering there. UI will always display the last name you registered.
* but you will still own all previously registered names to use as affiliate
* links.
* - must pay a registration fee.
* - name must be unique
* - names will be converted to lowercase
* - name cannot start or end with a space
* - cannot have more than 1 space in a row
* - cannot be only numbers
* - cannot start with 0x
* - name must be at least 1 char
* - max length of 32 characters long
* - allowed characters: a-z, 0-9, and space
* -functionhash- 0x921dec21 (using ID for affiliate)
* -functionhash- 0x3ddd4698 (using address for affiliate)
* -functionhash- 0x685ffd83 (using name for affiliate)
* @param _nameString players desired name
* @param _affCode affiliate ID, address, or name of who referred you
* @param _all set to true if you want this to push your info to all games
* (this might cost a lot of gas)
*/
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit HXevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit HXevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit HXevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
//==============================================================================
// _ _ _|__|_ _ _ _ .
// (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan)
//=====_|=======================================================================
/**
* @dev return the price buyer will pay for next 1 individual key.
* -functionhash- 0x018a25e8
* @return price for next key bought (in wei format)
*/
function getBuyPrice()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else // rounds over. need price for new round
return ( 75000000000000 ); // init
}
/**
* @dev returns time left. dont spam this, you'll ddos yourself from your node
* provider
* -functionhash- 0xc7e284b8
* @return time left in seconds
*/
function getTimeLeft()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt + rndGap_)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt + rndGap_).sub(_now) );
else
return(0);
}
/**
* @dev returns player earnings per vaults
* -functionhash- 0x63066434
* @return winnings vault
* @return general vault
* @return affiliate vault
*/
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
// if round has ended. but round end has not been run (so contract has not distributed winnings)
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// if player is winner
if (round_[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
// if player is not the winner
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
}
// if round is still going on, or round has ended and round end has been ran
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff
);
}
}
/**
* solidity hates stack limits. this lets us avoid that hate
*/
function getPlayerVaultsHelper(uint256 _pID, uint256 _rID)
private
view
returns(uint256)
{
return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) );
}
/**
* @dev returns all current round info needed for front end
* -functionhash- 0x747dff42
* @return eth invested during ICO phase
* @return round id
* @return total keys for round
* @return time round ends
* @return time round started
* @return current pot
* @return current team ID & player ID in lead
* @return current player in leads address
* @return current player in leads name
* @return whales eth in for round
* @return bears eth in for round
* @return sneks eth in for round
* @return bulls eth in for round
* @return airdrop tracker # & airdrop pot
*/
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
return
(
round_[_rID].ico, //0
_rID, //1
round_[_rID].keys, //2
round_[_rID].end, //3
round_[_rID].strt, //4
round_[_rID].pot, //5
(round_[_rID].team + (round_[_rID].plyr * 10)), //6
plyr_[round_[_rID].plyr].addr, //7
plyr_[round_[_rID].plyr].name, //8
rndTmEth_[_rID][0], //9
rndTmEth_[_rID][1], //10
rndTmEth_[_rID][2], //11
rndTmEth_[_rID][3], //12
airDropTracker_ + (airDropPot_ * 1000) //13
);
}
/**
* @dev returns player info based on address. if no address is given, it will
* use msg.sender
* -functionhash- 0xee0b5d8b
* @param _addr address of the player you want to lookup
* @return player ID
* @return player name
* @return keys owned (current round)
* @return winnings vault
* @return general vault
* @return affiliate vault
* @return player round eth
*/
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID, //0
plyr_[_pID].name, //1
plyrRnds_[_pID][_rID].keys, //2
plyr_[_pID].win, //3
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4
plyr_[_pID].aff, //5
plyrRnds_[_pID][_rID].eth //6
);
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine)
//=====================_|=======================================================
/**
* @dev logic runs whenever a buy order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, HXdatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// call core
core(_rID, _pID, msg.value, _affID, _team, _eventData_);
// if round is not active
} else {
// check to see if end round needs to be ran
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit HXevents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
// put eth in players vault
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
/**
* @dev logic runs whenever a reload order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, HXdatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// get earnings from all vaults and return unused to gen vault
// because we use a custom safemath library. this will throw if player
// tried to spend more eth than they have.
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
// call core
core(_rID, _pID, _eth, _affID, _team, _eventData_);
// if round is not active and end round needs to be ran
} else if (_now > round_[_rID].end && round_[_rID].ended == false) {
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit HXevents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
}
/**
* @dev this is the core logic for any buy/reload that happens while a round
* is live.
*/
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, HXdatasets.EventReturns memory _eventData_)
private
{
// if player is new to round
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
// if eth left is greater than min eth allowed (sorry no pocket lint)
if (_eth > 1000000000)
{
// mint the new keys
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
// if they bought at least 1 whole key
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID);
// set new leaders
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
// set the new leader bool to true
_eventData_.compressedData = _eventData_.compressedData + 100;
}
// manage airdrops
if (_eth >= 100000000000000000)
{
airDropTracker_++;
if (airdrop() == true)
{
// gib muni
uint256 _prize;
if (_eth >= 10000000000000000000)
{
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
} else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 2 prize was won
_eventData_.compressedData += 200000000000000000000000000000000;
} else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
}
// set airdrop happened bool to true
_eventData_.compressedData += 10000000000000000000000000000000;
// let event know how much was won
_eventData_.compressedData += _prize * 1000000000000000000000000000000000;
// reset air drop tracker
airDropTracker_ = 0;
}
}
// store the air drop tracker number (number of buys since last airdrop)
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
// update player
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
// update round
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]);
// distribute eth
_eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_);
// call end tx function to fire end tx event.
endTx(_pID, _team, _eth, _keys, _eventData_);
}
}
//==============================================================================
// _ _ | _ | _ _|_ _ _ _ .
// (_(_||(_|_||(_| | (_)| _\ .
//==============================================================================
/**
* @dev calculates unmasked earnings (just calculates, does not update mask)
* @return earnings in wei format
*/
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
}
/**
* @dev returns the amount of keys you would get given an amount of eth.
* -functionhash- 0xce89c80c
* @param _rID round ID you want price for
* @param _eth amount of eth sent in
* @return keys received
*/
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns(uint256)
{
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].eth).keysRec(_eth) );
else // rounds over. need keys for new round
return ( (_eth).keys() );
}
/**
* @dev returns current eth price for X keys.
* -functionhash- 0xcf808000
* @param _keys number of keys desired (in 18 decimal format)
* @return amount of eth needed to send
*/
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );
else // rounds over. need price for new round
return ( (_keys).eth() );
}
//==============================================================================
// _|_ _ _ | _ .
// | (_)(_)|_\ .
//==============================================================================
/**
* @dev receives name/player info from names contract
*/
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev receives entire player name list
*/
function receivePlayerNameList(uint256 _pID, bytes32 _name)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev gets existing or registers new pID. use this when a player may be new
* @return pID
*/
function determinePID(HXdatasets.EventReturns memory _eventData_)
private
returns (HXdatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
// if player is new to this version of fomo3d
if (_pID == 0)
{
// grab their player ID, name and last aff ID, from player names contract
_pID = PlayerBook.getPlayerID(msg.sender);
bytes32 _name = PlayerBook.getPlayerName(_pID);
uint256 _laff = PlayerBook.getPlayerLAff(_pID);
// set up player account
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if (_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
// set the new player bool to true
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
/**
* @dev checks to make sure user picked a valid team. if not sets team
* to default (sneks)
*/
function verifyTeam(uint256 _team)
private
pure
returns (uint256)
{
if (_team < 0 || _team > 3)
return(2);
else
return(_team);
}
/**
* @dev decides if round end needs to be run & new round started. and if
* player unmasked earnings from previously played rounds need to be moved.
*/
function managePlayer(uint256 _pID, HXdatasets.EventReturns memory _eventData_)
private
returns (HXdatasets.EventReturns)
{
// if player has played a previous round, move their unmasked earnings
// from that round to gen vault.
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
// update player's last round played
plyr_[_pID].lrnd = rID_;
// set the joined round bool to true
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
/**
* @dev ends the round. manages paying out winner/splitting up pot
*/
function endRound(HXdatasets.EventReturns memory _eventData_)
private
returns (HXdatasets.EventReturns)
{
// setup local rID
uint256 _rID = rID_;
// grab our winning player and team id's
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
// grab our pot amount
uint256 _pot = round_[_rID].pot;
// calculate our winner share, community rewards, gen share,
// p3d share, and amount reserved for next pot
uint256 _win = (_pot.mul(48)) / 100;
uint256 _com = (_pot.mul(2) / 100);
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100;
uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d);
// calculate ppt for round mask
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
// pay our winner
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
// community rewards
community_addr.transfer(_com);
// distribute gen portion to key holders
round_[_rID].mask = _ppt.add(round_[_rID].mask);
if (_p3d > 0)
token_community_addr.transfer(_p3d);
// prepare event data
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.P3DAmount = _p3d;
_eventData_.newPot = _res;
// start next round
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_).add(rndGap_);
round_[_rID].pot = _res;
return(_eventData_);
}
/**
* @dev moves any unmasked earnings to gen vault. updates earnings mask
*/
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
// put in gen vault
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
// zero out their earnings by updating mask
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
/**
* @dev updates round timer based on number of whole keys bought.
*/
function updateTimer(uint256 _keys, uint256 _rID)
private
{
// grab time
uint256 _now = now;
// calculate time based on number of keys bought
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
// compare to max and set new end time
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
/**
* @dev generates a random number between 0-99 and checks to see if thats
* resulted in an airdrop win
* @return do we have a winner?
*/
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
/**
* @dev distributes eth based on fees to com, aff, and p3d
*/
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, HXdatasets.EventReturns memory _eventData_)
private
returns(HXdatasets.EventReturns)
{
// pay 2% out to community rewards
uint256 _com = _eth / 50;
uint256 _p3d;
_p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100));
if (_p3d > 0)
{
token_community_addr.transfer(_p3d);
_eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount);
}
// distribute share to affiliate
uint256 _aff = _eth / 10;
// decide what to do with affiliate share of fees
// affiliate must not be self, and must have a name registered
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit HXevents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
} else {
_com = _com.add(_aff);
}
community_addr.transfer(_com);
return(_eventData_);
}
/**
* @dev distributes eth based on fees to gen and pot
*/
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, HXdatasets.EventReturns memory _eventData_)
private
returns(HXdatasets.EventReturns)
{
// calculate gen share
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
// toss 2% into airdrop pot
uint256 _air = (_eth / 50);
airDropPot_ = airDropPot_.add(_air);
// update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share))
_eth = _eth.sub(((_eth.mul(24)) / 100));
// calculate pot
uint256 _pot = _eth.sub(_gen);
// distribute gen share (thats what updateMasks() does) and adjust
// balances for dust.
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
// add eth to pot
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
// set up event data
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
/**
* @dev updates masks for round and player when keys are bought
* @return dust left over
*/
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
/* MASKING NOTES
earnings masks are a tricky thing for people to wrap their minds around.
the basic thing to understand here. is were going to have a global
tracker based on profit per share for each round, that increases in
relevant proportion to the increase in share supply.
the player will have an additional mask that basically says "based
on the rounds mask, my shares, and how much i've already withdrawn,
how much is still owed to me?"
*/
// calc profit per key & round mask based on this buy: (dust goes to pot)
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// calculate player earning from their own buy (only based on the keys
// they just bought). & update player earnings mask
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
// calculate & return dust
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
/**
* @dev adds up unmasked earnings, & vault earnings, sets them all to 0
* @return earnings in wei format
*/
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
// update gen vault
updateGenVault(_pID, plyr_[_pID].lrnd);
// from vaults
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
/**
* @dev prepares compression data and fires event for buy or reload tx's
*/
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, HXdatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit HXevents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
//==============================================================================
// (~ _ _ _._|_ .
// _)(/_(_|_|| | | \/ .
//====================/=========================================================
/** upon contract deploy, it will be deactivated. this is a one time
* use function that will activate the contract. we do this so devs
* have time to set things up on the web end **/
bool public activated_ = false;
function activate()
public
{
// only team just can activate
require(
msg.sender == developer_addr, "only community can activate"
);
// can only be ran once
require(activated_ == false, "shuoha already activated");
// activate the contract
activated_ = true;
// lets start first round
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
}
//==============================================================================
// __|_ _ __|_ _ .
// _\ | | |_|(_ | _\ .
//==============================================================================
library HXdatasets {
//compressedData key
// [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0]
// 0 - new player (bool)
// 1 - joined round (bool)
// 2 - new leader (bool)
// 3-5 - air drop tracker (uint 0-999)
// 6-16 - round end time
// 17 - winnerTeam
// 18 - 28 timestamp
// 29 - team
// 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico)
// 31 - airdrop happened bool
// 32 - airdrop tier
// 33 - airdrop amount won
//compressedIDs key
// [77-52][51-26][25-0]
// 0-25 - pID
// 26-51 - winPID
// 52-77 - rID
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr; // winner address
bytes32 winnerName; // winner name
uint256 amountWon; // amount won
uint256 newPot; // amount in new pot
uint256 P3DAmount; // amount distributed to p3d
uint256 genAmount; // amount distributed to gen
uint256 potAmount; // amount added to pot
}
struct Player {
address addr; // player address
bytes32 name; // player name
uint256 win; // winnings vault
uint256 gen; // general vault
uint256 aff; // affiliate vault
uint256 lrnd; // last round played
uint256 laff; // last affiliate id used
}
struct PlayerRounds {
uint256 eth; // eth player has added to round (used for eth limiter)
uint256 keys; // keys
uint256 mask; // player mask
uint256 ico; // ICO phase investment
}
struct Round {
uint256 plyr; // pID of player in lead
uint256 team; // tID of team in lead
uint256 end; // time ends/ended
bool ended; // has round end function been ran
uint256 strt; // time round started
uint256 keys; // keys
uint256 eth; // total eth in
uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends)
uint256 mask; // global mask
uint256 ico; // total eth sent in during ICO phase
uint256 icoGen; // total eth for gen during ICO phase
uint256 icoAvg; // average key price for ICO phase
}
struct TeamFee {
uint256 gen; // % of buy in thats paid to key holders of current round
uint256 p3d; // % of buy in thats paid to p3d holders
}
struct PotSplit {
uint256 gen; // % of pot thats paid to key holders of current round
uint256 p3d; // % of pot thats paid to p3d holders
}
}
//==============================================================================
// | _ _ _ | _ .
// |<(/_\/ (_(_||(_ .
//=======/======================================================================
library HXKeysCalcLong {
using SafeMath for *;
/**
* @dev calculates number of keys received given X eth
* @param _curEth current amount of eth in contract
* @param _newEth eth being spent
* @return amount of ticket purchased
*/
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
/**
* @dev calculates amount of eth received if you sold X keys
* @param _curKeys current amount of keys that exist
* @param _sellKeys amount of keys you wish to sell
* @return amount of eth received
*/
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
/**
* @dev calculates how many keys would exist with given an amount of eth
* @param _eth eth "in contract"
* @return number of keys that would exist
*/
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(156250000000000000000000000)).add(1406247070314025878906250000000000000000000000000000000000000000)).sqrt()).sub(37499960937500000000000000000000)) / (78125000);
}
/**
* @dev calculates how much eth would be in contract given a number of keys
* @param _keys number of keys "in contract"
* @return eth that would exists
*/
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((39062500).mul(_keys.sq()).add(((74999921875000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
//==============================================================================
// . _ _|_ _ _ |` _ _ _ _ .
// || | | (/_| ~|~(_|(_(/__\ .
//==============================================================================
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
library NameFilter {
/**
* @dev filters name strings
* -converts uppercase to lower case.
* -makes sure it does not start/end with a space
* -makes sure it does not contain multiple spaces in a row
* -cannot be only numbers
* -cannot start with 0x
* -restricts characters to A-Z, a-z, 0-9, and space.
* @return reprocessed string in bytes32 format
*/
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//sorry limited to 32 characters
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
// make sure it doesnt start with or end with space
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
// make sure first two characters are not 0x
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
// create a bool to track if we have a non number character
bool _hasNonNumber;
// convert & check
for (uint256 i = 0; i < _length; i++)
{
// if its uppercase A-Z
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
// convert to lower case a-z
_temp[i] = byte(uint(_temp[i]) + 32);
// we have a non number
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
// require character is a space
_temp[i] == 0x20 ||
// OR lowercase a-z
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
// or 0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
// make sure theres not 2x spaces in a row
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
// see if we have a character other than a number
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
/**
* @title SafeMath v0.1.9
* @dev Math operations with safety checks that throw on error
* change notes: original SafeMath library from OpenZeppelin modified by Inventor
* - added sqrt
* - added sq
* - added pwr
* - changed asserts to requires with error log outputs
* - removed div, its useless
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
} | calculates how much eth would be in contract given a number of keys _keys number of keys "in contract" return eth that would exists/ | function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((39062500).mul(_keys.sq()).add(((74999921875000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
| 88,580 |
pragma solidity 0.4.18;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// 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 A library for implementing a generic state machine pattern.
library StateMachineLib {
struct Stage {
// The id of the next stage
bytes32 nextId;
// The identifiers for the available functions in each stage
mapping(bytes4 => bool) allowedFunctions;
}
struct State {
// The current stage id
bytes32 currentStageId;
// A callback that is called when entering this stage
function(bytes32) internal onTransition;
// Checks if a stage id is valid
mapping(bytes32 => bool) validStage;
// Maps stage ids to their Stage structs
mapping(bytes32 => Stage) stages;
}
/// @dev Creates and sets the initial stage. It has to be called before creating any transitions.
/// @param stageId The id of the (new) stage to set as initial stage.
function setInitialStage(State storage self, bytes32 stageId) internal {
self.validStage[stageId] = true;
self.currentStageId = stageId;
}
/// @dev Creates a transition from 'fromId' to 'toId'. If fromId already had a nextId, it deletes the now unreachable stage.
/// @param fromId The id of the stage from which the transition begins.
/// @param toId The id of the stage that will be reachable from "fromId".
function createTransition(State storage self, bytes32 fromId, bytes32 toId) internal {
require(self.validStage[fromId]);
Stage storage from = self.stages[fromId];
// Invalidate the stage that won't be reachable any more
if (from.nextId != 0) {
self.validStage[from.nextId] = false;
delete self.stages[from.nextId];
}
from.nextId = toId;
self.validStage[toId] = true;
}
/// @dev Goes to the next stage if posible (if the next stage is valid)
function goToNextStage(State storage self) internal {
Stage storage current = self.stages[self.currentStageId];
require(self.validStage[current.nextId]);
self.currentStageId = current.nextId;
self.onTransition(current.nextId);
}
/// @dev Checks if the a function is allowed in the current stage.
/// @param selector A function selector (bytes4[keccak256(functionSignature)])
/// @return true If the function is allowed in the current stage
function checkAllowedFunction(State storage self, bytes4 selector) internal constant returns(bool) {
return self.stages[self.currentStageId].allowedFunctions[selector];
}
/// @dev Allow a function in the given stage.
/// @param stageId The id of the stage
/// @param selector A function selector (bytes4[keccak256(functionSignature)])
function allowFunction(State storage self, bytes32 stageId, bytes4 selector) internal {
require(self.validStage[stageId]);
self.stages[stageId].allowedFunctions[selector] = true;
}
}
contract StateMachine {
using StateMachineLib for StateMachineLib.State;
event LogTransition(bytes32 indexed stageId, uint256 blockNumber);
StateMachineLib.State internal state;
/* This modifier performs the conditional transitions and checks that the function
* to be executed is allowed in the current stage
*/
modifier checkAllowed {
conditionalTransitions();
require(state.checkAllowedFunction(msg.sig));
_;
}
function StateMachine() public {
// Register the startConditions function and the onTransition callback
state.onTransition = onTransition;
}
/// @dev Gets the current stage id.
/// @return The current stage id.
function getCurrentStageId() public view returns(bytes32) {
return state.currentStageId;
}
/// @dev Performs conditional transitions. Can be called by anyone.
function conditionalTransitions() public {
bytes32 nextId = state.stages[state.currentStageId].nextId;
while (state.validStage[nextId]) {
StateMachineLib.Stage storage next = state.stages[nextId];
// If the next stage's condition is true, go to next stage and continue
if (startConditions(nextId)) {
state.goToNextStage();
nextId = next.nextId;
} else {
break;
}
}
}
/// @dev Determines whether the conditions for transitioning to the given stage are met.
/// @return true if the conditions are met for the given stageId. False by default (must override in child contracts).
function startConditions(bytes32) internal constant returns(bool) {
return false;
}
/// @dev Callback called when there is a stage transition. It should be overridden for additional functionality.
function onTransition(bytes32 stageId) internal {
LogTransition(stageId, block.number);
}
}
/// @title A contract that implements the state machine pattern and adds time dependant transitions.
contract TimedStateMachine is StateMachine {
event LogSetStageStartTime(bytes32 indexed stageId, uint256 startTime);
// Stores the start timestamp for each stage (the value is 0 if the stage doesn't have a start timestamp).
mapping(bytes32 => uint256) internal startTime;
/// @dev This function overrides the startConditions function in the parent class in order to enable automatic transitions that depend on the timestamp.
function startConditions(bytes32 stageId) internal constant returns(bool) {
// Get the startTime for stage
uint256 start = startTime[stageId];
// If the startTime is set and has already passed, return true.
return start != 0 && block.timestamp > start;
}
/// @dev Sets the starting timestamp for a stage.
/// @param stageId The id of the stage for which we want to set the start timestamp.
/// @param timestamp The start timestamp for the given stage. It should be bigger than the current one.
function setStageStartTime(bytes32 stageId, uint256 timestamp) internal {
require(state.validStage[stageId]);
require(timestamp > block.timestamp);
startTime[stageId] = timestamp;
LogSetStageStartTime(stageId, timestamp);
}
/// @dev Returns the timestamp for the given stage id.
/// @param stageId The id of the stage for which we want to set the start timestamp.
function getStageStartTime(bytes32 stageId) public view returns(uint256) {
return startTime[stageId];
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract DetailedERC20 is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
function DetailedERC20(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will 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(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;
MintFinished();
return true;
}
}
contract ERC223Basic is ERC20Basic {
/**
* @dev Transfer the specified amount of tokens to the specified address.
* Now with a new parameter _data.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _data Transaction metadata.
*/
function transfer(address _to, uint _value, bytes _data) public returns (bool);
/**
* @dev triggered when transfer is successfully called.
*
* @param _from Sender address.
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _data Transaction metadata.
*/
event Transfer(address indexed _from, address indexed _to, uint256 indexed _value, bytes _data);
}
/// @title Contract that supports the receival of ERC223 tokens.
contract ERC223ReceivingContract {
/// @dev Standard ERC223 function that will handle incoming token transfers.
/// @param _from Token sender address.
/// @param _value Amount of tokens.
/// @param _data Transaction metadata.
function tokenFallback(address _from, uint _value, bytes _data);
}
/**
* @title ERC223 standard token implementation.
*/
contract ERC223BasicToken is ERC223Basic, BasicToken {
/**
* @dev Transfer the specified amount of tokens to the specified address.
* Invokes the `tokenFallback` function if the recipient is a contract.
* The token transfer fails if the recipient is a contract
* but does not implement the `tokenFallback` function
* or the fallback function to receive funds.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _data Transaction metadata.
*/
function transfer(address _to, uint _value, bytes _data) public returns (bool) {
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
uint codeLength;
assembly {
// Retrieve the size of the code on target address, this needs assembly .
codeLength := extcodesize(_to)
}
require(super.transfer(_to, _value));
if(codeLength>0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, _data);
}
Transfer(msg.sender, _to, _value, _data);
return true;
}
/**
* @dev Transfer the specified amount of tokens to the specified address.
* Invokes the `tokenFallback` function if the recipient is a contract.
* The token transfer fails if the recipient is a contract
* but does not implement the `tokenFallback` function
* or the fallback function to receive funds.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
bytes memory empty;
require(transfer(_to, _value, empty));
return true;
}
}
/// @title Token for the Pryze project.
contract PryzeToken is DetailedERC20, MintableToken, ERC223BasicToken {
string constant NAME = "Pryze";
string constant SYMBOL = "PRYZ";
uint8 constant DECIMALS = 18;
//// @dev Constructor that sets details of the ERC20 token.
function PryzeToken()
DetailedERC20(NAME, SYMBOL, DECIMALS)
public
{}
}
contract Whitelistable is Ownable {
event LogUserRegistered(address indexed sender, address indexed userAddress);
event LogUserUnregistered(address indexed sender, address indexed userAddress);
mapping(address => bool) public whitelisted;
function registerUser(address userAddress)
public
onlyOwner
{
require(userAddress != 0);
whitelisted[userAddress] = true;
LogUserRegistered(msg.sender, userAddress);
}
function unregisterUser(address userAddress)
public
onlyOwner
{
require(whitelisted[userAddress] == true);
whitelisted[userAddress] = false;
LogUserUnregistered(msg.sender, userAddress);
}
}
contract DisbursementHandler is Ownable {
struct Disbursement {
uint256 timestamp;
uint256 tokens;
}
event LogSetup(address indexed vestor, uint256 tokens, uint256 timestamp);
event LogChangeTimestamp(address indexed vestor, uint256 index, uint256 timestamp);
event LogWithdraw(address indexed to, uint256 value);
ERC20 public token;
mapping(address => Disbursement[]) public disbursements;
mapping(address => uint256) public withdrawnTokens;
function DisbursementHandler(address _token) public {
token = ERC20(_token);
}
/// @dev Called by the sale contract to create a disbursement.
/// @param vestor The address of the beneficiary.
/// @param tokens Amount of tokens to be locked.
/// @param timestamp Funds will be locked until this timestamp.
function setupDisbursement(
address vestor,
uint256 tokens,
uint256 timestamp
)
public
onlyOwner
{
require(block.timestamp < timestamp);
disbursements[vestor].push(Disbursement(timestamp, tokens));
LogSetup(vestor, timestamp, tokens);
}
/// @dev Change an existing disbursement.
/// @param vestor The address of the beneficiary.
/// @param timestamp Funds will be locked until this timestamp.
/// @param index Index of the DisbursementVesting in the vesting array.
function changeTimestamp(
address vestor,
uint256 index,
uint256 timestamp
)
public
onlyOwner
{
require(block.timestamp < timestamp);
require(index < disbursements[vestor].length);
disbursements[vestor][index].timestamp = timestamp;
LogChangeTimestamp(vestor, index, timestamp);
}
/// @dev Transfers tokens to a given address
/// @param to Address of token receiver
/// @param value Number of tokens to transfer
function withdraw(address to, uint256 value)
public
{
uint256 maxTokens = calcMaxWithdraw();
uint256 withdrawAmount = value < maxTokens ? value : maxTokens;
withdrawnTokens[msg.sender] = SafeMath.add(withdrawnTokens[msg.sender], withdrawAmount);
token.transfer(to, withdrawAmount);
LogWithdraw(to, value);
}
/// @dev Calculates the maximum amount of vested tokens
/// @return Number of vested tokens to withdraw
function calcMaxWithdraw()
public
constant
returns (uint256)
{
uint256 maxTokens = 0;
Disbursement[] storage temp = disbursements[msg.sender];
for (uint256 i = 0; i < temp.length; i++) {
if (block.timestamp > temp[i].timestamp) {
maxTokens = SafeMath.add(maxTokens, temp[i].tokens);
}
}
maxTokens = SafeMath.sub(maxTokens, withdrawnTokens[msg.sender]);
return maxTokens;
}
}
/// @title Sale base contract
contract Sale is Ownable, TimedStateMachine {
using SafeMath for uint256;
event LogContribution(address indexed contributor, uint256 amountSent, uint256 excessRefunded);
event LogTokenAllocation(address indexed contributor, uint256 contribution, uint256 tokens);
event LogDisbursement(address indexed beneficiary, uint256 tokens);
// Stages for the state machine
bytes32 public constant SETUP = "setup";
bytes32 public constant SETUP_DONE = "setupDone";
bytes32 public constant SALE_IN_PROGRESS = "saleInProgress";
bytes32 public constant SALE_ENDED = "saleEnded";
mapping(address => uint256) public contributions;
uint256 public weiContributed = 0;
uint256 public contributionCap;
// Wallet where funds will be sent
address public wallet;
MintableToken public token;
DisbursementHandler public disbursementHandler;
function Sale(
address _wallet,
uint256 _contributionCap
)
public
{
require(_wallet != 0);
require(_contributionCap != 0);
wallet = _wallet;
token = createTokenContract();
disbursementHandler = new DisbursementHandler(token);
contributionCap = _contributionCap;
setupStages();
}
function() external payable {
contribute();
}
/// @dev Sets the start timestamp for the SALE_IN_PROGRESS stage.
/// @param timestamp The start timestamp.
function setSaleStartTime(uint256 timestamp)
external
onlyOwner
checkAllowed
{
// require(_startTime < getStageStartTime(SALE_ENDED));
setStageStartTime(SALE_IN_PROGRESS, timestamp);
}
/// @dev Sets the start timestamp for the SALE_ENDED stage.
/// @param timestamp The start timestamp.
function setSaleEndTime(uint256 timestamp)
external
onlyOwner
checkAllowed
{
require(getStageStartTime(SALE_IN_PROGRESS) < timestamp);
setStageStartTime(SALE_ENDED, timestamp);
}
/// @dev Called in the SETUP stage, check configurations and to go to the SETUP_DONE stage.
function setupDone()
public
onlyOwner
checkAllowed
{
uint256 _startTime = getStageStartTime(SALE_IN_PROGRESS);
uint256 _endTime = getStageStartTime(SALE_ENDED);
require(block.timestamp < _startTime);
require(_startTime < _endTime);
state.goToNextStage();
}
/// @dev Called by users to contribute ETH to the sale.
function contribute()
public
payable
checkAllowed
{
require(msg.value > 0);
uint256 contributionLimit = getContributionLimit(msg.sender);
require(contributionLimit > 0);
// Check that the user is allowed to contribute
uint256 totalContribution = contributions[msg.sender].add(msg.value);
uint256 excess = 0;
// Check if it goes over the eth cap for the sale.
if (weiContributed.add(msg.value) > contributionCap) {
// Subtract the excess
excess = weiContributed.add(msg.value).sub(contributionCap);
totalContribution = totalContribution.sub(excess);
}
// Check if it goes over the contribution limit of the user.
if (totalContribution > contributionLimit) {
excess = excess.add(totalContribution).sub(contributionLimit);
contributions[msg.sender] = contributionLimit;
} else {
contributions[msg.sender] = totalContribution;
}
// We are only able to refund up to msg.value because the contract will not contain ether
excess = excess < msg.value ? excess : msg.value;
weiContributed = weiContributed.add(msg.value).sub(excess);
if (excess > 0) {
msg.sender.transfer(excess);
}
wallet.transfer(this.balance);
assert(contributions[msg.sender] <= contributionLimit);
LogContribution(msg.sender, msg.value, excess);
}
/// @dev Create a disbursement of tokens.
/// @param beneficiary The beneficiary of the disbursement.
/// @param tokenAmount Amount of tokens to be locked.
/// @param timestamp Tokens will be locked until this timestamp.
function distributeTimelockedTokens(
address beneficiary,
uint256 tokenAmount,
uint256 timestamp
)
external
onlyOwner
checkAllowed
{
disbursementHandler.setupDisbursement(
beneficiary,
tokenAmount,
timestamp
);
token.mint(disbursementHandler, tokenAmount);
LogDisbursement(beneficiary, tokenAmount);
}
function setupStages() internal {
// Set the stages
state.setInitialStage(SETUP);
state.createTransition(SETUP, SETUP_DONE);
state.createTransition(SETUP_DONE, SALE_IN_PROGRESS);
state.createTransition(SALE_IN_PROGRESS, SALE_ENDED);
// The selectors should be hardcoded
state.allowFunction(SETUP, this.distributeTimelockedTokens.selector);
state.allowFunction(SETUP, this.setSaleStartTime.selector);
state.allowFunction(SETUP, this.setSaleEndTime.selector);
state.allowFunction(SETUP, this.setupDone.selector);
state.allowFunction(SALE_IN_PROGRESS, this.contribute.selector);
state.allowFunction(SALE_IN_PROGRESS, 0); // fallback
}
// Override in the child sales
function createTokenContract() internal returns (MintableToken);
function getContributionLimit(address userAddress) internal returns (uint256);
/// @dev Stage start conditions.
function startConditions(bytes32 stageId) internal constant returns (bool) {
// If the cap has been reached, end the sale.
if (stageId == SALE_ENDED && contributionCap == weiContributed) {
return true;
}
return super.startConditions(stageId);
}
/// @dev State transitions callbacks.
function onTransition(bytes32 stageId) internal {
if (stageId == SALE_ENDED) {
onSaleEnded();
}
super.onTransition(stageId);
}
/// @dev Callback that gets called when entering the SALE_ENDED stage.
function onSaleEnded() internal {}
}
contract PryzeSale is Sale, Whitelistable {
uint256 public constant PRESALE_WEI = 10695.303 ether; // Amount raised in the presale
uint256 public constant PRESALE_WEI_WITH_BONUS = 10695.303 ether * 1.5; // Amount raised in the presale times the bonus
uint256 public constant MAX_WEI = 24695.303 ether; // Max wei to raise, including PRESALE_WEI
uint256 public constant WEI_CAP = 14000 ether; // MAX_WEI - PRESALE_WEI
uint256 public constant MAX_TOKENS = 400000000 * 1000000000000000000; // 4mm times 10^18 (18 decimals)
uint256 public presaleWeiContributed = 0;
uint256 private weiAllocated = 0;
mapping(address => uint256) public presaleContributions;
function PryzeSale(
address _wallet
)
Sale(_wallet, WEI_CAP)
public
{
}
/// @dev Sets the presale contribution for a contributor.
/// @param _contributor The contributor.
/// @param _amount The amount contributed in the presale (without the bonus).
function presaleContribute(address _contributor, uint256 _amount)
external
onlyOwner
checkAllowed
{
// If presale contribution is already set, replace the amount in the presaleWeiContributed variable
if (presaleContributions[_contributor] != 0) {
presaleWeiContributed = presaleWeiContributed.sub(presaleContributions[_contributor]);
}
presaleWeiContributed = presaleWeiContributed.add(_amount);
require(presaleWeiContributed <= PRESALE_WEI);
presaleContributions[_contributor] = _amount;
}
/// @dev Called to allocate the tokens depending on eth contributed.
/// @param contributor The address of the contributor.
function allocateTokens(address contributor)
external
checkAllowed
{
require(presaleContributions[contributor] != 0 || contributions[contributor] != 0);
uint256 tokensToAllocate = calculateAllocation(contributor);
// We keep a record of how much wei contributed has already been used for allocations
weiAllocated = weiAllocated.add(presaleContributions[contributor]).add(contributions[contributor]);
// Set contributions to 0
presaleContributions[contributor] = 0;
contributions[contributor] = 0;
// Mint the respective tokens to the contributor
token.mint(contributor, tokensToAllocate);
// If all tokens were allocated, stop minting functionality
if (weiAllocated == PRESALE_WEI.add(weiContributed)) {
token.finishMinting();
}
}
function setupDone()
public
onlyOwner
checkAllowed
{
require(presaleWeiContributed == PRESALE_WEI);
super.setupDone();
}
/// @dev Calculate the PRYZ allocation for the given contributor. The allocation is proportional to the amount of wei contributed.
/// @param contributor The address of the contributor
/// @return The amount of tokens to allocate
function calculateAllocation(address contributor) public constant returns (uint256) {
uint256 presale = presaleContributions[contributor].mul(15).div(10); // Multiply by 1.5
uint256 totalContribution = presale.add(contributions[contributor]);
return totalContribution.mul(MAX_TOKENS).div(PRESALE_WEI_WITH_BONUS.add(weiContributed));
}
function setupStages() internal {
super.setupStages();
state.allowFunction(SETUP, this.presaleContribute.selector);
state.allowFunction(SALE_ENDED, this.allocateTokens.selector);
}
function createTokenContract() internal returns(MintableToken) {
return new PryzeToken();
}
function getContributionLimit(address userAddress) internal returns (uint256) {
// No contribution cap if whitelisted
return whitelisted[userAddress] ? 2**256 - 1 : 0;
}
} | State transitions callbacks. | function onTransition(bytes32 stageId) internal {
if (stageId == SALE_ENDED) {
onSaleEnded();
}
super.onTransition(stageId);
}
| 2,414,408 |
./full_match/1/0xbE6e7EDb55c0b97f42cf12ddc2AF8DFD154D584C/sources/contracts/AvastarsMarketplace.sol | check the parameters to the function to make sure that a minter has validated this combination/ | function isValidMint(
SignedReplicantMintRequest memory sRequest
) internal view returns (bool) {
bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
keccak256("ReplicantMintRequest(uint8 generation,uint8 gender,uint256 traitHash,uint8 ranking,TraitSource[] traitSources,SignedTraitOffer[] consumedOffers)SignedTraitOffer(TraitOffer offer,bytes signature)TraitOffer(uint256 primeId,uint256 traitNumber,uint256 price,uint256 expiration,uint256 nonce)TraitSource(uint256 primeId,bool[12] traitConsumed)"),
sRequest.request.generation,
sRequest.request.gender,
sRequest.request.traitHash,
sRequest.request.ranking,
hashTraitSources(sRequest.request.traitSources),
hashConsumedOffers(sRequest.request.consumedOffers)
)));
address signer = ECDSA.recover(digest, sRequest.signature);
if (!isValidMinter(signer)) {
return false;
}
return true;
}
| 8,337,963 |
/**
* SEED Platform Generator ATDeployer
*/
pragma solidity ^0.5.2;
/**
* @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;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Not Owner!");
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice 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 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),"Address 0 could not be owner");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
interface IAdminTools {
function setFFPAddresses(address, address) external;
function setMinterAddress(address) external returns(address);
function getMinterAddress() external view returns(address);
function getWalletOnTopAddress() external view returns (address);
function setWalletOnTopAddress(address) external returns(address);
function addWLManagers(address) external;
function removeWLManagers(address) external;
function isWLManager(address) external view returns (bool);
function addWLOperators(address) external;
function removeWLOperators(address) external;
function renounceWLManager() external;
function isWLOperator(address) external view returns (bool);
function renounceWLOperators() external;
function addFundingManagers(address) external;
function removeFundingManagers(address) external;
function isFundingManager(address) external view returns (bool);
function addFundingOperators(address) external;
function removeFundingOperators(address) external;
function renounceFundingManager() external;
function isFundingOperator(address) external view returns (bool);
function renounceFundingOperators() external;
function addFundsUnlockerManagers(address) external;
function removeFundsUnlockerManagers(address) external;
function isFundsUnlockerManager(address) external view returns (bool);
function addFundsUnlockerOperators(address) external;
function removeFundsUnlockerOperators(address) external;
function renounceFundsUnlockerManager() external;
function isFundsUnlockerOperator(address) external view returns (bool);
function renounceFundsUnlockerOperators() external;
function isWhitelisted(address) external view returns(bool);
function getWLThresholdBalance() external view returns (uint256);
function getMaxWLAmount(address) external view returns(uint256);
function getWLLength() external view returns(uint256);
function setNewThreshold(uint256) external;
function changeMaxWLAmount(address, uint256) external;
function addToWhitelist(address, uint256) external;
function addToWhitelistMassive(address[] calldata, uint256[] calldata) external returns (bool);
function removeFromWhitelist(address, uint256) external;
}
interface IFactory {
function changeATFactoryAddress(address) external;
function changeTDeployerAddress(address) external;
function changeFPDeployerAddress(address) external;
function deployPanelContracts(string calldata, string calldata, string calldata, bytes32, uint8, uint8, uint256, uint256) external;
function isFactoryDeployer(address) external view returns(bool);
function isFactoryATGenerated(address) external view returns(bool);
function isFactoryTGenerated(address) external view returns(bool);
function isFactoryFPGenerated(address) external view returns(bool);
function getTotalDeployer() external view returns(uint256);
function getTotalATContracts() external view returns(uint256);
function getTotalTContracts() external view returns(uint256);
function getTotalFPContracts() external view returns(uint256);
function getContractsByIndex(uint256) external view returns (address, address, address, address);
function getFPAddressByIndex(uint256) external view returns (address);
function getFactoryContext() external view returns (address, address, uint);
}
interface IFundingPanel {
function getFactoryDeployIndex() external view returns(uint);
function isMemberInserted(address) external view returns(bool);
function addMemberToSet(address, uint8, string calldata, bytes32) external returns (bool);
function enableMember(address) external;
function disableMemberByStaffRetire(address) external;
function disableMemberByStaffForExit(address) external;
function disableMemberByMember(address) external;
function changeMemberData(address, string calldata, bytes32) external;
function changeTokenExchangeRate(uint256) external;
function changeTokenExchangeOnTopRate(uint256) external;
function getOwnerData() external view returns (string memory, bytes32);
function setOwnerData(string calldata, bytes32) external;
function getMembersNumber() external view returns (uint);
function getMemberAddressByIndex(uint8) external view returns (address);
function getMemberDataByAddress(address _memberWallet) external view returns (bool, uint8, string memory, bytes32, uint256, uint, uint256);
function setNewSeedMaxSupply(uint256) external returns (uint256);
function holderSendSeeds(uint256) external;
function unlockFunds(address, uint256) external;
function burnTokensForMember(address, uint256) external;
function importOtherTokens(address, uint256) external;
}
contract AdminTools is Ownable, IAdminTools {
using SafeMath for uint256;
struct wlVars {
bool permitted;
uint256 maxAmount;
}
mapping (address => wlVars) private whitelist;
uint8 private whitelistLength;
uint256 private whitelistThresholdBalance;
mapping (address => bool) private _WLManagers;
mapping (address => bool) private _FundingManagers;
mapping (address => bool) private _FundsUnlockerManagers;
mapping (address => bool) private _WLOperators;
mapping (address => bool) private _FundingOperators;
mapping (address => bool) private _FundsUnlockerOperators;
address private _minterAddress;
address private _walletOnTopAddress;
address public FPAddress;
IFundingPanel public FPContract;
address public FAddress;
IFactory public FContract;
event WLManagersAdded();
event WLManagersRemoved();
event WLOperatorsAdded();
event WLOperatorsRemoved();
event FundingManagersAdded();
event FundingManagersRemoved();
event FundingOperatorsAdded();
event FundingOperatorsRemoved();
event FundsUnlockerManagersAdded();
event FundsUnlockerManagersRemoved();
event FundsUnlockerOperatorsAdded();
event FundsUnlockerOperatorsRemoved();
event MaxWLAmountChanged();
event MinterOrigins();
event MinterChanged();
event WalletOnTopAddressChanged();
event LogWLThresholdBalanceChanged();
event LogWLAddressAdded();
event LogWLMassiveAddressesAdded();
event LogWLAddressRemoved();
constructor (uint256 _whitelistThresholdBalance) public {
whitelistThresholdBalance = _whitelistThresholdBalance;
}
function setFFPAddresses(address _factoryAddress, address _FPAddress) external onlyOwner {
FAddress = _factoryAddress;
FContract = IFactory(FAddress);
FPAddress = _FPAddress;
FPContract = IFundingPanel(FPAddress);
emit MinterOrigins();
}
/* Token Minter address, to set like Funding Panel address */
function getMinterAddress() external view returns(address) {
return _minterAddress;
}
function setMinterAddress(address _minter) external onlyOwner returns(address) {
require(_minter != address(0), "Not valid minter address!");
require(_minter != _minterAddress, " No change in minter contract");
require(FAddress != address(0), "Not valid factory address!");
require(FPAddress != address(0), "Not valid FP Contract address!");
require(FContract.getFPAddressByIndex(FPContract.getFactoryDeployIndex()) == _minter,
"Minter is not a known funding panel!");
_minterAddress = _minter;
emit MinterChanged();
return _minterAddress;
}
/* Wallet receiving extra minted tokens (percentage) */
function getWalletOnTopAddress() external view returns (address) {
return _walletOnTopAddress;
}
function setWalletOnTopAddress(address _wallet) external onlyOwner returns(address) {
require(_wallet != address(0), "Not valid wallet address!");
require(_wallet != _walletOnTopAddress, " No change in OnTopWallet");
_walletOnTopAddress = _wallet;
emit WalletOnTopAddressChanged();
return _walletOnTopAddress;
}
/* Modifiers */
modifier onlyWLManagers() {
require(isWLManager(msg.sender), "Not a Whitelist Manager!");
_;
}
modifier onlyWLOperators() {
require(isWLOperator(msg.sender), "Not a Whitelist Operator!");
_;
}
modifier onlyFundingManagers() {
require(isFundingManager(msg.sender), "Not a Funding Panel Manager!");
_;
}
modifier onlyFundingOperators() {
require(isFundingOperator(msg.sender), "Not a Funding Panel Operator!");
_;
}
modifier onlyFundsUnlockerManagers() {
require(isFundsUnlockerManager(msg.sender), "Not a Funds Unlocker Manager!");
_;
}
modifier onlyFundsUnlockerOperators() {
require(isFundsUnlockerOperator(msg.sender), "Not a Funds Unlocker Operator!");
_;
}
/* WL Roles Mngmt */
function addWLManagers(address account) external onlyOwner {
_addWLManagers(account);
_addWLOperators(account);
}
function removeWLManagers(address account) external onlyOwner {
_removeWLManagers(account);
}
function isWLManager(address account) public view returns (bool) {
return _WLManagers[account];
}
function addWLOperators(address account) external onlyWLManagers {
_addWLOperators(account);
}
function removeWLOperators(address account) external onlyWLManagers {
_removeWLOperators(account);
}
function renounceWLManager() external onlyWLManagers {
_removeWLManagers(msg.sender);
}
function _addWLManagers(address account) internal {
_WLManagers[account] = true;
emit WLManagersAdded();
}
function _removeWLManagers(address account) internal {
_WLManagers[account] = false;
emit WLManagersRemoved();
}
function isWLOperator(address account) public view returns (bool) {
return _WLOperators[account];
}
function renounceWLOperators() external onlyWLOperators {
_removeWLOperators(msg.sender);
}
function _addWLOperators(address account) internal {
_WLOperators[account] = true;
emit WLOperatorsAdded();
}
function _removeWLOperators(address account) internal {
_WLOperators[account] = false;
emit WLOperatorsRemoved();
}
/* Funding Roles Mngmt */
function addFundingManagers(address account) external onlyOwner {
_addFundingManagers(account);
_addFundingOperators(account);
}
function removeFundingManagers(address account) external onlyOwner {
_removeFundingManagers(account);
}
function isFundingManager(address account) public view returns (bool) {
return _FundingManagers[account];
}
function addFundingOperators(address account) external onlyFundingManagers {
_addFundingOperators(account);
}
function removeFundingOperators(address account) external onlyFundingManagers {
_removeFundingOperators(account);
}
function renounceFundingManager() external onlyFundingManagers {
_removeFundingManagers(msg.sender);
}
function _addFundingManagers(address account) internal {
_FundingManagers[account] = true;
emit FundingManagersAdded();
}
function _removeFundingManagers(address account) internal {
_FundingManagers[account] = false;
emit FundingManagersRemoved();
}
function isFundingOperator(address account) public view returns (bool) {
return _FundingOperators[account];
}
function renounceFundingOperators() external onlyFundingOperators {
_removeFundingOperators(msg.sender);
}
function _addFundingOperators(address account) internal {
_FundingOperators[account] = true;
emit FundingOperatorsAdded();
}
function _removeFundingOperators(address account) internal {
_FundingOperators[account] = false;
emit FundingOperatorsRemoved();
}
/* Funds Unlockers Roles Mngmt */
function addFundsUnlockerManagers(address account) external onlyOwner {
_addFundsUnlockerManagers(account);
}
function removeFundsUnlockerManagers(address account) external onlyOwner {
_removeFundsUnlockerManagers(account);
}
function isFundsUnlockerManager(address account) public view returns (bool) {
return _FundsUnlockerManagers[account];
}
function addFundsUnlockerOperators(address account) external onlyFundsUnlockerManagers {
_addFundsUnlockerOperators(account);
}
function removeFundsUnlockerOperators(address account) external onlyFundsUnlockerManagers {
_removeFundsUnlockerOperators(account);
}
function renounceFundsUnlockerManager() external onlyFundsUnlockerManagers {
_removeFundsUnlockerManagers(msg.sender);
}
function _addFundsUnlockerManagers(address account) internal {
_FundsUnlockerManagers[account] = true;
emit FundsUnlockerManagersAdded();
}
function _removeFundsUnlockerManagers(address account) internal {
_FundsUnlockerManagers[account] = false;
emit FundsUnlockerManagersRemoved();
}
function isFundsUnlockerOperator(address account) public view returns (bool) {
return _FundsUnlockerOperators[account];
}
function renounceFundsUnlockerOperators() external onlyFundsUnlockerOperators {
_removeFundsUnlockerOperators(msg.sender);
}
function _addFundsUnlockerOperators(address account) internal {
_FundsUnlockerOperators[account] = true;
emit FundsUnlockerOperatorsAdded();
}
function _removeFundsUnlockerOperators(address account) internal {
_FundsUnlockerOperators[account] = false;
emit FundsUnlockerOperatorsRemoved();
}
/* Whitelisting Mngmt */
/**
* @return true if subscriber is whitelisted, false otherwise
*/
function isWhitelisted(address _subscriber) public view returns(bool) {
return whitelist[_subscriber].permitted;
}
/**
* @return the anonymous threshold
*/
function getWLThresholdBalance() public view returns (uint256) {
return whitelistThresholdBalance;
}
/**
* @return maxAmount for holder
*/
function getMaxWLAmount(address _subscriber) external view returns(uint256) {
return whitelist[_subscriber].maxAmount;
}
/**
* @dev length of the whitelisted accounts
*/
function getWLLength() external view returns(uint256) {
return whitelistLength;
}
/**
* @dev set new anonymous threshold
* @param _newThreshold The new anonymous threshold.
*/
function setNewThreshold(uint256 _newThreshold) external onlyWLManagers {
require(whitelistThresholdBalance != _newThreshold, "New Threshold like the old one!");
whitelistThresholdBalance = _newThreshold;
emit LogWLThresholdBalanceChanged();
}
/**
* @dev Change maxAmount for holder
* @param _subscriber The subscriber in the whitelist.
* @param _newMaxToken New max amount that a subscriber can hold (in set tokens).
*/
function changeMaxWLAmount(address _subscriber, uint256 _newMaxToken) external onlyWLOperators {
require(isWhitelisted(_subscriber), "Investor is not whitelisted!");
whitelist[_subscriber].maxAmount = _newMaxToken;
emit MaxWLAmountChanged();
}
/**
* @dev Add the subscriber to the whitelist.
* @param _subscriber The subscriber to add to the whitelist.
* @param _maxAmnt max amount that a subscriber can hold (in set tokens).
*/
function addToWhitelist(address _subscriber, uint256 _maxAmnt) external onlyWLOperators {
require(_subscriber != address(0), "_subscriber is zero");
require(!whitelist[_subscriber].permitted, "already whitelisted");
whitelistLength++;
whitelist[_subscriber].permitted = true;
whitelist[_subscriber].maxAmount = _maxAmnt;
emit LogWLAddressAdded();
}
/**
* @dev Add the subscriber list to the whitelist (max 100)
* @param _subscriber The subscriber list to add to the whitelist.
* @param _maxAmnt max amount list that a subscriber can hold (in set tokens).
*/
function addToWhitelistMassive(address[] calldata _subscriber, uint256[] calldata _maxAmnt) external onlyWLOperators returns (bool _success) {
assert(_subscriber.length == _maxAmnt.length);
assert(_subscriber.length <= 100);
for (uint8 i = 0; i < _subscriber.length; i++) {
require(_subscriber[i] != address(0), "_subscriber is zero");
require(!whitelist[_subscriber[i]].permitted, "already whitelisted");
whitelistLength++;
whitelist[_subscriber[i]].permitted = true;
whitelist[_subscriber[i]].maxAmount = _maxAmnt[i];
}
emit LogWLMassiveAddressesAdded();
return true;
}
/**
* @dev Remove the subscriber from the whitelist.
* @param _subscriber The subscriber remove from the whitelist.
* @param _balance balance of a subscriber to be under the anonymous threshold, otherwise de-whilisting not permitted.
*/
function removeFromWhitelist(address _subscriber, uint256 _balance) external onlyWLOperators {
require(_subscriber != address(0), "_subscriber is zero");
require(whitelist[_subscriber].permitted, "not whitelisted");
require(_balance <= whitelistThresholdBalance, "balance greater than whitelist threshold");
whitelistLength--;
whitelist[_subscriber].permitted = false;
whitelist[_subscriber].maxAmount = 0;
emit LogWLAddressRemoved();
}
}
interface IATDeployer {
function newAdminTools(uint256) external returns(address);
function setFactoryAddress(address) external;
function getFactoryAddress() external view returns(address);
}
contract ATDeployer is Ownable, IATDeployer {
address private fAddress;
event ATDeployed(uint deployedBlock);
//constructor() public {}
modifier onlyFactory() {
require(msg.sender == fAddress, "Address not allowed to create AT Contract!");
_;
}
/**
* @dev Set the factory address for deployment.
* @param _fAddress The factory address.
*/
function setFactoryAddress(address _fAddress) external onlyOwner {
require(block.number < 8850000, "Time expired!");
require(_fAddress != address(0), "Address not allowed");
fAddress = _fAddress;
}
/**
* @dev Get the factory address for deployment.
*/
function getFactoryAddress() external view returns(address) {
return fAddress;
}
/**
* @dev deployment of a new AdminTools contract
* @return address of the deployed AdminTools contract
*/
function newAdminTools(uint256 _whitelistThresholdBalance) external onlyFactory returns(address) {
AdminTools c = new AdminTools(_whitelistThresholdBalance);
c.transferOwnership(msg.sender);
emit ATDeployed (block.number);
return address(c);
}
} | length of the whitelisted accounts/ | function getWLLength() external view returns(uint256) {
return whitelistLength;
}
| 896,008 |
pragma solidity ^0.4.25;
/******************************************/
/* Netkiller Standard safe token */
/******************************************/
/* Author netkiller <[email protected]> */
/* Home http://www.netkiller.cn */
/* Version 2018-09-30 */
/******************************************/
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract NetkillerToken is Ownable{
using SafeMath for uint256;
string public name;
string public symbol;
uint public decimals;
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) internal balances;
mapping (address => mapping (address => uint256)) internal allowed;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
constructor(
uint256 initialSupply,
string tokenName,
string tokenSymbol,
uint decimalUnits
) public {
owner = msg.sender;
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol;
decimals = decimalUnits;
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balances[msg.sender] = totalSupply; // Give the creator all initial token
}
function balanceOf(address _address) view public returns (uint256 balance) {
return balances[_address];
}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint256 _value) internal {
require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead
require (balances[_from] >= _value); // Check if the sender has enough
require (balances[_to] + _value > balances[_to]); // Check for overflows
balances[_from] = balances[_from].sub(_value); // Subtract from the sender
balances[_to] = balances[_to].add(_value); // Add the same to the recipient
emit Transfer(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]); // Check allowance
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) view public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function airdrop(address[] _to, uint256 _value) onlyOwner public returns (bool success) {
require(_value > 0 && balanceOf(msg.sender) >= _value.mul(_to.length));
for (uint i=0; i<_to.length; i++) {
_transfer(msg.sender, _to[i], _value);
}
return true;
}
function batchTransfer(address[] _to, uint256[] _value) onlyOwner public returns (bool success) {
require(_to.length == _value.length);
uint256 amount = 0;
for(uint n=0;n<_value.length;n++){
amount = amount.add(_value[n]);
}
require(amount > 0 && balanceOf(msg.sender) >= amount);
for (uint i=0; i<_to.length; i++) {
transfer(_to[i], _value[i]);
}
return true;
}
} | Integer division of two numbers truncating the quotient, reverts on division by zero./ assert(a == b c + a % b); There is no case in which this doesn't hold | function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
| 119,801 |
./partial_match/11155111/0xa1Cba558B09d7B88FaBFe967B64f0C9626E1fAd0/sources/contracts/SenderExchange.sol | returns the amount of Eth/TG tokens that are required to be returned to the user/trader upon swap _amountTGOLD amount of TGOLD input _amountCCIP_BnM amount of CCIP_BnM input/ post manual approval of Exchange.sol as the Spender of TGOLD on behalf of LProvider adding 1 token to LPool adding 2nd token to LPool Let's now send the msg to CCIP_BnMMumbai to mint(RxExchange.sol, _amountCCIP_BnM) and create Liquidity destChainSelector: added in SendMsgPayLink() of PTT.sol 1. check LINK fee | function _addBothTokensInLP(ERC20 TGOLDToken, uint256 _amountTGOLD, ERC20 CCIP_BnMToken, uint256 _amountCCIP_BnM) internal /*returns (uint256, uint256)*/ {
TGOLDToken.transferFrom(_msgSender(), address(this), _amountTGOLD);
CCIP_BnMToken.transferFrom(_msgSender(), address(this), _amountCCIP_BnM);
console.log("Transferred both hte tokens");
Client.EVM2AnyMessage memory evm2AnyMessage = _buildCCIPMessageAddLiq(CCIP_BnMMumbaiAddress, _amountCCIP_BnM);
uint64 destChainSelector = 16015286601757825753;
IRouterClient router = IRouterClient(i_router);
uint256 fees = router.getFee(destChainSelector, evm2AnyMessage);
if(fees > ERC20(i_link).balanceOf(address(this))) {
revert NotEnoughLINKBalance(ERC20(i_link).balanceOf(address(this)), fees);
}
emit AddedLiquidtyAsset1(_amountTGOLD);
emit MessageSent(messageId);
| 3,533,851 |
./full_match/4/0x7533015917469533A2aAd58A7F604FAd8A9b6cdE/sources/DATA.sol | GET ALL LETTERS OF A WALLET AS AN ARRAY OF STRINGS. | function letterNamesOfOwner(address _owner) external view returns(string[] memory ) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new string[](0);
string[] memory result = new string[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = letterNames[tokenOfOwnerByIndex(_owner, index) ] ;
}
return result;
}
} else {
if (tokenCount == 0) {
return new string[](0);
string[] memory result = new string[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = letterNames[tokenOfOwnerByIndex(_owner, index) ] ;
}
return result;
}
}
| 13,342,338 |
pragma solidity ^0.4.24;
/* ----------------------------------------------------------------------------
| Sheltercoin ICO 'Sheltercoin Token' Crowdfunding contract
| Date - 16-November-2017
| Blockchain Date - Dec 4 2018
| copyright 2017 zMint Limited. All Rights Reserved.
| authors A Campbell, S Outtrim
| Vers - 000 v001
| ------------------------
| Updates
| Date 25-Aug-17 ADC Finalising format
| Date 27-Aug-17 ADC Code review amendments
| Date 01-Sep-17 ADC Changes
| Date 16-Nov-17 ADC Sheltercoin Pre-ICO phase
| Date 27-Nov-17 ADC Pragma 17 Changes
| Date 12-Dec-17 SO, ADC Code Review, testing; production migration.
| Date 01-May-18 ADC Code changes
| Date 12-May-18 ADC KYC Client Verication
| Date 29-May-18 SO, ADC Code Revew, testing
| Date 11-Jun-18 SO hard coding, testing, production migration.
| Removed TransferAnyERC20Token, KYC contract shell
| Added whitelist and blacklist code
| Added bonus calc to ICO function
| Date 08-Aug-18 SO Updated function to constructor()
| Added SHLT specific function to SHLT code, replaced names
| Date 07-Feb-19 SO Production deployment of new SHLT token
|
|
| Sheltercoin.io :-)
| :-) hAVe aN aWeSoMe iCo :-)
|
// ---------------------------------------------------------------------------- */
/* =============================================================================
| Sheltercoin ICO 'Sheltercoin Token & Crowdfunding
|
| 001. contract - ERC20 Token Interface
|
|
|
| Apache Licence
| ============================================================================= */
/* ============================================================================
|
| Token Standard #20 Interface
| https://github.com/ethereum/EIPs/issues/20
|
| ============================================================================ */
contract ERC20Interface {
uint public totalSupply;
uint public tokensSold;
function balanceOf(address _owner) public constant returns (uint balance);
function transfer(address _to, uint _value) public returns (bool success);
function transferFrom(address _from, address _to, uint _value)
public returns (bool success);
function approve(address _spender, uint _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant
returns (uint remaining);
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender,
uint _value);
}
/* ======================================================================
|
| 002. contract Owned
|
| ====================================================================== */
contract Owned {
/* ------------------------------------------------------------------------
| 002.01 - Current owner, and proposed new owner
| -----------------------------------------------------------------------*/
address public owner;
address public newOwner;
// ------------------------------------------------------------------------
// 002.02 - Constructor - assign creator as the owner
// -----------------------------------------------------------------------*/
constructor () public {
owner = msg.sender;
}
/* ------------------------------------------------------------------------
| 002.03 - Modifier to mark that a function can only be executed by the owner
| -----------------------------------------------------------------------*/
modifier onlyOwner {
require(msg.sender == owner);
_;
}
/* ------------------------------------------------------------------------
| 002.04 - Owner can initiate transfer of contract to a new owner
| -----------------------------------------------------------------------*/
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
/* ------------------------------------------------------------------------
| 002.05 - New owner has to accept transfer of contract
| -----------------------------------------------------------------------*/
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
event OwnershipTransferred(address indexed _from, address indexed _to);
}
/* ===================================================================================
|
| 003. contract Pausable
| Abstract contract that allows children to implement an emergency stop mechanism
|
| ==================================================================================== */
contract Pausable is Owned {
event Pause();
event Unpause();
bool public paused = false;
/* ------------------------------------------------------------------------
| 003.01 - modifier to allow actions only when the contract IS paused
| -----------------------------------------------------------------------*/
modifier whenNotPaused() {
require(!paused);
_;
}
/* ------------------------------------------------------------------------
| 003.02 - modifier to allow actions only when the contract IS NOT paused
| -----------------------------------------------------------------------*/
modifier whenPaused {
require(paused);
_;
}
/* ------------------------------------------------------------------------
| 003.01 - called by the owner to pause, triggers stopped state
| -----------------------------------------------------------------------*/
function pause() public onlyOwner whenNotPaused returns (bool) {
paused = true;
emit Pause();
return true;
}
/* ------------------------------------------------------------------------
| 003.01 - called by the owner to unpause, returns to normal state
| -----------------------------------------------------------------------*/
function unpause() public onlyOwner whenPaused returns (bool) {
paused = false;
emit Unpause();
return true;
}
}
/* ===================================================================================
|
| 004. contract Transferable
| Abstract contract that allows wallets the transfer mechanism
|
| ==================================================================================== */
contract Transferable is Owned {
event Transfer();
event Untransfer();
bool public flg_transfer = true;
/* ------------------------------------------------------------------------
| 004.01 - modifier to allow actions only when the contract IS transfer
| -----------------------------------------------------------------------*/
modifier whenNotTransfer() {
require(!flg_transfer);
_;
}
/* ------------------------------------------------------------------------
| 004.02 - modifier to allow actions only when the contract IS NOT transfer
| -----------------------------------------------------------------------*/
modifier whenTransfer {
require(flg_transfer);
_;
}
/* ------------------------------------------------------------------------
| 004.01 - called by the owner to transfer, triggers stopped state
| -----------------------------------------------------------------------*/
function transfer() public onlyOwner whenNotTransfer returns (bool) {
flg_transfer = true;
emit Transfer();
return true;
}
/* ------------------------------------------------------------------------
| 004.01 - called by the owner to untransfer, returns to normal state
| -----------------------------------------------------------------------*/
function untransfer() public onlyOwner whenTransfer returns (bool) {
flg_transfer = false;
emit Untransfer();
return true;
}
}
/* ----------------------------------------------------------------------------
| 005. libraty Safe maths - OpenZeppelin
| --------------------------------------------------------------------------- */
library SafeMath {
/* ------------------------------------------------------------------------
// 005.01 - safeAdd a number to another number, checking for overflows
// -----------------------------------------------------------------------*/
function safeAdd(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c >= a && c >= b);
return c;
}
/* ------------------------------------------------------------------------
// 005.02 - safeSubtract a number from another number, checking for underflows
// -----------------------------------------------------------------------*/
function safeSub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
/* ------------------------------------------------------------------------
// 005.03 - safeMuiltplier a number to another number, checking for underflows
// -----------------------------------------------------------------------*/
function safeMul(uint a, uint b) internal pure returns (uint256) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
/* ------------------------------------------------------------------------
// 005.04 - safeDivision
// -----------------------------------------------------------------------*/
function safeDiv(uint a, uint b) internal pure returns (uint256) {
uint c = a / b;
return c;
}
/* ------------------------------------------------------------------------
// 005.05 - Max64
// -----------------------------------------------------------------------*/
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
/* ------------------------------------------------------------------------
// 005.06 - Min64
// -----------------------------------------------------------------------*/
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
/* ------------------------------------------------------------------------
// 005.07 - max256
// -----------------------------------------------------------------------*/
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/* ------------------------------------------------------------------------
// 005.08 - min256
// -----------------------------------------------------------------------*/
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
/* ----------------------------------------------------------------------------
| 006. contract Sheltercoin Token Configuration - pass through parameters
| ---------------------------------------------------------------------------- */
contract SheltercoinTokCfg {
/* ------------------------------------------------------------------------
| 006.01 - Token symbol(), name() and decimals()
|------------------------------------------------------------------------ */
string public constant SYMBOL = "SHLT";
string public constant NAME = "SHLT Sheltercoin.io";
uint8 public constant DECIMALS = 8;
bool public flg001 = false;
/* -----------------------------------------------------------------------
| 006.02 - Decimal factor for multiplications
| ------------------------------------------------------------------------*/
uint public constant TOKENS_SOFT_CAP = 1 * DECIMALSFACTOR;
uint public constant TOKENS_HARD_CAP = 1000000000 * DECIMALSFACTOR; /* billion */
uint public constant TOKENS_TOTAL = 1000000000 * DECIMALSFACTOR;
uint public tokensSold = 0;
/* ------------------------------------------------------------------------
| 006.03 - Lot 1 Crowdsale start date and end date
| Do not use the `now` function here
| Good caluclator for sanity check for epoch - http://www.unixtimestamp.com/
| Start - Sunday 30-Jun-19 12:00:00 UTC
| End - Tuesday 30-Jun-20 12:00:00 UTC
| ----------------------------------------------------------------------- */
uint public constant DECIMALSFACTOR = 10**uint(DECIMALS);
/* ------------------------------------------------------------------------
| 006.04 - Lot 1 Crowdsale timings Soft Cap and Hard Cap, and Total tokens
| -------------------------------------------------------------------------- */
uint public START_DATE = 1582545600; // 24-Feb-20 12:00:00 GMT
uint public END_DATE = 1614165071; // 24-Feb-21 11:11:11 GMT
/* ------------------------------------------------------------------------
| 006.05 - Individual transaction contribution min and max amounts
| Set to 0 to switch off, or `x ether`
| ----------------------------------------------------------------------*/
uint public CONTRIBUTIONS_MIN = 0;
uint public CONTRIBUTIONS_MAX = 1000000 ether;
}
/* ----------------------------------------------------------------------------
| 007. - contract ERC20 Token, with the safeAddition of Symbol, name and Decimal
| --------------------------------------------------------------------------*/
contract ERC20Token is ERC20Interface, Owned, Pausable, Transferable {
using SafeMath for uint;
/* ------------------------------------------------------------------------
| 007.01 - Symbol(), Name() and Decimals()
| ----------------------------------------------------------------------*/
string public symbol;
string public name;
uint8 public decimals;
/* ------------------------------------------------------------------------
| 007.02 - Balances for each account
| ----------------------------------------------------------------------*/
mapping(address => uint) balances;
/*------------------------------------------------------------------------
| 007.03 - Owner of account approves the transfer of an amount to another account
| ----------------------------------------------------------------------*/
mapping(address => mapping (address => uint)) allowed;
/* ------------------------------------------------------------------------
| 007.04 - Constructor
| ----------------------------------------------------------------------*/
constructor (
string _symbol,
string _name,
uint8 _decimals,
uint _tokensSold
) Owned() public {
symbol = _symbol;
name = _name;
decimals = _decimals;
tokensSold = _tokensSold;
balances[owner] = _tokensSold;
}
/* ------------------------------------------------------------------------
| 007.05 -Get the account balance of another account with address _owner
| ----------------------------------------------------------------------*/
function balanceOf(address _owner) public constant returns (uint balance) {
return balances[_owner];
}
/* ------------------------------------------------------------------------
| 007.06 - Transfer the balance from owner's account to another account
| ----------------------------------------------------------------------*/
function transfer(address _to, uint _amount) public returns (bool success) {
if (balances[msg.sender] >= _amount // User has balance
&& _amount > 0 // Non-zero transfer
&& balances[_to] + _amount > balances[_to] // Overflow check
) {
balances[msg.sender] = balances[msg.sender].safeSub(_amount);
balances[_to] = balances[_to].safeAdd(_amount);
emit Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
/* ------------------------------------------------------------------------
| 007.07 - Allow _spender to withdraw from your Account, multiple times, up to the
| _value amount. If this function is called again it overwrites the
| current allowance with _value.
| ----------------------------------------------------------------------*/
function approve(
address _spender,
uint _amount
) public returns (bool success) {
allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
/* ------------------------------------------------------------------------
| 007.08 - Spender of tokens transfer an amount of tokens from the token owner's
| balance to another account. The owner of the tokens must already
| have approved this transfer
| ----------------------------------------------------------------------*/
function transferFrom(
address _from,
address _to,
uint _amount
) public returns (bool success) {
if (balances[_from] >= _amount // _from a/c has a balance
&& allowed[_from][msg.sender] >= _amount // Transfer allowed
&& _amount > 0 // Non-zero transfer
&& balances[_to] + _amount > balances[_to] // Overflow check
) {
balances[_from] = balances[_from].safeSub(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].safeSub(_amount);
balances[_to] = balances[_to].safeAdd(_amount);
emit Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
}
/* ------------------------------------------------------------------------
| 007.09 - Returns the amount of tokens approved by the owner that can be
| transferred to the spender's account
| ----------------------------------------------------------------------*/
function allowance(
address _owner,
address _spender
) public constant returns (uint remaining)
{
return allowed[_owner][_spender];
}
}
/* ----------------------------------------------------------------------------
| 008. contract SheltercoinToken - Sheltercoin ICO Crowdsale
| --------------------------------------------------------------------------*/
contract SHLTSheltercoinToken is ERC20Token, SheltercoinTokCfg {
/* ------------------------------------------------------------------------
| 007.01 - Has the crowdsale been finalised?
| ----------------------------------------------------------------------*/
bool public finalised = false;
/* ------------------------------------------------------------------------
| 007.02 - Number of Tokens per 1 ETH
| This can be adjusted as the ETH/USD rate changes
|
| 007.03 SO
Price per ETH $105.63 Feb 7 2019 coinmarketcap
1 ETH = 2000 SHLT
1 SHLT = 0.0005 ETH
USD 5c
1 billion SHLT = total hard cap
|
| tokensPerEther = 2000
| tokensPerKEther = 2000000
|
/* ----------------------------------------------------------------------*/
uint public tokensPerEther = 2000;
uint public tokensPerKEther = 2000000;
uint public etherSold = 0;
uint public weiSold = 0;
uint public tokens = 0;
uint public dspTokens = 0;
uint public dspTokensSold = 0;
uint public dspEther = 0;
uint public dspEtherSold = 0;
uint public dspWeiSold = 0;
uint public BONUS_VALUE = 0;
uint public bonusTokens = 0;
// Emergency Disaster Relief
string public SCE_Shelter_ID;
string public SCE_Shelter_Desc;
// string public SCE_Emergency_ID;
string public SCE_Emergency_Type;
// string public SCE_UN_Body;
string public SCE_UN_Programme_ID;
string public SCE_Country;
string public SCE_Region;
// string public SCE_Area;
uint public SCE_START_DATE;
uint public SCE_END_DATE;
/* ------------------------------------------------------------------------
| 007.04 - Wallet receiving the raised funds
| - The ICO Contract address
| ----------------------------------------------------------------------*/
address public wallet;
address public tokenContractAdr;
/* ------------------------------------------------------------------------
| 007.05 - Crowdsale participant's accounts need to be client verified client before
| the participant can move their tokens
| ----------------------------------------------------------------------*/
mapping(address => bool) public Whitelisted;
mapping(address => bool) public Blacklisted;
modifier isWhitelisted() {
require(Whitelisted[msg.sender] == true);
_;
}
modifier isBlacklisted() {
require(Blacklisted[msg.sender] == true);
_;
}
/* ------------------------------------------------------------------------
| 007.06 - Constructor
| ----------------------------------------------------------------------*/
constructor (address _wallet)
public ERC20Token(SYMBOL, NAME, DECIMALS, 0)
{
wallet = _wallet;
flg001 = true ;
}
/* ------------------------------------------------------------------------
| 007.07 - Sheltercoin Owner can change the Crowdsale wallet address
| Can be set at any time before or during the Crowdsale
| Not relevant after the crowdsale is finalised as no more contributions
| are accepted
| ----------------------------------------------------------------------*/
function setWallet(address _wallet) public onlyOwner {
wallet = _wallet;
emit WalletUpdated(wallet);
}
event WalletUpdated(address newWallet);
/* ------------------------------------------------------------------------
| 007.08 - Sheltercoin Owner can set number of tokens per 1 x ETH
| Can only be set before the start of the Crowdsale
| ----------------------------------------------------------------------*/
function settokensPerKEther(uint _tokensPerKEther) public onlyOwner {
require(now < START_DATE);
require(_tokensPerKEther > 0);
tokensPerKEther = _tokensPerKEther;
emit tokensPerKEtherUpdated(tokensPerKEther);
}
event tokensPerKEtherUpdated(uint _tokPerKEther);
/* ------------------------------------------------------------------------
| 007.09 - Accept Ethers to buy Tokens during the Crowdsale
| ----------------------------------------------------------------------*/
function () public payable {
ICOContribution(msg.sender);
}
/* ------------------------------------------------------------------------
| 007.10 - Accept Ethers from one account for tokens to be created for another
| account. Can be used by Exchanges to purchase Tokens on behalf of
| it's Customers
| ----------------------------------------------------------------------*/
function ICOContribution(address participant) public payable {
// No contributions after the crowdsale is finalised
require(!finalised);
// Not paused
require(!paused);
// No contributions before the start of the crowdsale
require(now >= START_DATE);
// No contributions after the end of the crowdsale
require(now <= END_DATE);
// No contributions below the minimum (can be 0 ETH)
require(msg.value >= CONTRIBUTIONS_MIN);
// No contributions above a maximum (if maximum is set to non-0)
require(CONTRIBUTIONS_MAX == 0 || msg.value < CONTRIBUTIONS_MAX);
// client verification required before participant can transfer the tokens
require(Whitelisted[msg.sender]);
require(!Blacklisted[msg.sender]);
// Transfer the contributed ethers to the Crowdsale wallet
require(wallet.send(msg.value));
// Calculate number of Tokens for contributed ETH
// `18` is the ETH decimals
// `- decimals` is the token decimals
// `+ 3` for the tokens per 1,000 ETH factor
tokens = msg.value * tokensPerKEther / 10**uint(18 - decimals + 3);
/* create variable bonusTokens. This is the purchase amount adjusted by
any bonus. The SetBonus function is onlyOwner
Bonus is expressed in %, eg 50 = 50%
*/
bonusTokens = msg.value.safeMul(BONUS_VALUE + 100);
bonusTokens = bonusTokens.safeDiv(100);
tokens = bonusTokens;
dspTokens = tokens * tokensPerKEther / 10**uint(18 - decimals + 6);
dspEther = tokens / 10**uint(18);
// Check if the Hard Cap will be exceeded
require(totalSupply + tokens <= TOKENS_HARD_CAP);
require(tokensSold + tokens <= TOKENS_HARD_CAP);
// Crowdsale Address
tokenContractAdr = this;
// safeAdd tokens purchased to Account's balance and TokensSold
balances[participant] = balances[participant].safeAdd(tokens);
tokensSold = tokensSold.safeAdd(tokens);
etherSold = etherSold.safeAdd(dspEther);
weiSold = weiSold + tokenContractAdr.balance;
//weiSold = weiSold + this.balance;
// Event Display Totals
dspTokensSold = dspTokensSold.safeAdd(dspTokens);
dspEtherSold = dspEtherSold.safeAdd(dspEther);
dspWeiSold = dspWeiSold + tokenContractAdr.balance;
//dspWeiSold = dspWeiSold + this.balance;
// Transfer Tokens & Log the tokens purchased
emit Transfer(tokenContractAdr, participant, tokens);
emit TokensBought(participant,bonusTokens, dspWeiSold, dspEther, dspEtherSold, dspTokens, dspTokensSold, tokensPerEther);
}
event TokensBought(address indexed buyer, uint newWei,
uint newWeiBalance, uint newEther, uint EtherTotal, uint _toks, uint newTokenTotal,
uint _toksPerEther);
/* ------------------------------------------------------------------------
| 007.11 - SheltercoinOwner to finalise the Crowdsale
|
| ----------------------------------------------------------------------*/
function finalise() public onlyOwner {
// Can only finalise if raised > soft cap or after the end date
require(tokensSold >= TOKENS_SOFT_CAP || now > END_DATE);
// Can only finalise once
require(!finalised);
// Crowdsale Address
tokenContractAdr = this;
// Write out the total
emit TokensBought(tokenContractAdr, 0, dspWeiSold, dspEther, dspEtherSold, dspTokens, dspTokensSold, tokensPerEther);
// Can only finalise once
finalised = true;
}
/* ------------------------------------------------------------------------
| 007.12 - Sheltercoin Owner to safeAdd Pre-sales funding token balance before the Crowdsale
| commences
| ----------------------------------------------------------------------*/
function ICOAddPrecommitment(address participant, uint balance) public onlyOwner {
// Not paused
require(!paused);
// No contributions after the start of the crowdsale
// Allowing off chain contributions during the Crowdsale
// Allowing contributions after the end of the crowdsale
// Off Chain SHLT Balance to Transfer
require(balance > 0);
//Address field is completed
require(address(participant) != 0x0);
// safeAdd tokens purchased to Account's balance and TokensSold
tokenContractAdr = this;
balances[participant] = balances[participant].safeAdd(balance);
tokensSold = tokensSold.safeAdd(balance);
emit Transfer(tokenContractAdr, participant, balance);
}
event ICOcommitmentAdded(address indexed participant, uint balance, uint tokensSold );
/* ------------------------------------------------------------------------
| 007.12a - Sheltercoin Owner to Change ICO Start Date or ICO End Date
| commences
| ----------------------------------------------------------------------*/
function ICOdt(uint START_DATE_NEW, uint END_DATE_NEW ) public onlyOwner {
// No contributions after the crowdsale is finalised
require(!finalised);
// Not paused
require(!paused);
// Allowed to change any time
// No 0
require(START_DATE_NEW > 0);
require(END_DATE_NEW > 0);
tokenContractAdr = this;
START_DATE = START_DATE_NEW;
END_DATE = END_DATE_NEW;
emit ICOdate(START_DATE, END_DATE);
}
event ICOdate(uint ST_DT, uint END_DT);
/* ----------------------------------------------------------------------
| 007.13 - Transfer the Balance from Owner's account to another account, with client
| verification check for the crowdsale participant's first transfer
| ----------------------------------------------------------------------*/
function transfer(address _to, uint _amount) public returns (bool success) {
// Cannot transfer before crowdsale ends
// require(finalised);
// require(flg002transfer);
// Cannot transfer if Client verification is required
//require(!clientRequired[msg.sender]);
// Standard transfer
return super.transfer(_to, _amount);
}
/* ------------------------------------------------------------------------
| 007.14 - Spender of tokens transfer an amount of tokens from the token Owner's
| balance to another account, with Client verification check for the
| Crowdsale participant's first transfer
| ----------------------------------------------------------------------*/
function transferFrom(address _from, address _to, uint _amount)
public returns (bool success)
{
// Cannot transfer before crowdsale ends
// require(flg002transfer);
// Cannot transfer if Client verification is required
//require(!clientRequired[_from]);
// Standard transferFrom
return super.transferFrom(_from, _to, _amount);
}
/* ------------------------------------------------------------------------
| 007.16 - Any account can burn _from's tokens as long as the _from account has
| approved the _amount to be burnt using
| approve(0x0, _amount)
| ----------------------------------------------------------------------*/
function mintFrom(
address _from,
uint _amount
) public returns (bool success) {
if (balances[_from] >= _amount // From a/c has balance
&& allowed[_from][0x0] >= _amount // Transfer approved
&& _amount > 0 // Non-zero transfer
&& balances[0x0] + _amount > balances[0x0] // Overflow check
) {
balances[_from] = balances[_from].safeSub(_amount);
allowed[_from][0x0] = allowed[_from][0x0].safeSub(_amount);
balances[0x0] = balances[0x0].safeAdd(_amount);
tokensSold = tokensSold.safeSub(_amount);
emit Transfer(_from, 0x0, _amount);
return true;
} else {
return false;
}
}
/* ------------------------------------------------------------------------
| 007.17 - Set bonus percentage multiplier. 50% = * 1.5
| ----------------------------------------------------------------------*/
function setBonus(uint _bonus) public onlyOwner
returns (bool success) {
require (!finalised);
if (_bonus >= 0) // From a/c is owner
{
BONUS_VALUE = _bonus;
return true;
} else {
return false;
}
emit BonusSet(_bonus);
}
event BonusSet(uint _bonus);
/* ------------------------------------------------------------------------
| 007.15 - SheltercoinOwner to Client verify the participant's account
| ----------------------------------------------------------------------*/
function AddToWhitelist(address participant) public onlyOwner {
Whitelisted[participant] = true;
emit AddedToWhitelist(participant);
}
event AddedToWhitelist(address indexed participant);
function IsWhitelisted(address participant)
public view returns (bool) {
return bool(Whitelisted[participant]);
}
function RemoveFromWhitelist(address participant) public onlyOwner {
Whitelisted[participant] = false;
emit RemovedFromWhitelist(participant);
}
event RemovedFromWhitelist(address indexed participant);
function AddToBlacklist(address participant) public onlyOwner {
Blacklisted[participant] = true;
emit AddedToBlacklist(participant);
}
event AddedToBlacklist(address indexed participant);
function IsBlacklisted(address participant)
public view returns (bool) {
return bool(Blacklisted[participant]);
}
function RemoveFromBlackList(address participant) public onlyOwner {
Blacklisted[participant] = false;
emit RemovedFromBlacklist(participant);
}
event RemovedFromBlacklist(address indexed participant);
function SCEmergency(string _Shelter_ID, string _Shelter_Description, string _Emergency_Type, string _UN_Programme_ID, string _Country, string _Region, uint START_DATE_SCE, uint END_DATE_SCE ) public onlyOwner {
// Disaster Occur's
finalised = true;
require(finalised);
// Not paused
//require(!paused);
// No 0
require(START_DATE_SCE > 0);
// Write to the blockchain
tokenContractAdr = this;
SCE_Shelter_ID = _Shelter_ID;
SCE_Shelter_Desc = _Shelter_Description;
SCE_Emergency_Type = _Emergency_Type;
SCE_UN_Programme_ID = _UN_Programme_ID;
SCE_Country = _Country;
SCE_Region = _Region;
SCE_START_DATE = START_DATE_SCE;
SCE_END_DATE = END_DATE_SCE;
emit SC_Emergency(SCE_Shelter_ID, SCE_Shelter_Desc, SCE_Emergency_Type, SCE_UN_Programme_ID, SCE_Country, SCE_Region, SCE_START_DATE, SCE_END_DATE );
}
event SC_Emergency(string _str_Shelter_ID, string _str_Shelter_Descrip, string _str_Emergency_Type, string _str_UN_Prog_ID, string _str_Country, string _str_Region, uint SC_ST_DT, uint SC_END_DT);
} | Disaster Occur's Not pausedrequire(!paused); No 0 Write to the blockchain | function SCEmergency(string _Shelter_ID, string _Shelter_Description, string _Emergency_Type, string _UN_Programme_ID, string _Country, string _Region, uint START_DATE_SCE, uint END_DATE_SCE ) public onlyOwner {
finalised = true;
require(finalised);
require(START_DATE_SCE > 0);
tokenContractAdr = this;
SCE_Shelter_ID = _Shelter_ID;
SCE_Shelter_Desc = _Shelter_Description;
SCE_Emergency_Type = _Emergency_Type;
SCE_UN_Programme_ID = _UN_Programme_ID;
SCE_Country = _Country;
SCE_Region = _Region;
SCE_START_DATE = START_DATE_SCE;
SCE_END_DATE = END_DATE_SCE;
emit SC_Emergency(SCE_Shelter_ID, SCE_Shelter_Desc, SCE_Emergency_Type, SCE_UN_Programme_ID, SCE_Country, SCE_Region, SCE_START_DATE, SCE_END_DATE );
}
event SC_Emergency(string _str_Shelter_ID, string _str_Shelter_Descrip, string _str_Emergency_Type, string _str_UN_Prog_ID, string _str_Country, string _str_Region, uint SC_ST_DT, uint SC_END_DT);
| 2,509,303 |
./full_match/1/0xABE46f13C833Ab07bf9e523F485B53c9a633DD60/sources/contracts/IdleCDO.sol | _fee new fee | function setFee(uint256 _fee) external {
_checkOnlyOwner();
require((fee = _fee) <= MAX_FEE, '7');
}
| 8,321,926 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControlEnumerable.sol";
import "./AccessControl.sol";
import "../utils/structs/EnumerableSet.sol";
/**
*
* @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; // 角色对应的地址
/**
* ERC165 标准
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); // super 用的好
}
/**
* 根据序号某角色的账户 公开函数 只读
* @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); // 额外增加账户
}
}
| 撤销角色 公开函数 可重写 Overload {revokeRole} to track enumerable memberships/ | function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.revokeRole(role, account);
}
| 1,792,570 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "../../openzeppelin-upgradeable/token/ERC1155/ERC1155Upgradeable.sol";
import "../libraries-solidity/access/AdminControlUpgradeable.sol";
import "./core/ERC1155CreatorCore.sol";
/**
* @dev ERC1155Creator implementation
*/
contract ERC1155CreatorImplementation is
AdminControlUpgradeable,
ERC1155Upgradeable,
ERC1155CreatorCore
{
mapping(uint256 => uint256) private _totalSupply;
/**
* Initializer
*/
function initialize() public initializer {
__ERC1155_init("");
__Ownable_init();
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(
ERC1155Upgradeable,
ERC1155CreatorCore,
AdminControlUpgradeable
)
returns (bool)
{
return
ERC1155CreatorCore.supportsInterface(interfaceId) ||
ERC1155Upgradeable.supportsInterface(interfaceId) ||
AdminControlUpgradeable.supportsInterface(interfaceId);
}
function _beforeTokenTransfer(
address,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory
) internal virtual override {
_approveTransfer(from, to, ids, amounts);
}
/**
* @dev See {ICreatorCore-registerExtension}.
*/
function registerExtension(address extension, string calldata baseURI)
external
override
adminRequired
nonBlacklistRequired(extension)
{
_registerExtension(extension, baseURI, false);
}
/**
* @dev See {ICreatorCore-registerExtension}.
*/
function registerExtension(
address extension,
string calldata baseURI,
bool baseURIIdentical
) external override adminRequired nonBlacklistRequired(extension) {
_registerExtension(extension, baseURI, baseURIIdentical);
}
/**
* @dev See {ICreatorCore-unregisterExtension}.
*/
function unregisterExtension(address extension)
external
override
adminRequired
{
_unregisterExtension(extension);
}
/**
* @dev See {ICreatorCore-blacklistExtension}.
*/
function blacklistExtension(address extension)
external
override
adminRequired
{
_blacklistExtension(extension);
}
/**
* @dev See {ICreatorCore-setBaseTokenURIExtension}.
*/
function setBaseTokenURIExtension(string calldata uri_)
external
override
extensionRequired
{
_setBaseTokenURIExtension(uri_, false);
}
/**
* @dev See {ICreatorCore-setBaseTokenURIExtension}.
*/
function setBaseTokenURIExtension(string calldata uri_, bool identical)
external
override
extensionRequired
{
_setBaseTokenURIExtension(uri_, identical);
}
/**
* @dev See {ICreatorCore-setTokenURIPrefixExtension}.
*/
function setTokenURIPrefixExtension(string calldata prefix)
external
override
extensionRequired
{
_setTokenURIPrefixExtension(prefix);
}
/**
* @dev See {ICreatorCore-setTokenURIExtension}.
*/
function setTokenURIExtension(uint256 tokenId, string calldata uri_)
external
override
extensionRequired
{
_setTokenURIExtension(tokenId, uri_);
}
/**
* @dev See {ICreatorCore-setTokenURIExtension}.
*/
function setTokenURIExtension(
uint256[] memory tokenIds,
string[] calldata uris
) external override extensionRequired {
require(tokenIds.length == uris.length, "Invalid input");
for (uint256 i = 0; i < tokenIds.length; i++) {
_setTokenURIExtension(tokenIds[i], uris[i]);
}
}
/**
* @dev See {ICreatorCore-setBaseTokenURI}.
*/
function setBaseTokenURI(string calldata uri_)
external
override
adminRequired
{
_setBaseTokenURI(uri_);
}
/**
* @dev See {ICreatorCore-setTokenURIPrefix}.
*/
function setTokenURIPrefix(string calldata prefix)
external
override
adminRequired
{
_setTokenURIPrefix(prefix);
}
/**
* @dev See {ICreatorCore-setTokenURI}.
*/
function setTokenURI(uint256 tokenId, string calldata uri_)
external
override
adminRequired
{
_setTokenURI(tokenId, uri_);
}
/**
* @dev See {ICreatorCore-setTokenURI}.
*/
function setTokenURI(uint256[] memory tokenIds, string[] calldata uris)
external
override
adminRequired
{
require(tokenIds.length == uris.length, "Invalid input");
for (uint256 i = 0; i < tokenIds.length; i++) {
_setTokenURI(tokenIds[i], uris[i]);
}
}
/**
* @dev See {ICreatorCore-setMintPermissions}.
*/
function setMintPermissions(address extension, address permissions)
external
override
adminRequired
{
_setMintPermissions(extension, permissions);
}
/**
* @dev See {IERC1155CreatorCore-mintBaseNew}.
*/
function mintBaseNew(
address[] calldata to,
uint256[] calldata amounts,
string[] calldata uris
)
public
virtual
override
nonReentrant
adminRequired
returns (uint256[] memory)
{
return _mintNew(address(this), to, amounts, uris);
}
/**
* @dev See {IERC1155CreatorCore-mintBaseExisting}.
*/
function mintBaseExisting(
address[] calldata to,
uint256[] calldata tokenIds,
uint256[] calldata amounts
) public virtual override nonReentrant adminRequired {
for (uint256 i = 0; i < tokenIds.length; i++) {
require(
_tokensExtension[tokenIds[i]] == address(this),
"A token was created by an extension"
);
}
_mintExisting(address(this), to, tokenIds, amounts);
}
/**
* @dev See {IERC1155CreatorCore-mintExtensionNew}.
*/
function mintExtensionNew(
address[] calldata to,
uint256[] calldata amounts,
string[] calldata uris
)
public
virtual
override
nonReentrant
extensionRequired
returns (uint256[] memory tokenIds)
{
return _mintNew(msg.sender, to, amounts, uris);
}
/**
* @dev See {IERC1155CreatorCore-mintExtensionExisting}.
*/
function mintExtensionExisting(
address[] calldata to,
uint256[] calldata tokenIds,
uint256[] calldata amounts
) public virtual override nonReentrant extensionRequired {
for (uint256 i = 0; i < tokenIds.length; i++) {
require(
_tokensExtension[tokenIds[i]] == address(msg.sender),
"A token was not created by this extension"
);
}
_mintExisting(msg.sender, to, tokenIds, amounts);
}
/**
* @dev Mint new tokens
*/
function _mintNew(
address extension,
address[] memory to,
uint256[] memory amounts,
string[] memory uris
) internal returns (uint256[] memory tokenIds) {
if (to.length > 1) {
// Multiple receiver. Give every receiver the same new token
tokenIds = new uint256[](1);
require(
uris.length <= 1 &&
(amounts.length == 1 || to.length == amounts.length),
"Invalid input"
);
} else {
// Single receiver. Generating multiple tokens
tokenIds = new uint256[](amounts.length);
require(
uris.length == 0 || amounts.length == uris.length,
"Invalid input"
);
}
// Assign tokenIds
for (uint256 i = 0; i < tokenIds.length; i++) {
_tokenCount++;
tokenIds[i] = _tokenCount;
// Track the extension that minted the token
_tokensExtension[_tokenCount] = extension;
}
if (extension != address(this)) {
_checkMintPermissions(to, tokenIds, amounts);
}
if (to.length == 1 && tokenIds.length == 1) {
// Single mint
_mint(to[0], tokenIds[0], amounts[0], new bytes(0));
} else if (to.length > 1) {
// Multiple receivers. Receiving the same token
if (amounts.length == 1) {
// Everyone receiving the same amount
for (uint256 i = 0; i < to.length; i++) {
_mint(to[i], tokenIds[0], amounts[0], new bytes(0));
}
} else {
// Everyone receiving different amounts
for (uint256 i = 0; i < to.length; i++) {
_mint(to[i], tokenIds[0], amounts[i], new bytes(0));
}
}
} else {
_mintBatch(to[0], tokenIds, amounts, new bytes(0));
}
for (uint256 i = 0; i < tokenIds.length; i++) {
if (i < uris.length && bytes(uris[i]).length > 0) {
_tokenURIs[tokenIds[i]] = uris[i];
}
}
return tokenIds;
}
/**
* @dev Mint existing tokens
*/
function _mintExisting(
address extension,
address[] memory to,
uint256[] memory tokenIds,
uint256[] memory amounts
) internal {
if (extension != address(this)) {
_checkMintPermissions(to, tokenIds, amounts);
}
if (to.length == 1 && tokenIds.length == 1 && amounts.length == 1) {
// Single mint
_mint(to[0], tokenIds[0], amounts[0], new bytes(0));
} else if (to.length == 1 && tokenIds.length == amounts.length) {
// Batch mint to same receiver
_mintBatch(to[0], tokenIds, amounts, new bytes(0));
} else if (tokenIds.length == 1 && amounts.length == 1) {
// Mint of the same token/token amounts to various receivers
for (uint256 i = 0; i < to.length; i++) {
_mint(to[i], tokenIds[0], amounts[0], new bytes(0));
}
} else if (tokenIds.length == 1 && to.length == amounts.length) {
// Mint of the same token with different amounts to different receivers
for (uint256 i = 0; i < to.length; i++) {
_mint(to[i], tokenIds[0], amounts[i], new bytes(0));
}
} else if (
to.length == tokenIds.length && to.length == amounts.length
) {
// Mint of different tokens and different amounts to different receivers
for (uint256 i = 0; i < to.length; i++) {
_mint(to[i], tokenIds[i], amounts[i], new bytes(0));
}
} else {
revert("Invalid input");
}
}
/**
* @dev See {IERC1155CreatorCore-tokenExtension}.
*/
function tokenExtension(uint256 tokenId)
public
view
virtual
override
returns (address)
{
return _tokenExtension(tokenId);
}
/**
* @dev See {IERC1155CreatorCore-burn}.
*/
function burn(
address account,
uint256[] memory tokenIds,
uint256[] memory amounts
) public virtual override nonReentrant {
require(
account == msg.sender || isApprovedForAll(account, msg.sender),
"Caller is not owner nor approved"
);
require(tokenIds.length == amounts.length, "Invalid input");
if (tokenIds.length == 1) {
_burn(account, tokenIds[0], amounts[0]);
} else {
_burnBatch(account, tokenIds, amounts);
}
_postBurn(account, tokenIds, amounts);
}
/**
* @dev See {ICreatorCore-setRoyalties}.
*/
function setRoyalties(
address payable[] calldata receivers,
uint256[] calldata basisPoints
) external override adminRequired {
_setRoyaltiesExtension(address(this), receivers, basisPoints);
}
/**
* @dev See {ICreatorCore-setRoyalties}.
*/
function setRoyalties(
uint256 tokenId,
address payable[] calldata receivers,
uint256[] calldata basisPoints
) external override adminRequired {
_setRoyalties(tokenId, receivers, basisPoints);
}
/**
* @dev See {ICreatorCore-setRoyaltiesExtension}.
*/
function setRoyaltiesExtension(
address extension,
address payable[] calldata receivers,
uint256[] calldata basisPoints
) external override adminRequired {
_setRoyaltiesExtension(extension, receivers, basisPoints);
}
/**
* @dev {See ICreatorCore-getRoyalties}.
*/
function getRoyalties(uint256 tokenId)
external
view
virtual
override
returns (address payable[] memory, uint256[] memory)
{
return _getRoyalties(tokenId);
}
/**
* @dev {See ICreatorCore-getFees}.
*/
function getFees(uint256 tokenId)
external
view
virtual
override
returns (address payable[] memory, uint256[] memory)
{
return _getRoyalties(tokenId);
}
/**
* @dev {See ICreatorCore-getFeeRecipients}.
*/
function getFeeRecipients(uint256 tokenId)
external
view
virtual
override
returns (address payable[] memory)
{
return _getRoyaltyReceivers(tokenId);
}
/**
* @dev {See ICreatorCore-getFeeBps}.
*/
function getFeeBps(uint256 tokenId)
external
view
virtual
override
returns (uint256[] memory)
{
return _getRoyaltyBPS(tokenId);
}
/**
* @dev {See ICreatorCore-royaltyInfo}.
*/
function royaltyInfo(uint256 tokenId, uint256 value)
external
view
virtual
override
returns (address, uint256)
{
return _getRoyaltyInfo(tokenId, value);
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function uri(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
return _tokenURI(tokenId);
}
/**
* @dev Total amount of tokens in with a given id.
*/
function totalSupply(uint256 tokenId)
external
view
virtual
override
returns (uint256)
{
return _totalSupply[tokenId];
}
/**
* @dev See {ERC1155-_mint}.
*/
function _mint(
address account,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual override {
super._mint(account, id, amount, data);
_totalSupply[id] += amount;
}
/**
* @dev See {ERC1155-_mintBatch}.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override {
super._mintBatch(to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
_totalSupply[ids[i]] += amounts[i];
}
}
/**
* @dev See {ERC1155-_burn}.
*/
function _burn(
address account,
uint256 id,
uint256 amount
) internal virtual override {
super._burn(account, id, amount);
_totalSupply[id] -= amount;
}
/**
* @dev See {ERC1155-_burnBatch}.
*/
function _burnBatch(
address account,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual override {
super._burnBatch(account, ids, amounts);
for (uint256 i = 0; i < ids.length; ++i) {
_totalSupply[ids[i]] -= amounts[i];
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC1155/ERC1155.sol)
pragma solidity ^0.8.0;
import "./IERC1155Upgradeable.sol";
import "./IERC1155ReceiverUpgradeable.sol";
import "./extensions/IERC1155MetadataURIUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC1155Upgradeable, IERC1155MetadataURIUpgradeable {
using AddressUpgradeable for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
function __ERC1155_init(string memory uri_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC1155_init_unchained(uri_);
}
function __ERC1155_init_unchained(string memory uri_) internal initializer {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC1155Upgradeable).interfaceId ||
interfaceId == type(IERC1155MetadataURIUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155ReceiverUpgradeable(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155ReceiverUpgradeable.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155ReceiverUpgradeable.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
uint256[47] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "../../../openzeppelin/utils/structs/EnumerableSet.sol";
import "../../../openzeppelin/utils/introspection/ERC165.sol";
import "../../../openzeppelin-upgradeable/access/OwnableUpgradeable.sol";
import "./IAdminControl.sol";
abstract contract AdminControlUpgradeable is
OwnableUpgradeable,
IAdminControl,
ERC165
{
using EnumerableSet for EnumerableSet.AddressSet;
// Track registered admins
EnumerableSet.AddressSet private _admins;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IAdminControl).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev Only allows approved admins to call the specified function
*/
modifier adminRequired() {
require(
owner() == msg.sender || _admins.contains(msg.sender),
"AdminControl: Must be owner or admin"
);
_;
}
/**
* @dev See {IAdminControl-getAdmins}.
*/
function getAdmins()
external
view
override
returns (address[] memory admins)
{
admins = new address[](_admins.length());
for (uint256 i = 0; i < _admins.length(); i++) {
admins[i] = _admins.at(i);
}
return admins;
}
/**
* @dev See {IAdminControl-approveAdmin}.
*/
function approveAdmin(address admin) external override onlyOwner {
if (!_admins.contains(admin)) {
emit AdminApproved(admin, msg.sender);
_admins.add(admin);
}
}
/**
* @dev See {IAdminControl-revokeAdmin}.
*/
function revokeAdmin(address admin) external override onlyOwner {
if (_admins.contains(admin)) {
emit AdminRevoked(admin, msg.sender);
_admins.remove(admin);
}
}
/**
* @dev See {IAdminControl-isAdmin}.
*/
function isAdmin(address admin) public view override returns (bool) {
return (owner() == admin || _admins.contains(admin));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "../../../openzeppelin/utils/structs/EnumerableSet.sol";
import "../extensions/ERC1155/IERC1155CreatorExtensionApproveTransfer.sol";
import "../extensions/ERC1155/IERC1155CreatorExtensionBurnable.sol";
import "../permissions/ERC1155/IERC1155CreatorMintPermissions.sol";
import "./IERC1155CreatorCore.sol";
import "./CreatorCore.sol";
/**
* @dev Core ERC1155 creator implementation
*/
abstract contract ERC1155CreatorCore is CreatorCore, IERC1155CreatorCore {
using EnumerableSet for EnumerableSet.AddressSet;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(CreatorCore, IERC165)
returns (bool)
{
return
interfaceId == type(IERC1155CreatorCore).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {ICreatorCore-setApproveTransferExtension}.
*/
function setApproveTransferExtension(bool enabled)
external
override
extensionRequired
{
require(
!enabled ||
ERC165Checker.supportsInterface(
msg.sender,
type(IERC1155CreatorExtensionApproveTransfer).interfaceId
),
"Extension must implement IERC1155CreatorExtensionApproveTransfer"
);
if (_extensionApproveTransfers[msg.sender] != enabled) {
_extensionApproveTransfers[msg.sender] = enabled;
emit ExtensionApproveTransferUpdated(msg.sender, enabled);
}
}
/**
* @dev Set mint permissions for an extension
*/
function _setMintPermissions(address extension, address permissions)
internal
{
require(_extensions.contains(extension), "Invalid extension");
require(
permissions == address(0x0) ||
ERC165Checker.supportsInterface(
permissions,
type(IERC1155CreatorMintPermissions).interfaceId
),
"Invalid address"
);
if (_extensionPermissions[extension] != permissions) {
_extensionPermissions[extension] = permissions;
emit MintPermissionsUpdated(extension, permissions, msg.sender);
}
}
/**
* Check if an extension can mint
*/
function _checkMintPermissions(
address[] memory to,
uint256[] memory tokenIds,
uint256[] memory amounts
) internal {
if (_extensionPermissions[msg.sender] != address(0x0)) {
IERC1155CreatorMintPermissions(_extensionPermissions[msg.sender])
.approveMint(msg.sender, to, tokenIds, amounts);
}
}
/**
* Post burn actions
*/
function _postBurn(
address owner,
uint256[] memory tokenIds,
uint256[] memory amounts
) internal virtual {
require(tokenIds.length > 0, "Invalid input");
address extension = _tokensExtension[tokenIds[0]];
for (uint256 i = 0; i < tokenIds.length; i++) {
require(
_tokensExtension[tokenIds[i]] == extension,
"Mismatched token originators"
);
}
// Callback to originating extension if needed
if (extension != address(this)) {
if (
ERC165Checker.supportsInterface(
extension,
type(IERC1155CreatorExtensionBurnable).interfaceId
)
) {
IERC1155CreatorExtensionBurnable(extension).onBurn(
owner,
tokenIds,
amounts
);
}
}
}
/**
* Approve a transfer
*/
function _approveTransfer(
address from,
address to,
uint256[] memory tokenIds,
uint256[] memory amounts
) internal {
require(tokenIds.length > 0, "Invalid input");
address extension = _tokensExtension[tokenIds[0]];
for (uint256 i = 0; i < tokenIds.length; i++) {
require(
_tokensExtension[tokenIds[i]] == extension,
"Mismatched token originators"
);
}
if (_extensionApproveTransfers[extension]) {
require(
IERC1155CreatorExtensionApproveTransfer(extension)
.approveTransfer(from, to, tokenIds, amounts),
"Extension approval failure"
);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.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 IERC1155Upgradeable is IERC165Upgradeable {
/**
* @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
// OpenZeppelin Contracts v4.4.0 (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155ReceiverUpgradeable is IERC165Upgradeable {
/**
* @dev Handles the receipt of a single ERC1155 token type. This function is
* called at the end of a `safeTransferFrom` after the balance has been updated.
*
* NOTE: To accept the transfer, this must return
* `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* (i.e. 0xf23a6e61, or its own function selector).
*
* @param operator The address which initiated the transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param id The ID of the token being transferred
* @param value The amount of tokens being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
* @dev Handles the receipt of a multiple ERC1155 token types. This function
* is called at the end of a `safeBatchTransferFrom` after the balances have
* been updated.
*
* NOTE: To accept the transfer(s), this must return
* `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* (i.e. 0xbc197c81, or its own function selector).
*
* @param operator The address which initiated the batch transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param ids An array containing ids of each token being transferred (order and length must match values array)
* @param values An array containing amounts of each token being transferred (order and length must match ids array)
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC1155/extensions/IERC1155MetadataURI.sol)
pragma solidity ^0.8.0;
import "../IERC1155Upgradeable.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURIUpgradeable is IERC1155Upgradeable {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library 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;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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.0 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "../../../openzeppelin/utils/introspection/IERC165.sol";
/**
* @dev Interface for admin control
*/
interface IAdminControl is IERC165 {
event AdminApproved(address indexed account, address indexed sender);
event AdminRevoked(address indexed account, address indexed sender);
/**
* @dev gets address of all admins
*/
function getAdmins() external view returns (address[] memory);
/**
* @dev add an admin. Can only be called by contract owner.
*/
function approveAdmin(address admin) external;
/**
* @dev remove an admin. Can only be called by contract owner.
*/
function revokeAdmin(address admin) external;
/**
* @dev checks whether or not given address is an admin
* Returns True if they are
*/
function isAdmin(address admin) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "../../../../openzeppelin/utils/introspection/IERC165.sol";
/**
* Implement this if you want your extension to approve a transfer
*/
interface IERC1155CreatorExtensionApproveTransfer is IERC165 {
/**
* @dev Set whether or not the creator contract will check the extension for approval of token transfer
*/
function setApproveTransfer(address creator, bool enabled) external;
/**
* @dev Called by creator contract to approve a transfer
*/
function approveTransfer(
address from,
address to,
uint256[] calldata tokenIds,
uint256[] calldata amounts
) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "../../../../openzeppelin/utils/introspection/IERC165.sol";
/**
* @dev Your extension is required to implement this interface if it wishes
* to receive the onBurn callback whenever a token the extension created is
* burned
*/
interface IERC1155CreatorExtensionBurnable is IERC165 {
/**
* @dev callback handler for burn events
*/
function onBurn(
address owner,
uint256[] calldata tokenIds,
uint256[] calldata amounts
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "../../../../openzeppelin/utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155Creator compliant extension contracts.
*/
interface IERC1155CreatorMintPermissions is IERC165 {
/**
* @dev get approval to mint
*/
function approveMint(
address extension,
address[] calldata to,
uint256[] calldata tokenIds,
uint256[] calldata amounts
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "./CreatorCore.sol";
/**
* @dev Core ERC1155 creator interface
*/
interface IERC1155CreatorCore is ICreatorCore {
/**
* @dev mint a token with no extension. Can only be called by an admin.
*
* @param to - Can be a single element array (all tokens go to same address) or multi-element array (single token to many recipients)
* @param amounts - Can be a single element array (all recipients get the same amount) or a multi-element array
* @param uris - If no elements, all tokens use the default uri.
* If any element is an empty string, the corresponding token uses the default uri.
*
*
* Requirements: If to is a multi-element array, then uris must be empty or single element array
* If to is a multi-element array, then amounts must be a single element array or a multi-element array of the same size
* If to is a single element array, uris must be empty or the same length as amounts
*
* Examples:
* mintBaseNew(['0x....1', '0x....2'], [1], [])
* Mints a single new token, and gives 1 each to '0x....1' and '0x....2'. Token uses default uri.
*
* mintBaseNew(['0x....1', '0x....2'], [1, 2], [])
* Mints a single new token, and gives 1 to '0x....1' and 2 to '0x....2'. Token uses default uri.
*
* mintBaseNew(['0x....1'], [1, 2], ["", "http://token2.com"])
* Mints two new tokens to '0x....1'. 1 of the first token, 2 of the second. 1st token uses default uri, second uses "http://token2.com".
*
* @return Returns list of tokenIds minted
*/
function mintBaseNew(address[] calldata to, uint256[] calldata amounts, string[] calldata uris) external returns (uint256[] memory);
/**
* @dev batch mint existing token with no extension. Can only be called by an admin.
*
* @param to - Can be a single element array (all tokens go to same address) or multi-element array (single token to many recipients)
* @param tokenIds - Can be a single element array (all recipients get the same token) or a multi-element array
* @param amounts - Can be a single element array (all recipients get the same amount) or a multi-element array
*
* Requirements: If any of the parameters are multi-element arrays, they need to be the same length as other multi-element arrays
*
* Examples:
* mintBaseExisting(['0x....1', '0x....2'], [1], [10])
* Mints 10 of tokenId 1 to each of '0x....1' and '0x....2'.
*
* mintBaseExisting(['0x....1', '0x....2'], [1, 2], [10, 20])
* Mints 10 of tokenId 1 to '0x....1' and 20 of tokenId 2 to '0x....2'.
*
* mintBaseExisting(['0x....1'], [1, 2], [10, 20])
* Mints 10 of tokenId 1 and 20 of tokenId 2 to '0x....1'.
*
* mintBaseExisting(['0x....1', '0x....2'], [1], [10, 20])
* Mints 10 of tokenId 1 to '0x....1' and 20 of tokenId 1 to '0x....2'.
*
*/
function mintBaseExisting(address[] calldata to, uint256[] calldata tokenIds, uint256[] calldata amounts) external;
/**
* @dev mint a token from an extension. Can only be called by a registered extension.
*
* @param to - Can be a single element array (all tokens go to same address) or multi-element array (single token to many recipients)
* @param amounts - Can be a single element array (all recipients get the same amount) or a multi-element array
* @param uris - If no elements, all tokens use the default uri.
* If any element is an empty string, the corresponding token uses the default uri.
*
*
* Requirements: If to is a multi-element array, then uris must be empty or single element array
* If to is a multi-element array, then amounts must be a single element array or a multi-element array of the same size
* If to is a single element array, uris must be empty or the same length as amounts
*
* Examples:
* mintExtensionNew(['0x....1', '0x....2'], [1], [])
* Mints a single new token, and gives 1 each to '0x....1' and '0x....2'. Token uses default uri.
*
* mintExtensionNew(['0x....1', '0x....2'], [1, 2], [])
* Mints a single new token, and gives 1 to '0x....1' and 2 to '0x....2'. Token uses default uri.
*
* mintExtensionNew(['0x....1'], [1, 2], ["", "http://token2.com"])
* Mints two new tokens to '0x....1'. 1 of the first token, 2 of the second. 1st token uses default uri, second uses "http://token2.com".
*
* @return Returns list of tokenIds minted
*/
function mintExtensionNew(address[] calldata to, uint256[] calldata amounts, string[] calldata uris) external returns (uint256[] memory);
/**
* @dev batch mint existing token from extension. Can only be called by a registered extension.
*
* @param to - Can be a single element array (all tokens go to same address) or multi-element array (single token to many recipients)
* @param tokenIds - Can be a single element array (all recipients get the same token) or a multi-element array
* @param amounts - Can be a single element array (all recipients get the same amount) or a multi-element array
*
* Requirements: If any of the parameters are multi-element arrays, they need to be the same length as other multi-element arrays
*
* Examples:
* mintExtensionExisting(['0x....1', '0x....2'], [1], [10])
* Mints 10 of tokenId 1 to each of '0x....1' and '0x....2'.
*
* mintExtensionExisting(['0x....1', '0x....2'], [1, 2], [10, 20])
* Mints 10 of tokenId 1 to '0x....1' and 20 of tokenId 2 to '0x....2'.
*
* mintExtensionExisting(['0x....1'], [1, 2], [10, 20])
* Mints 10 of tokenId 1 and 20 of tokenId 2 to '0x....1'.
*
* mintExtensionExisting(['0x....1', '0x....2'], [1], [10, 20])
* Mints 10 of tokenId 1 to '0x....1' and 20 of tokenId 1 to '0x....2'.
*
*/
function mintExtensionExisting(address[] calldata to, uint256[] calldata tokenIds, uint256[] calldata amounts) external;
/**
* @dev burn tokens. Can only be called by token owner or approved address.
* On burn, calls back to the registered extension's onBurn method
*/
function burn(address account, uint256[] calldata tokenIds, uint256[] calldata amounts) external;
/**
* @dev Total amount of tokens in with a given tokenId.
*/
function totalSupply(uint256 tokenId) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "../../../openzeppelin/security/ReentrancyGuard.sol";
import "../../../openzeppelin/utils/Strings.sol";
import "../../../openzeppelin/utils/introspection/ERC165.sol";
import "../../../openzeppelin/utils/introspection/ERC165Checker.sol";
import "../../../openzeppelin/utils/structs/EnumerableSet.sol";
import "../../../openzeppelin-upgradeable/utils/AddressUpgradeable.sol";
import "../extensions/ICreatorExtensionTokenURI.sol";
import "./ICreatorCore.sol";
/**
* @dev Core creator implementation
*/
abstract contract CreatorCore is ReentrancyGuard, ICreatorCore, ERC165 {
using Strings for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
using AddressUpgradeable for address;
uint256 _tokenCount = 0;
// Track registered extensions data
EnumerableSet.AddressSet internal _extensions;
EnumerableSet.AddressSet internal _blacklistedExtensions;
mapping(address => address) internal _extensionPermissions;
mapping(address => bool) internal _extensionApproveTransfers;
// For tracking which extension a token was minted by
mapping(uint256 => address) internal _tokensExtension;
// The baseURI for a given extension
mapping(address => string) private _extensionBaseURI;
mapping(address => bool) private _extensionBaseURIIdentical;
// The prefix for any tokens with a uri configured
mapping(address => string) private _extensionURIPrefix;
// Mapping for individual token URIs
mapping(uint256 => string) internal _tokenURIs;
// Royalty configurations
mapping(address => address payable[]) internal _extensionRoyaltyReceivers;
mapping(address => uint256[]) internal _extensionRoyaltyBPS;
mapping(uint256 => address payable[]) internal _tokenRoyaltyReceivers;
mapping(uint256 => uint256[]) internal _tokenRoyaltyBPS;
/**
* External interface identifiers for royalties
*/
/**
* @dev CreatorCore
*
* bytes4(keccak256('getRoyalties(uint256)')) == 0xbb3bafd6
*
* => 0xbb3bafd6 = 0xbb3bafd6
*/
bytes4 private constant _INTERFACE_ID_ROYALTIES_CREATORCORE = 0xbb3bafd6;
/**
* @dev Rarible: RoyaltiesV1
*
* bytes4(keccak256('getFeeRecipients(uint256)')) == 0xb9c4d9fb
* bytes4(keccak256('getFeeBps(uint256)')) == 0x0ebd4c7f
*
* => 0xb9c4d9fb ^ 0x0ebd4c7f = 0xb7799584
*/
bytes4 private constant _INTERFACE_ID_ROYALTIES_RARIBLE = 0xb7799584;
/**
* @dev Foundation
*
* bytes4(keccak256('getFees(uint256)')) == 0xd5a06d4c
*
* => 0xd5a06d4c = 0xd5a06d4c
*/
bytes4 private constant _INTERFACE_ID_ROYALTIES_FOUNDATION = 0xd5a06d4c;
/**
* @dev EIP-2981
*
* bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a
*
* => 0x2a55205a = 0x2a55205a
*/
bytes4 private constant _INTERFACE_ID_ROYALTIES_EIP2981 = 0x2a55205a;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(ICreatorCore).interfaceId ||
super.supportsInterface(interfaceId) ||
interfaceId == _INTERFACE_ID_ROYALTIES_CREATORCORE ||
interfaceId == _INTERFACE_ID_ROYALTIES_RARIBLE ||
interfaceId == _INTERFACE_ID_ROYALTIES_FOUNDATION ||
interfaceId == _INTERFACE_ID_ROYALTIES_EIP2981;
}
/**
* @dev Only allows registered extensions to call the specified function
*/
modifier extensionRequired() {
require(
_extensions.contains(msg.sender),
"Must be registered extension"
);
_;
}
/**
* @dev Only allows non-blacklisted extensions
*/
modifier nonBlacklistRequired(address extension) {
require(
!_blacklistedExtensions.contains(extension),
"Extension blacklisted"
);
_;
}
/**
* @dev See {ICreatorCore-getExtensions}.
*/
function getExtensions()
external
view
override
returns (address[] memory extensions)
{
extensions = new address[](_extensions.length());
for (uint256 i = 0; i < _extensions.length(); i++) {
extensions[i] = _extensions.at(i);
}
return extensions;
}
/**
* @dev Register an extension
*/
function _registerExtension(
address extension,
string calldata baseURI,
bool baseURIIdentical
) internal {
require(extension != address(this), "Creator: Invalid");
require(
extension.isContract(),
"Creator: Extension must be a contract"
);
if (!_extensions.contains(extension)) {
_extensionBaseURI[extension] = baseURI;
_extensionBaseURIIdentical[extension] = baseURIIdentical;
emit ExtensionRegistered(extension, msg.sender);
_extensions.add(extension);
}
}
/**
* @dev Unregister an extension
*/
function _unregisterExtension(address extension) internal {
if (_extensions.contains(extension)) {
emit ExtensionUnregistered(extension, msg.sender);
_extensions.remove(extension);
}
}
/**
* @dev Blacklist an extension
*/
function _blacklistExtension(address extension) internal {
require(extension != address(this), "Cannot blacklist yourself");
if (_extensions.contains(extension)) {
emit ExtensionUnregistered(extension, msg.sender);
_extensions.remove(extension);
}
if (!_blacklistedExtensions.contains(extension)) {
emit ExtensionBlacklisted(extension, msg.sender);
_blacklistedExtensions.add(extension);
}
}
/**
* @dev Set base token uri for an extension
*/
function _setBaseTokenURIExtension(string calldata uri, bool identical)
internal
{
_extensionBaseURI[msg.sender] = uri;
_extensionBaseURIIdentical[msg.sender] = identical;
}
/**
* @dev Set token uri prefix for an extension
*/
function _setTokenURIPrefixExtension(string calldata prefix) internal {
_extensionURIPrefix[msg.sender] = prefix;
}
/**
* @dev Set token uri for a token of an extension
*/
function _setTokenURIExtension(uint256 tokenId, string calldata uri)
internal
{
require(_tokensExtension[tokenId] == msg.sender, "Invalid token");
_tokenURIs[tokenId] = uri;
}
/**
* @dev Set base token uri for tokens with no extension
*/
function _setBaseTokenURI(string memory uri) internal {
_extensionBaseURI[address(this)] = uri;
}
/**
* @dev Set token uri prefix for tokens with no extension
*/
function _setTokenURIPrefix(string calldata prefix) internal {
_extensionURIPrefix[address(this)] = prefix;
}
/**
* @dev Set token uri for a token with no extension
*/
function _setTokenURI(uint256 tokenId, string calldata uri) internal {
require(_tokensExtension[tokenId] == address(this), "Invalid token");
_tokenURIs[tokenId] = uri;
}
/**
* @dev Retrieve a token's URI
*/
function _tokenURI(uint256 tokenId) internal view returns (string memory) {
address extension = _tokensExtension[tokenId];
require(
!_blacklistedExtensions.contains(extension),
"Extension blacklisted"
);
if (bytes(_tokenURIs[tokenId]).length != 0) {
if (bytes(_extensionURIPrefix[extension]).length != 0) {
return
string(
abi.encodePacked(
_extensionURIPrefix[extension],
_tokenURIs[tokenId]
)
);
}
return _tokenURIs[tokenId];
}
if (
ERC165Checker.supportsInterface(
extension,
type(ICreatorExtensionTokenURI).interfaceId
)
) {
return
ICreatorExtensionTokenURI(extension).tokenURI(
address(this),
tokenId
);
}
if (!_extensionBaseURIIdentical[extension]) {
return
string(
abi.encodePacked(
_extensionBaseURI[extension],
tokenId.toString()
)
);
} else {
return _extensionBaseURI[extension];
}
}
/**
* Get token extension
*/
function _tokenExtension(uint256 tokenId)
internal
view
returns (address extension)
{
extension = _tokensExtension[tokenId];
require(extension != address(this), "No extension for token");
require(
!_blacklistedExtensions.contains(extension),
"Extension blacklisted"
);
return extension;
}
/**
* Helper to get royalties for a token
*/
function _getRoyalties(uint256 tokenId)
internal
view
returns (address payable[] storage, uint256[] storage)
{
return (_getRoyaltyReceivers(tokenId), _getRoyaltyBPS(tokenId));
}
/**
* Helper to get royalty receivers for a token
*/
function _getRoyaltyReceivers(uint256 tokenId)
internal
view
returns (address payable[] storage)
{
if (_tokenRoyaltyReceivers[tokenId].length > 0) {
return _tokenRoyaltyReceivers[tokenId];
} else if (
_extensionRoyaltyReceivers[_tokensExtension[tokenId]].length > 0
) {
return _extensionRoyaltyReceivers[_tokensExtension[tokenId]];
}
return _extensionRoyaltyReceivers[address(this)];
}
/**
* Helper to get royalty basis points for a token
*/
function _getRoyaltyBPS(uint256 tokenId)
internal
view
returns (uint256[] storage)
{
if (_tokenRoyaltyBPS[tokenId].length > 0) {
return _tokenRoyaltyBPS[tokenId];
} else if (_extensionRoyaltyBPS[_tokensExtension[tokenId]].length > 0) {
return _extensionRoyaltyBPS[_tokensExtension[tokenId]];
}
return _extensionRoyaltyBPS[address(this)];
}
function _getRoyaltyInfo(uint256 tokenId, uint256 value)
internal
view
returns (address receiver, uint256 amount)
{
address payable[] storage receivers = _getRoyaltyReceivers(tokenId);
require(receivers.length <= 1, "More than 1 royalty receiver");
if (receivers.length == 0) {
return (address(this), 0);
}
return (receivers[0], (_getRoyaltyBPS(tokenId)[0] * value) / 10000);
}
/**
* Set royalties for a token
*/
function _setRoyalties(
uint256 tokenId,
address payable[] calldata receivers,
uint256[] calldata basisPoints
) internal {
require(receivers.length == basisPoints.length, "Invalid input");
uint256 totalBasisPoints;
for (uint256 i = 0; i < basisPoints.length; i++) {
totalBasisPoints += basisPoints[i];
}
require(totalBasisPoints < 10000, "Invalid total royalties");
_tokenRoyaltyReceivers[tokenId] = receivers;
_tokenRoyaltyBPS[tokenId] = basisPoints;
emit RoyaltiesUpdated(tokenId, receivers, basisPoints);
}
/**
* Set royalties for all tokens of an extension
*/
function _setRoyaltiesExtension(
address extension,
address payable[] calldata receivers,
uint256[] calldata basisPoints
) internal {
require(receivers.length == basisPoints.length, "Invalid input");
uint256 totalBasisPoints;
for (uint256 i = 0; i < basisPoints.length; i++) {
totalBasisPoints += basisPoints[i];
}
require(totalBasisPoints < 10000, "Invalid total royalties");
_extensionRoyaltyReceivers[extension] = receivers;
_extensionRoyaltyBPS[extension] = basisPoints;
if (extension == address(this)) {
emit DefaultRoyaltiesUpdated(receivers, basisPoints);
} else {
emit ExtensionRoyaltiesUpdated(extension, receivers, basisPoints);
}
}
}
// 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
// OpenZeppelin Contracts v4.4.0 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165Checker.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Library used to query support of an interface declared via {IERC165}.
*
* Note that these functions return the actual result of the query: they do not
* `revert` if an interface is not supported. It is up to the caller to decide
* what to do in these cases.
*/
library ERC165Checker {
// As per the EIP-165 spec, no interface should ever match 0xffffffff
bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
/**
* @dev Returns true if `account` supports the {IERC165} interface,
*/
function supportsERC165(address account) internal view returns (bool) {
// Any contract that implements ERC165 must explicitly indicate support of
// InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
return
_supportsERC165Interface(account, type(IERC165).interfaceId) &&
!_supportsERC165Interface(account, _INTERFACE_ID_INVALID);
}
/**
* @dev Returns true if `account` supports the interface defined by
* `interfaceId`. Support for {IERC165} itself is queried automatically.
*
* See {IERC165-supportsInterface}.
*/
function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
// query support of both ERC165 as per the spec and support of _interfaceId
return supportsERC165(account) && _supportsERC165Interface(account, interfaceId);
}
/**
* @dev Returns a boolean array where each value corresponds to the
* interfaces passed in and whether they're supported or not. This allows
* you to batch check interfaces for a contract where your expectation
* is that some interfaces may not be supported.
*
* See {IERC165-supportsInterface}.
*
* _Available since v3.4._
*/
function getSupportedInterfaces(address account, bytes4[] memory interfaceIds)
internal
view
returns (bool[] memory)
{
// an array of booleans corresponding to interfaceIds and whether they're supported or not
bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);
// query support of ERC165 itself
if (supportsERC165(account)) {
// query support of each interface in interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]);
}
}
return interfaceIdsSupported;
}
/**
* @dev Returns true if `account` supports all the interfaces defined in
* `interfaceIds`. Support for {IERC165} itself is queried automatically.
*
* Batch-querying can lead to gas savings by skipping repeated checks for
* {IERC165} support.
*
* See {IERC165-supportsInterface}.
*/
function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
// query support of ERC165 itself
if (!supportsERC165(account)) {
return false;
}
// query support of each interface in _interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
if (!_supportsERC165Interface(account, interfaceIds[i])) {
return false;
}
}
// all interfaces supported
return true;
}
/**
* @notice Query if a contract implements an interface, does not check ERC165 support
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return true if the contract at account indicates support of the interface with
* identifier interfaceId, false otherwise
* @dev Assumes that account contains a contract that supports ERC165, otherwise
* the behavior of this method is undefined. This precondition can be checked
* with {supportsERC165}.
* Interface identification is specified in ERC-165.
*/
function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) {
bytes memory encodedParams = abi.encodeWithSelector(IERC165.supportsInterface.selector, interfaceId);
(bool success, bytes memory result) = account.staticcall{gas: 30000}(encodedParams);
if (result.length < 32) return false;
return success && abi.decode(result, (bool));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "../../../openzeppelin/utils/introspection/IERC165.sol";
/**
* @dev Implement this if you want your extension to have overloadable URI's
*/
interface ICreatorExtensionTokenURI is IERC165 {
/**
* Get the uri for a given creator/tokenId
*/
function tokenURI(address creator, uint256 tokenId)
external
view
returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "../../../openzeppelin/utils/introspection/IERC165.sol";
/**
* @dev Core creator interface
*/
interface ICreatorCore is IERC165 {
event ExtensionRegistered(
address indexed extension,
address indexed sender
);
event ExtensionUnregistered(
address indexed extension,
address indexed sender
);
event ExtensionBlacklisted(
address indexed extension,
address indexed sender
);
event MintPermissionsUpdated(
address indexed extension,
address indexed permissions,
address indexed sender
);
event RoyaltiesUpdated(
uint256 indexed tokenId,
address payable[] receivers,
uint256[] basisPoints
);
event DefaultRoyaltiesUpdated(
address payable[] receivers,
uint256[] basisPoints
);
event ExtensionRoyaltiesUpdated(
address indexed extension,
address payable[] receivers,
uint256[] basisPoints
);
event ExtensionApproveTransferUpdated(
address indexed extension,
bool enabled
);
/**
* @dev gets address of all extensions
*/
function getExtensions() external view returns (address[] memory);
/**
* @dev add an extension. Can only be called by contract owner or admin.
* extension address must point to a contract implementing ICreatorExtension.
* Returns True if newly added, False if already added.
*/
function registerExtension(address extension, string calldata baseURI)
external;
/**
* @dev add an extension. Can only be called by contract owner or admin.
* extension address must point to a contract implementing ICreatorExtension.
* Returns True if newly added, False if already added.
*/
function registerExtension(
address extension,
string calldata baseURI,
bool baseURIIdentical
) external;
/**
* @dev add an extension. Can only be called by contract owner or admin.
* Returns True if removed, False if already removed.
*/
function unregisterExtension(address extension) external;
/**
* @dev blacklist an extension. Can only be called by contract owner or admin.
* This function will destroy all ability to reference the metadata of any tokens created
* by the specified extension. It will also unregister the extension if needed.
* Returns True if removed, False if already removed.
*/
function blacklistExtension(address extension) external;
/**
* @dev set the baseTokenURI of an extension. Can only be called by extension.
*/
function setBaseTokenURIExtension(string calldata uri) external;
/**
* @dev set the baseTokenURI of an extension. Can only be called by extension.
* For tokens with no uri configured, tokenURI will return "uri+tokenId"
*/
function setBaseTokenURIExtension(string calldata uri, bool identical)
external;
/**
* @dev set the common prefix of an extension. Can only be called by extension.
* If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI"
* Useful if you want to use ipfs/arweave
*/
function setTokenURIPrefixExtension(string calldata prefix) external;
/**
* @dev set the tokenURI of a token extension. Can only be called by extension that minted token.
*/
function setTokenURIExtension(uint256 tokenId, string calldata uri)
external;
/**
* @dev set the tokenURI of a token extension for multiple tokens. Can only be called by extension that minted token.
*/
function setTokenURIExtension(
uint256[] memory tokenId,
string[] calldata uri
) external;
/**
* @dev set the baseTokenURI for tokens with no extension. Can only be called by owner/admin.
* For tokens with no uri configured, tokenURI will return "uri+tokenId"
*/
function setBaseTokenURI(string calldata uri) external;
/**
* @dev set the common prefix for tokens with no extension. Can only be called by owner/admin.
* If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI"
* Useful if you want to use ipfs/arweave
*/
function setTokenURIPrefix(string calldata prefix) external;
/**
* @dev set the tokenURI of a token with no extension. Can only be called by owner/admin.
*/
function setTokenURI(uint256 tokenId, string calldata uri) external;
/**
* @dev set the tokenURI of multiple tokens with no extension. Can only be called by owner/admin.
*/
function setTokenURI(uint256[] memory tokenIds, string[] calldata uris)
external;
/**
* @dev set a permissions contract for an extension. Used to control minting.
*/
function setMintPermissions(address extension, address permissions)
external;
/**
* @dev Configure so transfers of tokens created by the caller (must be extension) gets approval
* from the extension before transferring
*/
function setApproveTransferExtension(bool enabled) external;
/**
* @dev get the extension of a given token
*/
function tokenExtension(uint256 tokenId) external view returns (address);
/**
* @dev Set default royalties
*/
function setRoyalties(
address payable[] calldata receivers,
uint256[] calldata basisPoints
) external;
/**
* @dev Set royalties of a token
*/
function setRoyalties(
uint256 tokenId,
address payable[] calldata receivers,
uint256[] calldata basisPoints
) external;
/**
* @dev Set royalties of an extension
*/
function setRoyaltiesExtension(
address extension,
address payable[] calldata receivers,
uint256[] calldata basisPoints
) external;
/**
* @dev Get royalites of a token. Returns list of receivers and basisPoints
*/
function getRoyalties(uint256 tokenId)
external
view
returns (address payable[] memory, uint256[] memory);
// Royalty support for various other standards
function getFeeRecipients(uint256 tokenId)
external
view
returns (address payable[] memory);
function getFeeBps(uint256 tokenId)
external
view
returns (uint256[] memory);
function getFees(uint256 tokenId)
external
view
returns (address payable[] memory, uint256[] memory);
function royaltyInfo(uint256 tokenId, uint256 value)
external
view
returns (address, uint256);
} | See {IERC1155CreatorCore-mintBaseExisting}./ | function mintBaseExisting(
address[] calldata to,
uint256[] calldata tokenIds,
uint256[] calldata amounts
) public virtual override nonReentrant adminRequired {
for (uint256 i = 0; i < tokenIds.length; i++) {
require(
_tokensExtension[tokenIds[i]] == address(this),
"A token was created by an extension"
);
}
_mintExisting(address(this), to, tokenIds, amounts);
}
| 11,819,363 |
// File: contracts/src/common/lifecycle/Killable.sol
pragma solidity ^0.5.0;
/**
* A module that allows contracts to self-destruct.
*/
contract Killable {
address payable public _owner;
/**
* Initialized with the deployer as the owner.
*/
constructor() internal {
_owner = msg.sender;
}
/**
* Self-destruct the contract.
* This function can only be executed by the owner.
*/
function kill() public {
require(msg.sender == _owner, "only owner method");
selfdestruct(_owner);
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/ownership/Ownable.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
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/src/common/interface/IGroup.sol
pragma solidity ^0.5.0;
contract IGroup {
function isGroup(address _addr) public view returns (bool);
function addGroup(address _addr) external;
function getGroupKey(address _addr) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("_group", _addr));
}
}
// File: contracts/src/common/validate/AddressValidator.sol
pragma solidity ^0.5.0;
/**
* A module that provides common validations patterns.
*/
contract AddressValidator {
string constant errorMessage = "this is illegal address";
/**
* Validates passed address is not a zero address.
*/
function validateIllegalAddress(address _addr) external pure {
require(_addr != address(0), errorMessage);
}
/**
* Validates passed address is included in an address set.
*/
function validateGroup(address _addr, address _groupAddr) external view {
require(IGroup(_groupAddr).isGroup(_addr), errorMessage);
}
/**
* Validates passed address is included in two address sets.
*/
function validateGroups(
address _addr,
address _groupAddr1,
address _groupAddr2
) external view {
if (IGroup(_groupAddr1).isGroup(_addr)) {
return;
}
require(IGroup(_groupAddr2).isGroup(_addr), errorMessage);
}
/**
* Validates that the address of the first argument is equal to the address of the second argument.
*/
function validateAddress(address _addr, address _target) external pure {
require(_addr == _target, errorMessage);
}
/**
* Validates passed address equals to the two addresses.
*/
function validateAddresses(
address _addr,
address _target1,
address _target2
) external pure {
if (_addr == _target1) {
return;
}
require(_addr == _target2, errorMessage);
}
/**
* Validates passed address equals to the three addresses.
*/
function validate3Addresses(
address _addr,
address _target1,
address _target2,
address _target3
) external pure {
if (_addr == _target1) {
return;
}
if (_addr == _target2) {
return;
}
require(_addr == _target3, errorMessage);
}
}
// File: contracts/src/common/validate/UsingValidator.sol
pragma solidity ^0.5.0;
// prettier-ignore
/**
* Module for contrast handling AddressValidator.
*/
contract UsingValidator {
AddressValidator private _validator;
/**
* Create a new AddressValidator contract when initialize.
*/
constructor() public {
_validator = new AddressValidator();
}
/**
* Returns the set AddressValidator address.
*/
function addressValidator() internal view returns (AddressValidator) {
return _validator;
}
}
// File: contracts/src/common/config/AddressConfig.sol
pragma solidity ^0.5.0;
/**
* A registry contract to hold the latest contract addresses.
* Dev Protocol will be upgradeable by this contract.
*/
contract AddressConfig is Ownable, UsingValidator, Killable {
address public token = 0x98626E2C9231f03504273d55f397409deFD4a093;
address public allocator;
address public allocatorStorage;
address public withdraw;
address public withdrawStorage;
address public marketFactory;
address public marketGroup;
address public propertyFactory;
address public propertyGroup;
address public metricsGroup;
address public metricsFactory;
address public policy;
address public policyFactory;
address public policySet;
address public policyGroup;
address public lockup;
address public lockupStorage;
address public voteTimes;
address public voteTimesStorage;
address public voteCounter;
address public voteCounterStorage;
/**
* Set the latest Allocator contract address.
* Only the owner can execute this function.
*/
function setAllocator(address _addr) external onlyOwner {
allocator = _addr;
}
/**
* Set the latest AllocatorStorage contract address.
* Only the owner can execute this function.
* NOTE: But currently, the AllocatorStorage contract is not used.
*/
function setAllocatorStorage(address _addr) external onlyOwner {
allocatorStorage = _addr;
}
/**
* Set the latest Withdraw contract address.
* Only the owner can execute this function.
*/
function setWithdraw(address _addr) external onlyOwner {
withdraw = _addr;
}
/**
* Set the latest WithdrawStorage contract address.
* Only the owner can execute this function.
*/
function setWithdrawStorage(address _addr) external onlyOwner {
withdrawStorage = _addr;
}
/**
* Set the latest MarketFactory contract address.
* Only the owner can execute this function.
*/
function setMarketFactory(address _addr) external onlyOwner {
marketFactory = _addr;
}
/**
* Set the latest MarketGroup contract address.
* Only the owner can execute this function.
*/
function setMarketGroup(address _addr) external onlyOwner {
marketGroup = _addr;
}
/**
* Set the latest PropertyFactory contract address.
* Only the owner can execute this function.
*/
function setPropertyFactory(address _addr) external onlyOwner {
propertyFactory = _addr;
}
/**
* Set the latest PropertyGroup contract address.
* Only the owner can execute this function.
*/
function setPropertyGroup(address _addr) external onlyOwner {
propertyGroup = _addr;
}
/**
* Set the latest MetricsFactory contract address.
* Only the owner can execute this function.
*/
function setMetricsFactory(address _addr) external onlyOwner {
metricsFactory = _addr;
}
/**
* Set the latest MetricsGroup contract address.
* Only the owner can execute this function.
*/
function setMetricsGroup(address _addr) external onlyOwner {
metricsGroup = _addr;
}
/**
* Set the latest PolicyFactory contract address.
* Only the owner can execute this function.
*/
function setPolicyFactory(address _addr) external onlyOwner {
policyFactory = _addr;
}
/**
* Set the latest PolicyGroup contract address.
* Only the owner can execute this function.
*/
function setPolicyGroup(address _addr) external onlyOwner {
policyGroup = _addr;
}
/**
* Set the latest PolicySet contract address.
* Only the owner can execute this function.
*/
function setPolicySet(address _addr) external onlyOwner {
policySet = _addr;
}
/**
* Set the latest Policy contract address.
* Only the latest PolicyFactory contract can execute this function.
*/
function setPolicy(address _addr) external {
addressValidator().validateAddress(msg.sender, policyFactory);
policy = _addr;
}
/**
* Set the latest Dev contract address.
* Only the owner can execute this function.
*/
function setToken(address _addr) external onlyOwner {
token = _addr;
}
/**
* Set the latest Lockup contract address.
* Only the owner can execute this function.
*/
function setLockup(address _addr) external onlyOwner {
lockup = _addr;
}
/**
* Set the latest LockupStorage contract address.
* Only the owner can execute this function.
* NOTE: But currently, the LockupStorage contract is not used as a stand-alone because it is inherited from the Lockup contract.
*/
function setLockupStorage(address _addr) external onlyOwner {
lockupStorage = _addr;
}
/**
* Set the latest VoteTimes contract address.
* Only the owner can execute this function.
* NOTE: But currently, the VoteTimes contract is not used.
*/
function setVoteTimes(address _addr) external onlyOwner {
voteTimes = _addr;
}
/**
* Set the latest VoteTimesStorage contract address.
* Only the owner can execute this function.
* NOTE: But currently, the VoteTimesStorage contract is not used.
*/
function setVoteTimesStorage(address _addr) external onlyOwner {
voteTimesStorage = _addr;
}
/**
* Set the latest VoteCounter contract address.
* Only the owner can execute this function.
*/
function setVoteCounter(address _addr) external onlyOwner {
voteCounter = _addr;
}
/**
* Set the latest VoteCounterStorage contract address.
* Only the owner can execute this function.
* NOTE: But currently, the VoteCounterStorage contract is not used as a stand-alone because it is inherited from the VoteCounter contract.
*/
function setVoteCounterStorage(address _addr) external onlyOwner {
voteCounterStorage = _addr;
}
}
// File: contracts/src/common/config/UsingConfig.sol
pragma solidity ^0.5.0;
/**
* Module for using AddressConfig contracts.
*/
contract UsingConfig {
AddressConfig private _config;
/**
* Initialize the argument as AddressConfig address.
*/
constructor(address _addressConfig) public {
_config = AddressConfig(_addressConfig);
}
/**
* Returns the latest AddressConfig instance.
*/
function config() internal view returns (AddressConfig) {
return _config;
}
/**
* Returns the latest AddressConfig address.
*/
function configAddress() external view returns (address) {
return address(_config);
}
}
// File: contracts/src/market/IMarketFactory.sol
pragma solidity ^0.5.0;
contract IMarketFactory {
function create(address _addr) external returns (address);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/src/property/IProperty.sol
pragma solidity ^0.5.0;
contract IProperty {
function author() external view returns (address);
function withdraw(address _sender, uint256 _value) external;
}
// File: contracts/src/market/IMarket.sol
pragma solidity ^0.5.0;
interface IMarket {
function authenticate(
address _prop,
string calldata _args1,
string calldata _args2,
string calldata _args3,
string calldata _args4,
string calldata _args5
)
external
returns (
// solium-disable-next-line indentation
bool
);
function authenticatedCallback(address _property, bytes32 _idHash)
external
returns (address);
function deauthenticate(address _metrics) external;
function schema() external view returns (string memory);
function behavior() external view returns (address);
function enabled() external view returns (bool);
function votingEndBlockNumber() external view returns (uint256);
function toEnable() external;
}
// File: contracts/src/market/IMarketBehavior.sol
pragma solidity ^0.5.0;
interface IMarketBehavior {
function authenticate(
address _prop,
string calldata _args1,
string calldata _args2,
string calldata _args3,
string calldata _args4,
string calldata _args5,
address market,
address account
)
external
returns (
// solium-disable-next-line indentation
bool
);
function schema() external view returns (string memory);
function getId(address _metrics) external view returns (string memory);
function getMetrics(string calldata _id) external view returns (address);
}
// File: contracts/src/policy/IPolicy.sol
pragma solidity ^0.5.0;
contract IPolicy {
function rewards(uint256 _lockups, uint256 _assets)
external
view
returns (uint256);
function holdersShare(uint256 _amount, uint256 _lockups)
external
view
returns (uint256);
function assetValue(uint256 _value, uint256 _lockups)
external
view
returns (uint256);
function authenticationFee(uint256 _assets, uint256 _propertyAssets)
external
view
returns (uint256);
function marketApproval(uint256 _agree, uint256 _opposite)
external
view
returns (bool);
function policyApproval(uint256 _agree, uint256 _opposite)
external
view
returns (bool);
function marketVotingBlocks() external view returns (uint256);
function policyVotingBlocks() external view returns (uint256);
function abstentionPenalty(uint256 _count) external view returns (uint256);
function lockUpBlocks() external view returns (uint256);
}
// File: contracts/src/metrics/IMetrics.sol
pragma solidity ^0.5.0;
contract IMetrics {
address public market;
address public property;
}
// File: contracts/src/metrics/Metrics.sol
pragma solidity ^0.5.0;
/**
* A contract for associating a Property and an asset authenticated by a Market.
*/
contract Metrics is IMetrics {
address public market;
address public property;
constructor(address _market, address _property) public {
//Do not validate because there is no AddressConfig
market = _market;
property = _property;
}
}
// File: contracts/src/metrics/IMetricsFactory.sol
pragma solidity ^0.5.0;
contract IMetricsFactory {
function create(address _property) external returns (address);
function destroy(address _metrics) external;
}
// File: contracts/src/metrics/IMetricsGroup.sol
pragma solidity ^0.5.0;
contract IMetricsGroup is IGroup {
function removeGroup(address _addr) external;
function totalIssuedMetrics() external view returns (uint256);
function getMetricsCountPerProperty(address _property)
public
view
returns (uint256);
function hasAssets(address _property) public view returns (bool);
}
// File: contracts/src/lockup/ILockup.sol
pragma solidity ^0.5.0;
contract ILockup {
function lockup(
address _from,
address _property,
uint256 _value
// solium-disable-next-line indentation
) external;
function update() public;
function cancel(address _property) external;
function withdraw(address _property) external;
function difference(address _property, uint256 _lastReward)
public
view
returns (
uint256 _reward,
uint256 _holdersAmount,
uint256 _holdersPrice,
uint256 _interestAmount,
uint256 _interestPrice
);
function getPropertyValue(address _property)
external
view
returns (uint256);
function getAllValue() external view returns (uint256);
function getValue(address _property, address _sender)
external
view
returns (uint256);
function calculateWithdrawableInterestAmount(
address _property,
address _user
)
public
view
returns (
// solium-disable-next-line indentation
uint256
);
function withdrawInterest(address _property) external;
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount)
external
returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender)
external
view
returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: @openzeppelin/contracts/token/ERC20/ERC20Detailed.sol
pragma solidity ^0.5.0;
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor(
string memory name,
string memory symbol,
uint8 decimals
) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @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.
*
* 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;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
view
returns (uint256)
{
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue)
public
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(addedValue)
);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
"ERC20: decreased allowance below zero"
)
);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(
amount,
"ERC20: transfer amount exceeds balance"
);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(
amount,
"ERC20: burn amount exceeds balance"
);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(
account,
_msgSender(),
_allowances[account][_msgSender()].sub(
amount,
"ERC20: burn amount exceeds allowance"
)
);
}
}
// File: @openzeppelin/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: @openzeppelin/contracts/access/roles/MinterRole.sol
pragma solidity ^0.5.0;
contract MinterRole is Context {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor() internal {
_addMinter(_msgSender());
}
modifier onlyMinter() {
require(
isMinter(_msgSender()),
"MinterRole: caller does not have the Minter role"
);
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(_msgSender());
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
// File: @openzeppelin/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/contracts/token/ERC20/ERC20Burnable.sol
pragma solidity ^0.5.0;
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public {
_burn(_msgSender(), amount);
}
/**
* @dev See {ERC20-_burnFrom}.
*/
function burnFrom(address account, uint256 amount) public {
_burnFrom(account, amount);
}
}
// File: contracts/src/common/libs/Decimals.sol
pragma solidity ^0.5.0;
/**
* Library for emulating calculations involving decimals.
*/
library Decimals {
using SafeMath for uint256;
uint120 private constant basisValue = 1000000000000000000;
/**
* Returns the ratio of the first argument to the second argument.
*/
function outOf(uint256 _a, uint256 _b)
internal
pure
returns (uint256 result)
{
if (_a == 0) {
return 0;
}
uint256 a = _a.mul(basisValue);
if (a < _b) {
return 0;
}
return (a.div(_b));
}
/**
* Returns multiplied the number by 10^18.
* This is used when there is a very large difference between the two numbers passed to the `outOf` function.
*/
function mulBasis(uint256 _a) internal pure returns (uint256) {
return _a.mul(basisValue);
}
/**
* Returns by changing the numerical value being emulated to the original number of digits.
*/
function divBasis(uint256 _a) internal pure returns (uint256) {
return _a.div(basisValue);
}
}
// File: contracts/src/common/storage/EternalStorage.sol
pragma solidity ^0.5.0;
/**
* Module for persisting states.
* Stores a map for `uint256`, `string`, `address`, `bytes32`, `bool`, and `int256` type with `bytes32` type as a key.
*/
contract EternalStorage {
address private currentOwner = msg.sender;
mapping(bytes32 => uint256) private uIntStorage;
mapping(bytes32 => string) private stringStorage;
mapping(bytes32 => address) private addressStorage;
mapping(bytes32 => bytes32) private bytesStorage;
mapping(bytes32 => bool) private boolStorage;
mapping(bytes32 => int256) private intStorage;
/**
* Modifiers to validate that only the owner can execute.
*/
modifier onlyCurrentOwner() {
require(msg.sender == currentOwner, "not current owner");
_;
}
/**
* Transfer the owner.
* Only the owner can execute this function.
*/
function changeOwner(address _newOwner) external {
require(msg.sender == currentOwner, "not current owner");
currentOwner = _newOwner;
}
// *** Getter Methods ***
/**
* Returns the value of the `uint256` type that mapped to the given key.
*/
function getUint(bytes32 _key) external view returns (uint256) {
return uIntStorage[_key];
}
/**
* Returns the value of the `string` type that mapped to the given key.
*/
function getString(bytes32 _key) external view returns (string memory) {
return stringStorage[_key];
}
/**
* Returns the value of the `address` type that mapped to the given key.
*/
function getAddress(bytes32 _key) external view returns (address) {
return addressStorage[_key];
}
/**
* Returns the value of the `bytes32` type that mapped to the given key.
*/
function getBytes(bytes32 _key) external view returns (bytes32) {
return bytesStorage[_key];
}
/**
* Returns the value of the `bool` type that mapped to the given key.
*/
function getBool(bytes32 _key) external view returns (bool) {
return boolStorage[_key];
}
/**
* Returns the value of the `int256` type that mapped to the given key.
*/
function getInt(bytes32 _key) external view returns (int256) {
return intStorage[_key];
}
// *** Setter Methods ***
/**
* Maps a value of `uint256` type to a given key.
* Only the owner can execute this function.
*/
function setUint(bytes32 _key, uint256 _value) external onlyCurrentOwner {
uIntStorage[_key] = _value;
}
/**
* Maps a value of `string` type to a given key.
* Only the owner can execute this function.
*/
function setString(bytes32 _key, string calldata _value)
external
onlyCurrentOwner
{
stringStorage[_key] = _value;
}
/**
* Maps a value of `address` type to a given key.
* Only the owner can execute this function.
*/
function setAddress(bytes32 _key, address _value)
external
onlyCurrentOwner
{
addressStorage[_key] = _value;
}
/**
* Maps a value of `bytes32` type to a given key.
* Only the owner can execute this function.
*/
function setBytes(bytes32 _key, bytes32 _value) external onlyCurrentOwner {
bytesStorage[_key] = _value;
}
/**
* Maps a value of `bool` type to a given key.
* Only the owner can execute this function.
*/
function setBool(bytes32 _key, bool _value) external onlyCurrentOwner {
boolStorage[_key] = _value;
}
/**
* Maps a value of `int256` type to a given key.
* Only the owner can execute this function.
*/
function setInt(bytes32 _key, int256 _value) external onlyCurrentOwner {
intStorage[_key] = _value;
}
// *** Delete Methods ***
/**
* Deletes the value of the `uint256` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteUint(bytes32 _key) external onlyCurrentOwner {
delete uIntStorage[_key];
}
/**
* Deletes the value of the `string` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteString(bytes32 _key) external onlyCurrentOwner {
delete stringStorage[_key];
}
/**
* Deletes the value of the `address` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteAddress(bytes32 _key) external onlyCurrentOwner {
delete addressStorage[_key];
}
/**
* Deletes the value of the `bytes32` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteBytes(bytes32 _key) external onlyCurrentOwner {
delete bytesStorage[_key];
}
/**
* Deletes the value of the `bool` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteBool(bytes32 _key) external onlyCurrentOwner {
delete boolStorage[_key];
}
/**
* Deletes the value of the `int256` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteInt(bytes32 _key) external onlyCurrentOwner {
delete intStorage[_key];
}
}
// File: contracts/src/common/storage/UsingStorage.sol
pragma solidity ^0.5.0;
/**
* Module for contrast handling EternalStorage.
*/
contract UsingStorage is Ownable {
address private _storage;
/**
* Modifier to verify that EternalStorage is set.
*/
modifier hasStorage() {
require(_storage != address(0), "storage is not set");
_;
}
/**
* Returns the set EternalStorage instance.
*/
function eternalStorage()
internal
view
hasStorage
returns (EternalStorage)
{
return EternalStorage(_storage);
}
/**
* Returns the set EternalStorage address.
*/
function getStorageAddress() external view hasStorage returns (address) {
return _storage;
}
/**
* Create a new EternalStorage contract.
* This function call will fail if the EternalStorage contract is already set.
* Also, only the owner can execute it.
*/
function createStorage() external onlyOwner {
require(_storage == address(0), "storage is set");
EternalStorage tmp = new EternalStorage();
_storage = address(tmp);
}
/**
* Assigns the EternalStorage contract that has already been created.
* Only the owner can execute this function.
*/
function setStorage(address _storageAddress) external onlyOwner {
_storage = _storageAddress;
}
/**
* Delegates the owner of the current EternalStorage contract.
* Only the owner can execute this function.
*/
function changeOwner(address newOwner) external onlyOwner {
EternalStorage(_storage).changeOwner(newOwner);
}
}
// File: contracts/src/lockup/LockupStorage.sol
pragma solidity ^0.5.0;
contract LockupStorage is UsingStorage {
using SafeMath for uint256;
uint256 public constant basis = 100000000000000000000000000000000;
//AllValue
function setStorageAllValue(uint256 _value) internal {
bytes32 key = getStorageAllValueKey();
eternalStorage().setUint(key, _value);
}
function getStorageAllValue() public view returns (uint256) {
bytes32 key = getStorageAllValueKey();
return eternalStorage().getUint(key);
}
function getStorageAllValueKey() private pure returns (bytes32) {
return keccak256(abi.encodePacked("_allValue"));
}
//Value
function setStorageValue(
address _property,
address _sender,
uint256 _value
) internal {
bytes32 key = getStorageValueKey(_property, _sender);
eternalStorage().setUint(key, _value);
}
function getStorageValue(address _property, address _sender)
public
view
returns (uint256)
{
bytes32 key = getStorageValueKey(_property, _sender);
return eternalStorage().getUint(key);
}
function getStorageValueKey(address _property, address _sender)
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_value", _property, _sender));
}
//PropertyValue
function setStoragePropertyValue(address _property, uint256 _value)
internal
{
bytes32 key = getStoragePropertyValueKey(_property);
eternalStorage().setUint(key, _value);
}
function getStoragePropertyValue(address _property)
public
view
returns (uint256)
{
bytes32 key = getStoragePropertyValueKey(_property);
return eternalStorage().getUint(key);
}
function getStoragePropertyValueKey(address _property)
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_propertyValue", _property));
}
//WithdrawalStatus
function setStorageWithdrawalStatus(
address _property,
address _from,
uint256 _value
) internal {
bytes32 key = getStorageWithdrawalStatusKey(_property, _from);
eternalStorage().setUint(key, _value);
}
function getStorageWithdrawalStatus(address _property, address _from)
public
view
returns (uint256)
{
bytes32 key = getStorageWithdrawalStatusKey(_property, _from);
return eternalStorage().getUint(key);
}
function getStorageWithdrawalStatusKey(address _property, address _sender)
private
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked("_withdrawalStatus", _property, _sender)
);
}
//InterestPrice
function setStorageInterestPrice(address _property, uint256 _value)
internal
{
// The previously used function
// This function is only used in testing
eternalStorage().setUint(getStorageInterestPriceKey(_property), _value);
}
function getStorageInterestPrice(address _property)
public
view
returns (uint256)
{
return eternalStorage().getUint(getStorageInterestPriceKey(_property));
}
function getStorageInterestPriceKey(address _property)
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_interestTotals", _property));
}
//LastInterestPrice
function setStorageLastInterestPrice(
address _property,
address _user,
uint256 _value
) internal {
eternalStorage().setUint(
getStorageLastInterestPriceKey(_property, _user),
_value
);
}
function getStorageLastInterestPrice(address _property, address _user)
public
view
returns (uint256)
{
return
eternalStorage().getUint(
getStorageLastInterestPriceKey(_property, _user)
);
}
function getStorageLastInterestPriceKey(address _property, address _user)
private
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked("_lastLastInterestPrice", _property, _user)
);
}
//LastSameRewardsAmountAndBlock
function setStorageLastSameRewardsAmountAndBlock(
uint256 _amount,
uint256 _block
) internal {
uint256 record = _amount.mul(basis).add(_block);
eternalStorage().setUint(
getStorageLastSameRewardsAmountAndBlockKey(),
record
);
}
function getStorageLastSameRewardsAmountAndBlock()
public
view
returns (uint256 _amount, uint256 _block)
{
uint256 record = eternalStorage().getUint(
getStorageLastSameRewardsAmountAndBlockKey()
);
uint256 amount = record.div(basis);
uint256 blockNumber = record.sub(amount.mul(basis));
return (amount, blockNumber);
}
function getStorageLastSameRewardsAmountAndBlockKey()
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_LastSameRewardsAmountAndBlock"));
}
//CumulativeGlobalRewards
function setStorageCumulativeGlobalRewards(uint256 _value) internal {
eternalStorage().setUint(
getStorageCumulativeGlobalRewardsKey(),
_value
);
}
function getStorageCumulativeGlobalRewards() public view returns (uint256) {
return eternalStorage().getUint(getStorageCumulativeGlobalRewardsKey());
}
function getStorageCumulativeGlobalRewardsKey()
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_cumulativeGlobalRewards"));
}
//LastCumulativeGlobalReward
function setStorageLastCumulativeGlobalReward(
address _property,
address _user,
uint256 _value
) internal {
eternalStorage().setUint(
getStorageLastCumulativeGlobalRewardKey(_property, _user),
_value
);
}
function getStorageLastCumulativeGlobalReward(
address _property,
address _user
) public view returns (uint256) {
return
eternalStorage().getUint(
getStorageLastCumulativeGlobalRewardKey(_property, _user)
);
}
function getStorageLastCumulativeGlobalRewardKey(
address _property,
address _user
) private pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
"_LastCumulativeGlobalReward",
_property,
_user
)
);
}
//LastCumulativePropertyInterest
function setStorageLastCumulativePropertyInterest(
address _property,
address _user,
uint256 _value
) internal {
eternalStorage().setUint(
getStorageLastCumulativePropertyInterestKey(_property, _user),
_value
);
}
function getStorageLastCumulativePropertyInterest(
address _property,
address _user
) public view returns (uint256) {
return
eternalStorage().getUint(
getStorageLastCumulativePropertyInterestKey(_property, _user)
);
}
function getStorageLastCumulativePropertyInterestKey(
address _property,
address _user
) private pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
"_lastCumulativePropertyInterest",
_property,
_user
)
);
}
//CumulativeLockedUpUnitAndBlock
function setStorageCumulativeLockedUpUnitAndBlock(
address _addr,
uint256 _unit,
uint256 _block
) internal {
uint256 record = _unit.mul(basis).add(_block);
eternalStorage().setUint(
getStorageCumulativeLockedUpUnitAndBlockKey(_addr),
record
);
}
function getStorageCumulativeLockedUpUnitAndBlock(address _addr)
public
view
returns (uint256 _unit, uint256 _block)
{
uint256 record = eternalStorage().getUint(
getStorageCumulativeLockedUpUnitAndBlockKey(_addr)
);
uint256 unit = record.div(basis);
uint256 blockNumber = record.sub(unit.mul(basis));
return (unit, blockNumber);
}
function getStorageCumulativeLockedUpUnitAndBlockKey(address _addr)
private
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked("_cumulativeLockedUpUnitAndBlock", _addr)
);
}
//CumulativeLockedUpValue
function setStorageCumulativeLockedUpValue(address _addr, uint256 _value)
internal
{
eternalStorage().setUint(
getStorageCumulativeLockedUpValueKey(_addr),
_value
);
}
function getStorageCumulativeLockedUpValue(address _addr)
public
view
returns (uint256)
{
return
eternalStorage().getUint(
getStorageCumulativeLockedUpValueKey(_addr)
);
}
function getStorageCumulativeLockedUpValueKey(address _addr)
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_cumulativeLockedUpValue", _addr));
}
//PendingWithdrawal
function setStoragePendingInterestWithdrawal(
address _property,
address _user,
uint256 _value
) internal {
eternalStorage().setUint(
getStoragePendingInterestWithdrawalKey(_property, _user),
_value
);
}
function getStoragePendingInterestWithdrawal(
address _property,
address _user
) public view returns (uint256) {
return
eternalStorage().getUint(
getStoragePendingInterestWithdrawalKey(_property, _user)
);
}
function getStoragePendingInterestWithdrawalKey(
address _property,
address _user
) private pure returns (bytes32) {
return
keccak256(
abi.encodePacked("_pendingInterestWithdrawal", _property, _user)
);
}
//DIP4GenesisBlock
function setStorageDIP4GenesisBlock(uint256 _block) internal {
eternalStorage().setUint(getStorageDIP4GenesisBlockKey(), _block);
}
function getStorageDIP4GenesisBlock() public view returns (uint256) {
return eternalStorage().getUint(getStorageDIP4GenesisBlockKey());
}
function getStorageDIP4GenesisBlockKey() private pure returns (bytes32) {
return keccak256(abi.encodePacked("_dip4GenesisBlock"));
}
//LastCumulativeLockedUpAndBlock
function setStorageLastCumulativeLockedUpAndBlock(
address _property,
address _user,
uint256 _cLocked,
uint256 _block
) internal {
uint256 record = _cLocked.mul(basis).add(_block);
eternalStorage().setUint(
getStorageLastCumulativeLockedUpAndBlockKey(_property, _user),
record
);
}
function getStorageLastCumulativeLockedUpAndBlock(
address _property,
address _user
) public view returns (uint256 _cLocked, uint256 _block) {
uint256 record = eternalStorage().getUint(
getStorageLastCumulativeLockedUpAndBlockKey(_property, _user)
);
uint256 cLocked = record.div(basis);
uint256 blockNumber = record.sub(cLocked.mul(basis));
return (cLocked, blockNumber);
}
function getStorageLastCumulativeLockedUpAndBlockKey(
address _property,
address _user
) private pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
"_lastCumulativeLockedUpAndBlock",
_property,
_user
)
);
}
}
// File: contracts/src/allocator/IAllocator.sol
pragma solidity ^0.5.0;
contract IAllocator {
function calculateMaxRewardsPerBlock() public view returns (uint256);
function beforeBalanceChange(
address _property,
address _from,
address _to
// solium-disable-next-line indentation
) external;
}
// File: contracts/src/lockup/Lockup.sol
pragma solidity ^0.5.0;
// prettier-ignore
/**
* A contract that manages the staking of DEV tokens and calculates rewards.
* Staking and the following mechanism determines that reward calculation.
*
* Variables:
* -`M`: Maximum mint amount per block determined by Allocator contract
* -`B`: Number of blocks during staking
* -`P`: Total number of staking locked up in a Property contract
* -`S`: Total number of staking locked up in all Property contracts
* -`U`: Number of staking per account locked up in a Property contract
*
* Formula:
* Staking Rewards = M * B * (P / S) * (U / P)
*
* Note:
* -`M`, `P` and `S` vary from block to block, and the variation cannot be predicted.
* -`B` is added every time the Ethereum block is created.
* - Only `U` and `B` are predictable variables.
* - As `M`, `P` and `S` cannot be observed from a staker, the "cumulative sum" is often used to calculate ratio variation with history.
* - Reward withdrawal always withdraws the total withdrawable amount.
*
* Scenario:
* - Assume `M` is fixed at 500
* - Alice stakes 100 DEV on Property-A (Alice's staking state on Property-A: `M`=500, `B`=0, `P`=100, `S`=100, `U`=100)
* - After 10 blocks, Bob stakes 60 DEV on Property-B (Alice's staking state on Property-A: `M`=500, `B`=10, `P`=100, `S`=160, `U`=100)
* - After 10 blocks, Carol stakes 40 DEV on Property-A (Alice's staking state on Property-A: `M`=500, `B`=20, `P`=140, `S`=200, `U`=100)
* - After 10 blocks, Alice withdraws Property-A staking reward. The reward at this time is 5000 DEV (10 blocks * 500 DEV) + 3125 DEV (10 blocks * 62.5% * 500 DEV) + 2500 DEV (10 blocks * 50% * 500 DEV).
*/
contract Lockup is ILockup, UsingConfig, UsingValidator, LockupStorage {
using SafeMath for uint256;
using Decimals for uint256;
event Lockedup(address _from, address _property, uint256 _value);
/**
* Initialize the passed address as AddressConfig address.
*/
// solium-disable-next-line no-empty-blocks
constructor(address _config) public UsingConfig(_config) {}
/**
* Adds staking.
* Only the Dev contract can execute this function.
*/
function lockup(
address _from,
address _property,
uint256 _value
) external {
/**
* Validates the sender is Dev contract.
*/
addressValidator().validateAddress(msg.sender, config().token());
/**
* Validates the target of staking is included Property set.
*/
addressValidator().validateGroup(_property, config().propertyGroup());
require(_value != 0, "illegal lockup value");
/**
* Validates the passed Property has greater than 1 asset.
*/
require(
IMetricsGroup(config().metricsGroup()).hasAssets(_property),
"unable to stake to unauthenticated property"
);
/**
* Refuses new staking when after cancel staking and until release it.
*/
bool isWaiting = getStorageWithdrawalStatus(_property, _from) != 0;
require(isWaiting == false, "lockup is already canceled");
/**
* Since the reward per block that can be withdrawn will change with the addition of staking,
* saves the undrawn withdrawable reward before addition it.
*/
updatePendingInterestWithdrawal(_property, _from);
/**
* Saves the variables at the time of staking to prepare for reward calculation.
*/
(, , , uint256 interest, ) = difference(_property, 0);
updateStatesAtLockup(_property, _from, interest);
/**
* Saves variables that should change due to the addition of staking.
*/
updateValues(true, _from, _property, _value);
emit Lockedup(_from, _property, _value);
}
/**
* Cancel staking.
* The staking amount can be withdrawn after the blocks specified by `Policy.lockUpBlocks` have passed.
*/
function cancel(address _property) external {
/**
* Validates the target of staked is included Property set.
*/
addressValidator().validateGroup(_property, config().propertyGroup());
/**
* Validates the sender is staking to the target Property.
*/
require(hasValue(_property, msg.sender), "dev token is not locked");
/**
* Validates not already been canceled.
*/
bool isWaiting = getStorageWithdrawalStatus(_property, msg.sender) != 0;
require(isWaiting == false, "lockup is already canceled");
/**
* Get `Policy.lockUpBlocks`, add it to the current block number, and saves that block number in `WithdrawalStatus`.
* Staking is cannot release until the block number saved in `WithdrawalStatus` is reached.
*/
uint256 blockNumber = IPolicy(config().policy()).lockUpBlocks();
blockNumber = blockNumber.add(block.number);
setStorageWithdrawalStatus(_property, msg.sender, blockNumber);
}
/**
* Withdraw staking.
* Releases canceled staking and transfer the staked amount to the sender.
*/
function withdraw(address _property) external {
/**
* Validates the target of staked is included Property set.
*/
addressValidator().validateGroup(_property, config().propertyGroup());
/**
* Validates the block number reaches the block number where staking can be released.
*/
require(possible(_property, msg.sender), "waiting for release");
/**
* Validates the sender is staking to the target Property.
*/
uint256 lockedUpValue = getStorageValue(_property, msg.sender);
require(lockedUpValue != 0, "dev token is not locked");
/**
* Since the increase of rewards will stop with the release of the staking,
* saves the undrawn withdrawable reward before releasing it.
*/
updatePendingInterestWithdrawal(_property, msg.sender);
/**
* Transfer the staked amount to the sender.
*/
IProperty(_property).withdraw(msg.sender, lockedUpValue);
/**
* Saves variables that should change due to the canceling staking..
*/
updateValues(false, msg.sender, _property, lockedUpValue);
/**
* Sets the staked amount to 0.
*/
setStorageValue(_property, msg.sender, 0);
/**
* Sets the cancellation status to not have.
*/
setStorageWithdrawalStatus(_property, msg.sender, 0);
}
/**
* Returns the current staking amount, and the block number in which the recorded last.
* These values are used to calculate the cumulative sum of the staking.
*/
function getCumulativeLockedUpUnitAndBlock(address _property)
private
view
returns (uint256 _unit, uint256 _block)
{
/**
* Get the current staking amount and the last recorded block number from the `CumulativeLockedUpUnitAndBlock` storage.
* If the last recorded block number is not 0, it is returns as it is.
*/
(
uint256 unit,
uint256 lastBlock
) = getStorageCumulativeLockedUpUnitAndBlock(_property);
if (lastBlock > 0) {
return (unit, lastBlock);
}
/**
* If the last recorded block number is 0, this function falls back as already staked before the current specs (before DIP4).
* More detail for DIP4: https://github.com/dev-protocol/DIPs/issues/4
*
* When the passed address is 0, the caller wants to know the total staking amount on the protocol,
* so gets the total staking amount from `AllValue` storage.
* When the address is other than 0, the caller wants to know the staking amount of a Property,
* so gets the staking amount from the `PropertyValue` storage.
*/
unit = _property == address(0)
? getStorageAllValue()
: getStoragePropertyValue(_property);
/**
* Staking pre-DIP4 will be treated as staked simultaneously with the DIP4 release.
* Therefore, the last recorded block number is the same as the DIP4 release block.
*/
lastBlock = getStorageDIP4GenesisBlock();
return (unit, lastBlock);
}
/**
* Returns the cumulative sum of the staking on passed address, the current staking amount,
* and the block number in which the recorded last.
* The latest cumulative sum can be calculated using the following formula:
* (current staking amount) * (current block number - last recorded block number) + (last cumulative sum)
*/
function getCumulativeLockedUp(address _property)
public
view
returns (
uint256 _value,
uint256 _unit,
uint256 _block
)
{
/**
* Gets the current staking amount and the last recorded block number from the `getCumulativeLockedUpUnitAndBlock` function.
*/
(uint256 unit, uint256 lastBlock) = getCumulativeLockedUpUnitAndBlock(
_property
);
/**
* Gets the last cumulative sum of the staking from `CumulativeLockedUpValue` storage.
*/
uint256 lastValue = getStorageCumulativeLockedUpValue(_property);
/**
* Returns the latest cumulative sum, current staking amount as a unit, and last recorded block number.
*/
return (
lastValue.add(unit.mul(block.number.sub(lastBlock))),
unit,
lastBlock
);
}
/**
* Returns the cumulative sum of the staking on the protocol totally, the current staking amount,
* and the block number in which the recorded last.
*/
function getCumulativeLockedUpAll()
public
view
returns (
uint256 _value,
uint256 _unit,
uint256 _block
)
{
/**
* If the 0 address is passed as a key, it indicates the entire protocol.
*/
return getCumulativeLockedUp(address(0));
}
/**
* Updates the `CumulativeLockedUpValue` and `CumulativeLockedUpUnitAndBlock` storage.
* This function expected to executes when the amount of staking as a unit changes.
*/
function updateCumulativeLockedUp(
bool _addition,
address _property,
uint256 _unit
) private {
address zero = address(0);
/**
* Gets the cumulative sum of the staking amount, staking amount, and last recorded block number for the passed Property address.
*/
(uint256 lastValue, uint256 lastUnit, ) = getCumulativeLockedUp(
_property
);
/**
* Gets the cumulative sum of the staking amount, staking amount, and last recorded block number for the protocol total.
*/
(uint256 lastValueAll, uint256 lastUnitAll, ) = getCumulativeLockedUp(
zero
);
/**
* Adds or subtracts the staking amount as a new unit to the cumulative sum of the staking for the passed Property address.
*/
setStorageCumulativeLockedUpValue(
_property,
_addition ? lastValue.add(_unit) : lastValue.sub(_unit)
);
/**
* Adds or subtracts the staking amount as a new unit to the cumulative sum of the staking for the protocol total.
*/
setStorageCumulativeLockedUpValue(
zero,
_addition ? lastValueAll.add(_unit) : lastValueAll.sub(_unit)
);
/**
* Adds or subtracts the staking amount to the staking unit for the passed Property address.
* Also, record the latest block number.
*/
setStorageCumulativeLockedUpUnitAndBlock(
_property,
_addition ? lastUnit.add(_unit) : lastUnit.sub(_unit),
block.number
);
/**
* Adds or subtracts the staking amount to the staking unit for the protocol total.
* Also, record the latest block number.
*/
setStorageCumulativeLockedUpUnitAndBlock(
zero,
_addition ? lastUnitAll.add(_unit) : lastUnitAll.sub(_unit),
block.number
);
}
/**
* Updates cumulative sum of the maximum mint amount calculated by Allocator contract, the latest maximum mint amount per block,
* and the last recorded block number.
* The cumulative sum of the maximum mint amount is always added.
* By recording that value when the staker last stakes, the difference from the when the staker stakes can be calculated.
*/
function update() public {
/**
* Gets the cumulative sum of the maximum mint amount and the maximum mint number per block.
*/
(uint256 _nextRewards, uint256 _amount) = dry();
/**
* Records each value and the latest block number.
*/
setStorageCumulativeGlobalRewards(_nextRewards);
setStorageLastSameRewardsAmountAndBlock(_amount, block.number);
}
/**
* Updates the cumulative sum of the maximum mint amount when staking, the cumulative sum of staker reward as an interest of the target Property
* and the cumulative staking amount, and the latest block number.
*/
function updateStatesAtLockup(
address _property,
address _user,
uint256 _interest
) private {
/**
* Gets the cumulative sum of the maximum mint amount.
*/
(uint256 _reward, ) = dry();
/**
* Records each value and the latest block number.
*/
if (isSingle(_property, _user)) {
setStorageLastCumulativeGlobalReward(_property, _user, _reward);
}
setStorageLastCumulativePropertyInterest(_property, _user, _interest);
(uint256 cLocked, , ) = getCumulativeLockedUp(_property);
setStorageLastCumulativeLockedUpAndBlock(
_property,
_user,
cLocked,
block.number
);
}
/**
* Returns the last cumulative staking amount of the passed Property address and the last recorded block number.
*/
function getLastCumulativeLockedUpAndBlock(address _property, address _user)
private
view
returns (uint256 _cLocked, uint256 _block)
{
/**
* Gets the values from `LastCumulativeLockedUpAndBlock` storage.
*/
(
uint256 cLocked,
uint256 blockNumber
) = getStorageLastCumulativeLockedUpAndBlock(_property, _user);
/**
* When the last recorded block number is 0, the block number at the time of the DIP4 release is returned as being staked at the same time as the DIP4 release.
* More detail for DIP4: https://github.com/dev-protocol/DIPs/issues/4
*/
if (blockNumber == 0) {
blockNumber = getStorageDIP4GenesisBlock();
}
return (cLocked, blockNumber);
}
/**
* Referring to the values recorded in each storage to returns the latest cumulative sum of the maximum mint amount and the latest maximum mint amount per block.
*/
function dry()
private
view
returns (uint256 _nextRewards, uint256 _amount)
{
/**
* Gets the latest mint amount per block from Allocator contract.
*/
uint256 rewardsAmount = IAllocator(config().allocator())
.calculateMaxRewardsPerBlock();
/**
* Gets the maximum mint amount per block, and the last recorded block number from `LastSameRewardsAmountAndBlock` storage.
*/
(
uint256 lastAmount,
uint256 lastBlock
) = getStorageLastSameRewardsAmountAndBlock();
/**
* If the recorded maximum mint amount per block and the result of the Allocator contract are different,
* the result of the Allocator contract takes precedence as a maximum mint amount per block.
*/
uint256 lastMaxRewards = lastAmount == rewardsAmount
? rewardsAmount
: lastAmount;
/**
* Calculates the difference between the latest block number and the last recorded block number.
*/
uint256 blocks = lastBlock > 0 ? block.number.sub(lastBlock) : 0;
/**
* Adds the calculated new cumulative maximum mint amount to the recorded cumulative maximum mint amount.
*/
uint256 additionalRewards = lastMaxRewards.mul(blocks);
uint256 nextRewards = getStorageCumulativeGlobalRewards().add(
additionalRewards
);
/**
* Returns the latest theoretical cumulative sum of maximum mint amount and maximum mint amount per block.
*/
return (nextRewards, rewardsAmount);
}
/**
* Returns the latest theoretical cumulative sum of maximum mint amount, the holder's reward of the passed Property address and its unit price,
* and the staker's reward as interest and its unit price.
* The latest theoretical cumulative sum of maximum mint amount is got from `dry` function.
* The Holder's reward is a staking(delegation) reward received by the holder of the Property contract(token) according to the share.
* The unit price of the holder's reward is the reward obtained per 1 piece of Property contract(token).
* The staker rewards are rewards for staking users.
* The unit price of the staker reward is the reward per DEV token 1 piece that is staking.
*/
function difference(address _property, uint256 _lastReward)
public
view
returns (
uint256 _reward,
uint256 _holdersAmount,
uint256 _holdersPrice,
uint256 _interestAmount,
uint256 _interestPrice
)
{
/**
* Gets the cumulative sum of the maximum mint amount.
*/
(uint256 rewards, ) = dry();
/**
* Gets the cumulative sum of the staking amount of the passed Property address and
* the cumulative sum of the staking amount of the protocol total.
*/
(uint256 valuePerProperty, , ) = getCumulativeLockedUp(_property);
(uint256 valueAll, , ) = getCumulativeLockedUpAll();
/**
* Calculates the amount of reward that can be received by the Property from the ratio of the cumulative sum of the staking amount of the Property address
* and the cumulative sum of the staking amount of the protocol total.
* If the past cumulative sum of the maximum mint amount passed as the second argument is 1 or more,
* this result is the difference from that cumulative sum.
*/
uint256 propertyRewards = rewards.sub(_lastReward).mul(
valuePerProperty.mulBasis().outOf(valueAll)
);
/**
* Gets the staking amount and total supply of the Property and calls `Policy.holdersShare` function to calculates
* the holder's reward amount out of the total reward amount.
*/
uint256 lockedUpPerProperty = getStoragePropertyValue(_property);
uint256 totalSupply = ERC20Mintable(_property).totalSupply();
uint256 holders = IPolicy(config().policy()).holdersShare(
propertyRewards,
lockedUpPerProperty
);
/**
* The total rewards amount minus the holder reward amount is the staker rewards as an interest.
*/
uint256 interest = propertyRewards.sub(holders);
/**
* Returns each value and a unit price of each reward.
*/
return (
rewards,
holders,
holders.div(totalSupply),
interest,
lockedUpPerProperty > 0 ? interest.div(lockedUpPerProperty) : 0
);
}
/**
* Returns the staker reward as interest.
*/
function _calculateInterestAmount(address _property, address _user)
private
view
returns (uint256)
{
/**
* Gets the cumulative sum of the staking amount, current staking amount, and last recorded block number of the Property.
*/
(
uint256 cLockProperty,
uint256 unit,
uint256 lastBlock
) = getCumulativeLockedUp(_property);
/**
* Gets the cumulative sum of staking amount and block number of Property when the user staked.
*/
(
uint256 lastCLocked,
uint256 lastBlockUser
) = getLastCumulativeLockedUpAndBlock(_property, _user);
/**
* Get the amount the user is staking for the Property.
*/
uint256 lockedUpPerAccount = getStorageValue(_property, _user);
/**
* Gets the cumulative sum of the Property's staker reward when the user staked.
*/
uint256 lastInterest = getStorageLastCumulativePropertyInterest(
_property,
_user
);
/**
* Calculates the cumulative sum of the staking amount from the time the user staked to the present.
* It can be calculated by multiplying the staking amount by the number of elapsed blocks.
*/
uint256 cLockUser = lockedUpPerAccount.mul(
block.number.sub(lastBlockUser)
);
/**
* Determines if the user is the only staker to the Property.
*/
bool isOnly = unit == lockedUpPerAccount && lastBlock <= lastBlockUser;
/**
* If the user is the Property's only staker and the first staker, and the only staker on the protocol:
*/
if (isSingle(_property, _user)) {
/**
* Passing the cumulative sum of the maximum mint amount when staked, to the `difference` function,
* gets the staker reward amount that the user can receive from the time of staking to the present.
* In the case of the staking is single, the ratio of the Property and the user account for 100% of the cumulative sum of the maximum mint amount,
* so the difference cannot be calculated with the value of `LastCumulativePropertyInterest`.
* Therefore, it is necessary to calculate the difference using the cumulative sum of the maximum mint amounts at the time of staked.
*/
(, , , , uint256 interestPrice) = difference(
_property,
getStorageLastCumulativeGlobalReward(_property, _user)
);
/**
* Returns the result after adjusted decimals to 10^18.
*/
uint256 result = interestPrice
.mul(lockedUpPerAccount)
.divBasis()
.divBasis();
return result;
/**
* If not the single but the only staker:
*/
} else if (isOnly) {
/**
* Pass 0 to the `difference` function to gets the Property's cumulative sum of the staker reward.
*/
(, , , uint256 interest, ) = difference(_property, 0);
/**
* Calculates the difference in rewards that can be received by subtracting the Property's cumulative sum of staker rewards at the time of staking.
*/
uint256 result = interest >= lastInterest
? interest.sub(lastInterest).divBasis().divBasis()
: 0;
return result;
}
/**
* If the user is the Property's not the first staker and not the only staker:
*/
/**
* Pass 0 to the `difference` function to gets the Property's cumulative sum of the staker reward.
*/
(, , , uint256 interest, ) = difference(_property, 0);
/**
* Calculates the share of rewards that can be received by the user among Property's staker rewards.
* "Cumulative sum of the staking amount of the Property at the time of staking" is subtracted from "cumulative sum of the staking amount of the Property",
* and calculates the cumulative sum of staking amounts from the time of staking to the present.
* The ratio of the "cumulative sum of staking amount from the time the user staked to the present" to that value is the share.
*/
uint256 share = cLockUser.outOf(cLockProperty.sub(lastCLocked));
/**
* If the Property's staker reward is greater than the value of the `CumulativePropertyInterest` storage,
* calculates the difference and multiply by the share.
* Otherwise, it returns 0.
*/
uint256 result = interest >= lastInterest
? interest
.sub(lastInterest)
.mul(share)
.divBasis()
.divBasis()
.divBasis()
: 0;
return result;
}
/**
* Returns the total rewards currently available for withdrawal. (For calling from inside the contract)
*/
function _calculateWithdrawableInterestAmount(
address _property,
address _user
) private view returns (uint256) {
/**
* If the passed Property has not authenticated, returns always 0.
*/
if (
IMetricsGroup(config().metricsGroup()).hasAssets(_property) == false
) {
return 0;
}
/**
* Gets the reward amount in saved without withdrawal.
*/
uint256 pending = getStoragePendingInterestWithdrawal(_property, _user);
/**
* Gets the reward amount of before DIP4.
*/
uint256 legacy = __legacyWithdrawableInterestAmount(_property, _user);
/**
* Gets the latest withdrawal reward amount.
*/
uint256 amount = _calculateInterestAmount(_property, _user);
/**
* Returns the sum of all values.
*/
uint256 withdrawableAmount = amount
.add(pending) // solium-disable-next-line indentation
.add(legacy);
return withdrawableAmount;
}
/**
* Returns the total rewards currently available for withdrawal. (For calling from external of the contract)
*/
function calculateWithdrawableInterestAmount(
address _property,
address _user
) public view returns (uint256) {
uint256 amount = _calculateWithdrawableInterestAmount(_property, _user);
return amount;
}
/**
* Withdraws staking reward as an interest.
*/
function withdrawInterest(address _property) external {
/**
* Validates the target of staking is included Property set.
*/
addressValidator().validateGroup(_property, config().propertyGroup());
/**
* Gets the withdrawable amount.
*/
uint256 value = _calculateWithdrawableInterestAmount(
_property,
msg.sender
);
/**
* Gets the cumulative sum of staker rewards of the passed Property address.
*/
(, , , uint256 interest, ) = difference(_property, 0);
/**
* Validates rewards amount there are 1 or more.
*/
require(value > 0, "your interest amount is 0");
/**
* Sets the unwithdrawn reward amount to 0.
*/
setStoragePendingInterestWithdrawal(_property, msg.sender, 0);
/**
* Creates a Dev token instance.
*/
ERC20Mintable erc20 = ERC20Mintable(config().token());
/**
* Updates the staking status to avoid double rewards.
*/
updateStatesAtLockup(_property, msg.sender, interest);
__updateLegacyWithdrawableInterestAmount(_property, msg.sender);
/**
* Mints the reward.
*/
require(erc20.mint(msg.sender, value), "dev mint failed");
/**
* Since the total supply of tokens has changed, updates the latest maximum mint amount.
*/
update();
}
/**
* Status updates with the addition or release of staking.
*/
function updateValues(
bool _addition,
address _account,
address _property,
uint256 _value
) private {
/**
* If added staking:
*/
if (_addition) {
/**
* Updates the cumulative sum of the staking amount of the passed Property and the cumulative amount of the staking amount of the protocol total.
*/
updateCumulativeLockedUp(true, _property, _value);
/**
* Updates the current staking amount of the protocol total.
*/
addAllValue(_value);
/**
* Updates the current staking amount of the Property.
*/
addPropertyValue(_property, _value);
/**
* Updates the user's current staking amount in the Property.
*/
addValue(_property, _account, _value);
/**
* If released staking:
*/
} else {
/**
* Updates the cumulative sum of the staking amount of the passed Property and the cumulative amount of the staking amount of the protocol total.
*/
updateCumulativeLockedUp(false, _property, _value);
/**
* Updates the current staking amount of the protocol total.
*/
subAllValue(_value);
/**
* Updates the current staking amount of the Property.
*/
subPropertyValue(_property, _value);
}
/**
* Since each staking amount has changed, updates the latest maximum mint amount.
*/
update();
}
/**
* Returns the staking amount of the protocol total.
*/
function getAllValue() external view returns (uint256) {
return getStorageAllValue();
}
/**
* Adds the staking amount of the protocol total.
*/
function addAllValue(uint256 _value) private {
uint256 value = getStorageAllValue();
value = value.add(_value);
setStorageAllValue(value);
}
/**
* Subtracts the staking amount of the protocol total.
*/
function subAllValue(uint256 _value) private {
uint256 value = getStorageAllValue();
value = value.sub(_value);
setStorageAllValue(value);
}
/**
* Returns the user's staking amount in the Property.
*/
function getValue(address _property, address _sender)
external
view
returns (uint256)
{
return getStorageValue(_property, _sender);
}
/**
* Adds the user's staking amount in the Property.
*/
function addValue(
address _property,
address _sender,
uint256 _value
) private {
uint256 value = getStorageValue(_property, _sender);
value = value.add(_value);
setStorageValue(_property, _sender, value);
}
/**
* Returns whether the user is staking in the Property.
*/
function hasValue(address _property, address _sender)
private
view
returns (bool)
{
uint256 value = getStorageValue(_property, _sender);
return value != 0;
}
/**
* Returns whether a single user has all staking share.
* This value is true when only one Property and one user is historically the only staker.
*/
function isSingle(address _property, address _user)
private
view
returns (bool)
{
uint256 perAccount = getStorageValue(_property, _user);
(uint256 cLockProperty, uint256 unitProperty, ) = getCumulativeLockedUp(
_property
);
(uint256 cLockTotal, , ) = getCumulativeLockedUpAll();
return perAccount == unitProperty && cLockProperty == cLockTotal;
}
/**
* Returns the staking amount of the Property.
*/
function getPropertyValue(address _property)
external
view
returns (uint256)
{
return getStoragePropertyValue(_property);
}
/**
* Adds the staking amount of the Property.
*/
function addPropertyValue(address _property, uint256 _value) private {
uint256 value = getStoragePropertyValue(_property);
value = value.add(_value);
setStoragePropertyValue(_property, value);
}
/**
* Subtracts the staking amount of the Property.
*/
function subPropertyValue(address _property, uint256 _value) private {
uint256 value = getStoragePropertyValue(_property);
uint256 nextValue = value.sub(_value);
setStoragePropertyValue(_property, nextValue);
}
/**
* Saves the latest reward amount as an undrawn amount.
*/
function updatePendingInterestWithdrawal(address _property, address _user)
private
{
/**
* Gets the latest reward amount.
*/
uint256 withdrawableAmount = _calculateWithdrawableInterestAmount(
_property,
_user
);
/**
* Saves the amount to `PendingInterestWithdrawal` storage.
*/
setStoragePendingInterestWithdrawal(
_property,
_user,
withdrawableAmount
);
/**
* Updates the reward amount of before DIP4 to prevent further addition it.
*/
__updateLegacyWithdrawableInterestAmount(_property, _user);
}
/**
* Returns whether the staking can be released.
*/
function possible(address _property, address _from)
private
view
returns (bool)
{
uint256 blockNumber = getStorageWithdrawalStatus(_property, _from);
if (blockNumber == 0) {
return false;
}
if (blockNumber <= block.number) {
return true;
} else {
if (IPolicy(config().policy()).lockUpBlocks() == 1) {
return true;
}
}
return false;
}
/**
* Returns the reward amount of the calculation model before DIP4.
* It can be calculated by subtracting "the last cumulative sum of reward unit price" from
* "the current cumulative sum of reward unit price," and multiplying by the staking amount.
*/
function __legacyWithdrawableInterestAmount(
address _property,
address _user
) private view returns (uint256) {
uint256 _last = getStorageLastInterestPrice(_property, _user);
uint256 price = getStorageInterestPrice(_property);
uint256 priceGap = price.sub(_last);
uint256 lockedUpValue = getStorageValue(_property, _user);
uint256 value = priceGap.mul(lockedUpValue);
return value.divBasis();
}
/**
* Updates and treats the reward of before DIP4 as already received.
*/
function __updateLegacyWithdrawableInterestAmount(
address _property,
address _user
) private {
uint256 interestPrice = getStorageInterestPrice(_property);
if (getStorageLastInterestPrice(_property, _user) != interestPrice) {
setStorageLastInterestPrice(_property, _user, interestPrice);
}
}
/**
* Updates the block number of the time of DIP4 release.
*/
function setDIP4GenesisBlock(uint256 _block) external onlyOwner {
/**
* Validates the value is not set.
*/
require(getStorageDIP4GenesisBlock() == 0, "already set the value");
/**
* Sets the value.
*/
setStorageDIP4GenesisBlock(_block);
}
}
// File: contracts/src/dev/Dev.sol
pragma solidity ^0.5.0;
// prettier-ignore
// prettier-ignore
// prettier-ignore
/**
* The contract used as the DEV token.
* The DEV token is an ERC20 token used as the native token of the Dev Protocol.
* The DEV token is created by migration from its predecessor, the MVP, legacy DEV token. For that reason, the initial supply is 0.
* Also, mint will be performed based on the Allocator contract.
* When authenticated a new asset by the Market contracts, DEV token is burned as fees.
*/
contract Dev is
ERC20Detailed,
ERC20Mintable,
ERC20Burnable,
UsingConfig,
UsingValidator
{
/**
* Initialize the passed address as AddressConfig address.
* The token name is `Dev`, the token symbol is `DEV`, and the decimals is 18.
*/
constructor(address _config)
public
ERC20Detailed("Dev", "DEV", 18)
UsingConfig(_config)
{}
/**
* Staking DEV tokens.
* The transfer destination must always be included in the address set for Property tokens.
* This is because if the transfer destination is not a Property token, it is possible that the staked DEV token cannot be withdrawn.
*/
function deposit(address _to, uint256 _amount) external returns (bool) {
require(transfer(_to, _amount), "dev transfer failed");
lock(msg.sender, _to, _amount);
return true;
}
/**
* Staking DEV tokens by an allowanced address.
* The transfer destination must always be included in the address set for Property tokens.
* This is because if the transfer destination is not a Property token, it is possible that the staked DEV token cannot be withdrawn.
*/
function depositFrom(
address _from,
address _to,
uint256 _amount
) external returns (bool) {
require(transferFrom(_from, _to, _amount), "dev transferFrom failed");
lock(_from, _to, _amount);
return true;
}
/**
* Burn the DEV tokens as an authentication fee.
* Only Market contracts can execute this function.
*/
function fee(address _from, uint256 _amount) external returns (bool) {
addressValidator().validateGroup(msg.sender, config().marketGroup());
_burn(_from, _amount);
return true;
}
/**
* Call `Lockup.lockup` to execute staking.
*/
function lock(
address _from,
address _to,
uint256 _amount
) private {
Lockup(config().lockup()).lockup(_from, _to, _amount);
}
}
// File: contracts/src/market/Market.sol
pragma solidity ^0.5.0;
/**
* A user-proposable contract for authenticating and associating assets with Property.
* A user deploys a contract that inherits IMarketBehavior and creates this Market contract with the MarketFactory contract.
*/
contract Market is UsingConfig, IMarket, UsingValidator {
using SafeMath for uint256;
bool public enabled;
address public behavior;
uint256 public votingEndBlockNumber;
uint256 public issuedMetrics;
mapping(bytes32 => bool) private idMap;
mapping(address => bytes32) private idHashMetricsMap;
/**
* Initialize the passed address as AddressConfig address and user-proposed contract.
*/
constructor(address _config, address _behavior)
public
UsingConfig(_config)
{
/**
* Validates the sender is MarketFactory contract.
*/
addressValidator().validateAddress(
msg.sender,
config().marketFactory()
);
/**
* Stores the contract address proposed by a user as an internal variable.
*/
behavior = _behavior;
/**
* By default this contract is disabled.
*/
enabled = false;
/**
* Sets the period during which voting by voters can be accepted.
* This period is determined by `Policy.marketVotingBlocks`.
*/
uint256 marketVotingBlocks = IPolicy(config().policy())
.marketVotingBlocks();
votingEndBlockNumber = block.number.add(marketVotingBlocks);
}
/**
* Validates the sender is the passed Property's author.
*/
function propertyValidation(address _prop) private view {
addressValidator().validateAddress(
msg.sender,
IProperty(_prop).author()
);
require(enabled, "market is not enabled");
}
/**
* Modifier for validates the sender is the passed Property's author.
*/
modifier onlyPropertyAuthor(address _prop) {
propertyValidation(_prop);
_;
}
/**
* Modifier for validates the sender is the author of the Property associated with the passed Metrics contract.
*/
modifier onlyLinkedPropertyAuthor(address _metrics) {
address _prop = Metrics(_metrics).property();
propertyValidation(_prop);
_;
}
/**
* Activates this Market.
* Called from VoteCounter contract when passed the voting or from MarketFactory contract when the first Market is created.
*/
function toEnable() external {
addressValidator().validateAddresses(
msg.sender,
config().marketFactory(),
config().voteCounter()
);
enabled = true;
}
/**
* Bypass to IMarketBehavior.authenticate.
* Authenticates the new asset and proves that the Property author is the owner of the asset.
*/
function authenticate(
address _prop,
string memory _args1,
string memory _args2,
string memory _args3,
string memory _args4,
string memory _args5
) public onlyPropertyAuthor(_prop) returns (bool) {
uint256 len = bytes(_args1).length;
require(len > 0, "id is required");
return
IMarketBehavior(behavior).authenticate(
_prop,
_args1,
_args2,
_args3,
_args4,
_args5,
address(this),
msg.sender
);
}
/**
* Returns the authentication fee.
* Calculates by gets the staking amount of the Property to be authenticated
* and the total number of authenticated assets on the protocol, and calling `Policy.authenticationFee`.
*/
function getAuthenticationFee(address _property)
private
view
returns (uint256)
{
uint256 tokenValue = ILockup(config().lockup()).getPropertyValue(
_property
);
IPolicy policy = IPolicy(config().policy());
IMetricsGroup metricsGroup = IMetricsGroup(config().metricsGroup());
return
policy.authenticationFee(
metricsGroup.totalIssuedMetrics(),
tokenValue
);
}
/**
* A function that will be called back when the asset is successfully authenticated.
* There are cases where oracle is required for the authentication process, so the function is used callback style.
*/
function authenticatedCallback(address _property, bytes32 _idHash)
external
returns (address)
{
/**
* Validates the sender is the saved IMarketBehavior address.
*/
addressValidator().validateAddress(msg.sender, behavior);
require(enabled, "market is not enabled");
/**
* Validates the assets are not double authenticated.
*/
require(idMap[_idHash] == false, "id is duplicated");
idMap[_idHash] = true;
/**
* Gets the Property author address.
*/
address sender = IProperty(_property).author();
/**
* Publishes a new Metrics contract and associate the Property with the asset.
*/
IMetricsFactory metricsFactory = IMetricsFactory(
config().metricsFactory()
);
address metrics = metricsFactory.create(_property);
idHashMetricsMap[metrics] = _idHash;
/**
* Burn as a authentication fee.
*/
uint256 authenticationFee = getAuthenticationFee(_property);
require(
Dev(config().token()).fee(sender, authenticationFee),
"dev fee failed"
);
/**
* Adds the number of authenticated assets in this Market.
*/
issuedMetrics = issuedMetrics.add(1);
return metrics;
}
/**
* Release the authenticated asset.
*/
function deauthenticate(address _metrics)
external
onlyLinkedPropertyAuthor(_metrics)
{
/**
* Validates the passed Metrics address is authenticated in this Market.
*/
bytes32 idHash = idHashMetricsMap[_metrics];
require(idMap[idHash], "not authenticated");
/**
* Removes the authentication status from local variables.
*/
idMap[idHash] = false;
idHashMetricsMap[_metrics] = bytes32(0);
/**
* Removes the passed Metrics contract from the Metrics address set.
*/
IMetricsFactory metricsFactory = IMetricsFactory(
config().metricsFactory()
);
metricsFactory.destroy(_metrics);
/**
* Subtracts the number of authenticated assets in this Market.
*/
issuedMetrics = issuedMetrics.sub(1);
}
/**
* Bypass to IMarketBehavior.schema.
*/
function schema() external view returns (string memory) {
return IMarketBehavior(behavior).schema();
}
}
// File: contracts/src/market/IMarketGroup.sol
pragma solidity ^0.5.0;
contract IMarketGroup is IGroup {
function getCount() external view returns (uint256);
}
// File: contracts/src/market/MarketFactory.sol
pragma solidity ^0.5.0;
/**
* A factory contract that creates a new Market contract.
*/
contract MarketFactory is IMarketFactory, UsingConfig, UsingValidator {
event Create(address indexed _from, address _market);
/**
* Initialize the passed address as AddressConfig address.
*/
// solium-disable-next-line no-empty-blocks
constructor(address _config) public UsingConfig(_config) {}
/**
* Creates a new Market contract.
*/
function create(address _addr) external returns (address) {
/**
* Validates the passed address is not 0 address.
*/
addressValidator().validateIllegalAddress(_addr);
/**
* Creates a new Market contract with the passed address as the IMarketBehavior.
*/
Market market = new Market(address(config()), _addr);
/**
* Adds the created Market contract to the Market address set.
*/
address marketAddr = address(market);
IMarketGroup marketGroup = IMarketGroup(config().marketGroup());
marketGroup.addGroup(marketAddr);
/**
* For the first Market contract, it will be activated immediately.
* If not, the Market contract will be activated after a vote by the voters.
*/
if (marketGroup.getCount() == 1) {
market.toEnable();
}
emit Create(msg.sender, marketAddr);
return marketAddr;
}
} | Destroys `amount` tokens from the caller. See {ERC20-_burn}./ | function burn(uint256 amount) public {
_burn(_msgSender(), amount);
}
| 10,085,404 |
./full_match/4/0x42FB57E852bcA06C29dc1cBFea0E4aa735920571/sources/browser/this.sol | According to EIP-1052, 0x0 is the value returned for not-yet created accounts and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned for accounts without code, i.e. `keccak256('')` solhint-disable-next-line no-inline-assembly | function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
return (codehash != accountHash && codehash != 0x0);
}
| 663,281 |
./full_match/1/0x3E8AF8a2f06f2dB2474c13d7259724758B42Cf53/sources/XengameV2Live/NFTregistry.sol | Calculate the reward points for the NFT Check if the NFT was previously registered to a different user Remove the previous owner's points Pay the previous owner their rewards | function registerNFT(uint256 tokenId) public {
address player = msg.sender;
require(IXENNFTContract(nftContractAddress).ownerOf(tokenId) == player, "You don't own this NFT.");
uint256 rewardPoints = getTokenWeight(tokenId);
address previousOwner = getNFTOwner(tokenId);
require(previousOwner != player, "You already have this NFT regestered");
if (previousOwner != address(0) && previousOwner != player) {
User storage previousOwnerData = users[previousOwner];
uint256 previousRewardPoints = previousOwnerData.userPoints;
uint256 previousRewardAmount = calculateReward(previousOwner);
address payable previousOwnerpay = payable(previousOwner);
previousOwnerData.userPoints -= previousRewardPoints;
previousOwnerpay.transfer(previousRewardAmount);
}
User storage currentUserData = users[player];
if (currentUserData.lastRewardRatio != rewardRatio && currentUserData.lastRewardRatio != 0) {
withdrawRewards();
}
currentUserData.userPoints += rewardPoints;
totalPoints += rewardPoints;
currentUserData.lastRewardRatio = rewardRatio;
emit NFTRegistered(player, tokenId, rewardPoints);
}
| 17,023,542 |
pragma solidity 0.5.16;
pragma experimental ABIEncoderV2;
import 'OpenZeppelin/[email protected]/contracts/ownership/Ownable.sol';
import 'OpenZeppelin/[email protected]/contracts/math/SafeMath.sol';
// import 'Uniswap/[email protected]/contracts/interfaces/IUniswapV2Pair.sol';
import './interfaces/IMdexPair.sol';
import './GoblinConfig.sol';
import './PriceOracle.sol';
import './SafeToken.sol';
interface IPancakeswapGoblin {
function lpToken() external view returns (IMdexPair);
}
contract PancakeswapGoblinConfig is Ownable, GoblinConfig {
using SafeToken for address;
using SafeMath for uint;
struct Config {
bool acceptDebt;
uint64 workFactor;
uint64 killFactor;
uint64 maxPriceDiff;
}
PriceOracle public oracle;
mapping(address => Config) public goblins;
constructor(PriceOracle _oracle) public {
oracle = _oracle;
}
/// @dev Set oracle address. Must be called by owner.
function setOracle(PriceOracle _oracle) external onlyOwner {
oracle = _oracle;
}
/// @dev Set goblin configurations. Must be called by owner.
function setConfigs(address[] calldata addrs, Config[] calldata configs) external onlyOwner {
uint len = addrs.length;
require(configs.length == len, 'bad len');
for (uint idx = 0; idx < len; idx++) {
goblins[addrs[idx]] = Config({
acceptDebt: configs[idx].acceptDebt,
workFactor: configs[idx].workFactor,
killFactor: configs[idx].killFactor,
maxPriceDiff: configs[idx].maxPriceDiff
});
}
}
/// @dev Return whether the given goblin is stable, presumably not under manipulation.
function isStable(address goblin) public view returns (bool) {
IMdexPair lp = IPancakeswapGoblin(goblin).lpToken();
address token0 = lp.token0();
address token1 = lp.token1();
// 1. Check that reserves and balances are consistent (within 1%)
(uint r0, uint r1, ) = lp.getReserves();
uint t0bal = token0.balanceOf(address(lp));
uint t1bal = token1.balanceOf(address(lp));
require(t0bal.mul(100) <= r0.mul(101), 'bad t0 balance');
require(t1bal.mul(100) <= r1.mul(101), 'bad t1 balance');
// 2. Check that price is in the acceptable range
(uint price, uint lastUpdate) = oracle.getPrice(token0, token1);
require(lastUpdate >= now - 7 days, 'price too stale');
uint lpPrice = r1.mul(1e18).div(r0);
uint maxPriceDiff = goblins[goblin].maxPriceDiff;
require(lpPrice <= price.mul(maxPriceDiff).div(10000), 'price too high');
require(lpPrice >= price.mul(10000).div(maxPriceDiff), 'price too low');
// 3. Done
return true;
}
/// @dev Return whether the given goblin accepts more debt.
function acceptDebt(address goblin) external view returns (bool) {
require(isStable(goblin), '!stable');
return goblins[goblin].acceptDebt;
}
/// @dev Return the work factor for the goblin + BNB debt, using 1e4 as denom.
function workFactor(
address goblin,
uint /* debt */
) external view returns (uint) {
require(isStable(goblin), '!stable');
return uint(goblins[goblin].workFactor);
}
/// @dev Return the kill factor for the goblin + BNB debt, using 1e4 as denom.
function killFactor(
address goblin,
uint /* debt */
) external view returns (uint) {
require(isStable(goblin), '!stable');
return uint(goblins[goblin].killFactor);
}
}
| Return the kill factor for the goblin + BNB debt, using 1e4 as denom. | function killFactor(
address goblin,
uint /* debt */
) external view returns (uint) {
require(isStable(goblin), '!stable');
return uint(goblins[goblin].killFactor);
}
| 5,429,071 |
./full_match/1/0x1F033Cb8A2Df08a147BC512723fd0da3FEc5cCA7/sources/autopay/contracts/Autopay.sol | Getter function for retrieving the total amount of tips paid by a given address _user address of user to query return uint256 total amount of tips paid by user/ | function getTipsByAddress(address _user) external view returns (uint256) {
return userTipsTotal[_user];
}
| 4,950,813 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/utils/Context.sol";
// ============ Errors ============
error InvalidCall();
// ============ Contract ============
abstract contract ERC721 is Context, ERC165, IERC721 {
// ============ Storage ============
// Mapping from token ID to owner address
mapping(uint256 => address) internal _owners;
// Mapping owner address to token count
mapping(address => uint256) internal _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;
// ============ Modifiers ============
modifier isOwner(uint256 tokenId, address owner) {
if (_owners[tokenId] != owner) revert InvalidCall();
_;
}
modifier isToken(uint256 tokenId) {
if (_owners[tokenId] == address(0)) revert InvalidCall();
_;
}
modifier isNotToken(uint256 tokenId) {
if (_owners[tokenId] != address(0)) revert InvalidCall();
_;
}
modifier notZeroAddress(address location) {
if (location == address(0)) revert InvalidCall();
_;
}
modifier isApproved(address from, uint256 tokenId) {
address spender = _msgSender();
if (spender != from
&& getApproved(tokenId) != spender
&& !isApprovedForAll(from, spender)
) revert InvalidCall();
_;
}
// ============ Read Methods ============
/**
* @dev Returns the number of tokens in `owner`'s account.
*/
function balanceOf(
address owner
) public virtual view returns(uint256 balance) {
return _balances[owner];
}
/**
* @dev Returns the account approved for `tokenId` token.
*/
function getApproved(
uint256 tokenId
) public virtual view returns(address operator) {
return _tokenApprovals[tokenId];
}
/**
* @dev Returns if the `operator` is allowed to manage all of the
* assets of `owner`.
*/
function isApprovedForAll(
address owner,
address operator
) public virtual view returns(bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev Returns the owner of the `tokenId` token.
*/
function ownerOf(
uint256 tokenId
) public virtual view returns(address owner) {
return _owners[tokenId];
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
virtual
view
override(ERC165, IERC165)
returns(bool)
{
return
interfaceId == type(IERC721).interfaceId
|| super.supportsInterface(interfaceId);
}
// ============ Approve Methods ============
/**
* @dev Gives permission to `to` to transfer `tokenId` token to
* another account. The approval is cleared when the token is
* transferred.
*/
function approve(address to, uint256 tokenId) public virtual {
address owner = _owners[tokenId];
if (to == owner) revert InvalidCall();
address sender = _msgSender();
if (sender != owner && !isApprovedForAll(owner, sender))
revert InvalidCall();
_approve(to, tokenId, owner);
}
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any
* token owned by the caller.
*/
function setApprovalForAll(
address operator,
bool approved
) public virtual {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId, address owner)
internal virtual
{
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any
* token owned by the caller.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
if (owner == operator) revert InvalidCall();
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
// ============ Burn Methods ============
/**
* @dev Blindly burns `tokenId`.
*/
function _burn(uint256 tokenId) internal virtual isToken(tokenId) {
address from = _owners[tokenId];
//allow other contracts to tap into this
_beforeTokenTransfer(from, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId, from);
unchecked {
_balances[from] -= 1;
delete _owners[tokenId];
}
emit Transfer(from, address(0), tokenId);
}
// ============ Mint Methods ============
/**
* @dev Blindly mints `tokenId` to `to`.
*/
function _mint(
address to,
uint256 tokenId
) internal virtual notZeroAddress(to) isNotToken(tokenId) {
//allow other contracts to tap into this
_beforeTokenTransfer(address(0), to, tokenId);
unchecked {
_balances[to] += 1;
_owners[tokenId] = to;
}
emit Transfer(address(0), 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);
//if smart contract
if (to.code.length > 0
//and not received
&& !_checkOnERC721Received(address(0), to, tokenId, _data)
) revert InvalidCall();
}
// ============ Transfer Methods ============
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @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.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory data
) public virtual override isApproved(from, tokenId) {
_safeTransfer(from, to, tokenId, data);
}
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override isApproved(from, tokenId) {
//go ahead and transfer
_transfer(from, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received}
* on a target address. The call is not executed if the target address
* is not a contract.
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
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 InvalidCall();
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
/**
* @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.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory data
) internal virtual {
_transfer(from, to, tokenId);
//see: @openzep/utils/Address.sol
if (to.code.length > 0
&& !_checkOnERC721Received(from, to, tokenId, data)
) revert InvalidCall();
}
/**
* @dev Blindly transfers `tokenId` token from `from` to `to`.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual isToken(tokenId) isOwner(tokenId, from) {
//allow other contracts to tap into this
_beforeTokenTransfer(from, to, tokenId);
unchecked {
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
}
emit Transfer(from, to, tokenId);
}
// ============ TODO Methods ============
/**
* @dev Hook that is called before a set of serially-ordered token ids
* are about to be transferred. This includes minting.
*
* startTokenId - the first token id to be transferred
* amount - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId`
* will be transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
} | Approve or remove `operator` as an operator for the caller. Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller./ | function setApprovalForAll(
address operator,
bool approved
) public virtual {
_setApprovalForAll(_msgSender(), operator, approved);
}
| 977,338 |
./full_match/1/0x4361b1B8aE2E4f96bFB7A2BC95D6aB748882fdbB/sources/src/Fiefdoms.sol | Checks if given token ID exists tokenId Token to run existence check on return True if token exists | function exists(uint256 tokenId) external view returns (bool) {
return _exists(tokenId);
}
| 4,962,743 |
/**
*Submitted for verification at Etherscan.io on 2022-04-25
*/
/*
_____ _ _ _ _
|_ _| __ __ __ (_) | |_ | |_ ___ | | ___ _ _
| | \ V V / | | | _| | _| / -_) | | / _ \ | ' \
_|_|_ \_/\_/ _|_|_ _\__| _\__| \___| _|_|_ \___/ |_||_|
_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|
"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'
Welcome to the official Twittelon Telegram chat.
Be a tweetoooorr and tell everyone about $TWTELN and of course don't forget to praise Mylady Elon and $TWTELN.
Telegram: t.me/twittelon_inu
Twitter: twitter.com/TwittelonInu
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract TokenTimelock {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// beneficiary of tokens after they are released
address private _beneficiary;
// tells if the lock is initiated
bool private _lockInitiated = false;
// timestamp when token release is enabled
uint256 private _releaseTime;
constructor (address beneficiary) public {
// solhint-disable-next-line not-rely-on-time
_beneficiary = beneficiary;
}
/**
* @notice Initiates the unlock timestamp
*/
function initiateLock(uint256 releaseTime) public virtual {
require(!_lockInitiated, "Lock is already initiated");
require(msg.sender == _beneficiary, "Only the beneficiary can initiate the lock");
require(releaseTime > block.timestamp, "Release time is before current time");
_releaseTime = releaseTime;
_lockInitiated = true;
}
/**
* @return the beneficiary of the tokens.
*/
function beneficiary() public view returns (address) {
return _beneficiary;
}
/**
* @return the time when the tokens are released.
*/
function releaseTime() public view returns (uint256) {
return _releaseTime;
}
/**
* @return if the lock is initiated.
*/
function initiated() public view returns (bool) {
return _lockInitiated;
}
/**
* @return if the funds can be withdrawn yet or not
*/
function unlocked() public view returns (bool){
return block.timestamp >= _releaseTime;
}
/**
* @return holdings of a token in the lock
*/
function holdings(IERC20 token) public view returns (uint256){
return token.balanceOf(address(this));
}
/**
* @notice Increases the unlock timestamp
*/
function increaseLock(uint256 newReleaseTime) public virtual {
require(_lockInitiated, "Lock is not yet initiated");
require(msg.sender == _beneficiary, "Only the beneficiary can increase the locktime");
require(newReleaseTime > _releaseTime, "New releasetime has to be greater than current one");
_releaseTime = newReleaseTime;
}
/**
* @notice Transfers tokens held by timelock to beneficiary.
*/
function release(IERC20 token) public virtual {
require(_lockInitiated, "Lock is not yet initiated");
require(block.timestamp >= _releaseTime, "Current time is before release time");
uint256 amount = token.balanceOf(address(this));
require(amount > 0, "No tokens to release");
token.safeTransfer(_beneficiary, amount);
}
}
contract TwittelonInuTimelock is TokenTimelock {
constructor(address beneficiary)
public
TokenTimelock(beneficiary)
{}
} | return holdings of a token in the lock/ | function holdings(IERC20 token) public view returns (uint256){
return token.balanceOf(address(this));
}
| 7,881,454 |
// SPDX-License-Identifier: MIT
//WARNING: Psuedo-code/Draft Phase... Do NOT USE THIS IN PRODUCTION. The current version of this contract is essentially pseudo code containing major functionality that will be edited to be operational by community
pragma solidity >=0.8.0 <0.9.0;
pragma experimental ABIEncoderV2;
//Required libs
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
//Options Market Liquidity Pool
contract LiquidityPool is ReentrancyGuard {
using SafeMath for uint256;
modifier onlyOwner() {
require(msg.sender == owner, "Only owner can complete this tx");
_;
}
//allow deposits of ETH
fallback() external payable {}
receive() external payable {}
//mapping of each user's balance in the pool, similar to ERC20 balanceOf
mapping(address => uint256) public poolOwnerBalance;
//All tokens that this pool will accept to provide options liquidity for
mapping(address => bool) public tokenAddressWhitelisted;
//owner of the contract is ideally a DAO that can make decisions about when to initiate the pool and important rules it will follow
address public owner;
//Current total value... Most useful when withdrawals are happening versus its brother below which is how much was ever deposited
uint256 public poolTotalValue = 0;
//factor for percentage scaling
uint256 public percScale = 1e18;
//Total amount ever deposited here
uint256 public poolTotalDeposits = 0;
//The token (usually a stablecoin such as DAI that is accepted as a deposit to contribute to a user's poolOwnerBalance)
// address public depositToken = address(0x0);
IERC20 private _depositToken;
//The options market contract that is allowed to request the liquidity of this pool to it if it follows the rule fo the pool
address public optionsMarketContract = address(0x0);
//The maximum percentage that can be contributed by the pool for any given position or liquidity request
uint256 maxPercentageCapitalForAnyPosition = 2000; // 20%
//The date set by owner DAO whereby liquity can be withdrawn... No options can expire after this date
uint256 withdrawalDate = 0;
//Variable (boolean) that determines whether LPS can withdraw... is triggered to flase when pool officially starts, and set back to true when the pool ends... Users can at any point... if they are LP... withdraw thier rewards from this contract
bool allLPsCanWithdraw = true;
//Event triggered for Graph and users on Etherscan/ other explorers to track
event CapitalProvided(address optionsMarketAddress, uint256 amount);
//LP Pool Deposit token events
event Transfer(address from, address to, uint256 tokens);
event Approval(address approver, address spender, uint256 amount);
//Set creator as owner initially
constructor() payable {
owner = msg.sender;
}
//Token that can be received as a deposit by LPs
function setDepositToken(IERC20 token) public onlyOwner {
_depositToken = token;
}
//date by which deposits can be withdrawn with rewards
function setWithdrawDate(uint256 date) public onlyOwner returns (bool) {
require(date == 0, "Owner cannot change the withdrawal date");
withdrawalDate = date;
return true;
}
//the owner (DAO) can set the maximum percentage of total that can be used ina given requested position
function updateCapitalPercMaxForAnyPosition(uint256 percentage)
public
onlyOwner
returns (bool)
{
//1000 = 10%
maxPercentageCapitalForAnyPosition = percentage;
return true;
}
//User deposits and becomes an LP
function deposit(uint256 amount) public payable returns (bool) {
require(
_depositToken.transferFrom(msg.sender, address(this), amount),
"You must have the balance of the deposit token and have approved this contract before doing this"
);
poolTotalDeposits = poolTotalDeposits.add(amount);
poolTotalValue = poolTotalValue.add(amount);
poolOwnerBalance[msg.sender] = poolOwnerBalance[msg.sender].add(amount);
return true;
}
function calculatePercentage(uint256 _amount)
internal
view
returns (uint256)
{
uint256 userPercent = (
((_amount.mul(percScale)).div(100)).mul(poolTotalDeposits)
);
return userPercent;
}
//User withdraws their tokens after the expiration date of the pool
function withdraw(uint256 amount) public returns (bool) {
require(
allLPsCanWithdraw,
"allLPsCanWithdraw must be set to true for LPs to withdraw"
);
//percentage in 1e18
uint256 userPercentageOfDeposits = calculatePercentage(
poolOwnerBalance[msg.sender]
);
//do conversion and transfer
uint256 amountOutputTokensEntitledTo = (
poolTotalValue.mul(userPercentageOfDeposits)
).div(percScale);
_depositToken.transfer(msg.sender, amountOutputTokensEntitledTo);
poolOwnerBalance[msg.sender] = poolOwnerBalance[msg.sender].sub(amount);
poolTotalValue = poolTotalValue.sub(amount);
return true;
}
//User withdraws their percentage of the pool and rewards
function withdrawAll() public returns (bool) {
//User total Balance of the pool after the expiration of the pool
return true;
}
//Called by any user after the withdrawal/expiration date of the pool to trigger the ability for LPs to withdraw their rewards+initial send
function releaseCapitalAndRewardsForLPClaim() public returns (bool) {
if (block.timestamp > withdrawalDate) {
allLPsCanWithdraw = true;
}
return true;
}
//Owner (DAO) can set which tokens it will enter markets of
function whitelistToken(address tokenAddress)
public
payable
onlyOwner
returns (bool)
{
tokenAddressWhitelisted[tokenAddress] = true;
return true;
}
//OptionsMarket calls this function to get capital to create sell orders for someones options purchase order, setting the premium based on rules of the pool
function provideCapitalForOptionOrder(
IERC20 token,
uint256 amountOutputToken
) public {
require(
msg.sender == optionsMarketContract,
"only the authorized options market can make requests to this contract for liquidity"
);
bool authorized = isWhitelistedToken(token);
require(authorized, "This token is not authorized for this pool");
if (token != _depositToken) {
uint256 calculatedInputAmount = swapRate(
_depositToken,
token,
amountOutputToken
);
uint256 percentageOfTotalDeposits = calculatedInputAmount
.mul(1000)
.div(poolTotalValue);
require(
percentageOfTotalDeposits <= maxPercentageCapitalForAnyPosition,
"This amount of liquidity cannot be provided for a single transaction"
);
// uint256 outputAmount = swapForAmount(_depositToken, token, amountOutputToken);
}
token.transfer(optionsMarketContract, amountOutputToken);
emit CapitalProvided(optionsMarketContract, amountOutputToken);
}
//Gets the chainlink and/or uniswap rate for a token (Should not be suseptible to flash attacks, therefore best from a trusted oracle)
function swapRate(
IERC20 tokenFrom,
IERC20 tokenTo,
uint256 amount
) public pure returns (uint256) {
//gets rate from external AMM or chainlink, then returns
uint256 swapRate;
return swapRate;
}
function updateOwnerDAO(address newDAO) public onlyOwner returns (bool) {
owner = newDAO;
return true;
}
//Swaps a token using the best route... ETH->DAI or ETH->USDC->DAI to get the best reate for the user.
function swapForAmount(
IERC20 theDepositToken,
IERC20 token,
uint256 amountOutputToken
) public pure returns (uint256) {
//Price discovery and swap to needed token occurs here
return amountOutputToken;
}
//informs the contract or a user quering whether a token can be leveraged to facilitate a sell order of an option to accomodate a buy being made in the market
function isWhitelistedToken(IERC20 token) public view returns (bool) {
if (tokenAddressWhitelisted[address(token)] == true) {
return true;
} else {
return false;
}
}
//dev Sets `amount` as the allowance of `spender` over the caller's tokens.
function approve(address spender, uint256 amount) public returns (bool) {
_depositToken.approve(spender, amount);
emit Approval(msg.sender, spender, amount);
return true;
}
// @dev transsfer Moves `amount` tokens from the caller's account to `recipient`.
function transfer(address recipient, uint256 amount) public returns (bool) {
require(poolOwnerBalance[msg.sender] >= amount, "Insufficient funds");
require(recipient != address(0), "This address does not exist");
_depositToken.transferFrom(msg.sender, recipient, amount);
poolOwnerBalance[msg.sender] = poolOwnerBalance[msg.sender].add(amount);
poolOwnerBalance[recipient] = poolOwnerBalance[recipient].sub(amount);
emit Transfer(msg.sender, recipient, amount);
return true;
}
// @dev transferfrom Moves `amount` tokens from `sender` to `recipient`,
function transferFrom(
address sender,
address recipient,
uint256 amount
) public returns (bool) {
require(poolOwnerBalance[sender] >= amount, "Insufficient funds");
require(recipient != address(0), "This address does not exist");
_depositToken.transferFrom(sender, recipient, amount);
poolOwnerBalance[sender] = poolOwnerBalance[sender].add(amount);
poolOwnerBalance[recipient] = poolOwnerBalance[recipient].sub(amount);
emit Transfer(sender, recipient, amount);
return true;
}
}
| date by which deposits can be withdrawn with rewards | function setWithdrawDate(uint256 date) public onlyOwner returns (bool) {
require(date == 0, "Owner cannot change the withdrawal date");
withdrawalDate = date;
return true;
}
| 1,754,144 |
//SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.10;
import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol';
interface IZenERC20 {
function ownerOf(uint256 _tokenId) external view returns (address);
function balanceOf(address _addr) external view returns (uint256);
function getMinter(uint256 _tokenId) external view returns (address);
function marketTransfer(
address _from,
address _to,
uint256 _nftId
) external;
}
interface IZenNFT {
function getLastMintBlock() external view returns (uint256);
function getIdForAccount(address _acc) external view returns (uint256);
function receiveRewards(uint256 _dividendRewards) external;
function burnToClaim() external;
function create(address _account, uint256 _minReq)
external
returns (uint256);
function getUnclaimed(address _account) external returns (uint256);
function canMint(address _account) external view returns (bool);
function getMinReq(uint256 _tokenId) external returns (uint256);
function getIds() external view returns (uint256[] memory);
function balanceOf(address owner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function totalSupply() external view returns (uint256);
function getOpenZenSpotsCount() external view returns (uint256);
function getZenSpotAt(uint256 _tokenId)
external
view
returns (
uint256,
uint256,
address,
uint256,
uint256
);
function myInfo()
external
view
returns (
uint256 rank,
uint256 rewards,
uint256 startMinReq,
uint256 id,
uint256 mintBlock
);
function getInfo(address _account)
external
view
returns (
uint256 rank,
uint256 level,
uint256 id
);
}
interface IRoyaltyNFT {
function handleBuy(
address _account,
uint256 _amountETH,
uint256 _tokenAmount
) external;
function getInfo(address _account)
external
view
returns (
uint256 rank,
uint256 level,
uint256 id
);
function handleSold(address _account) external;
function claim() external;
function balanceOf(address owner) external view returns (uint256 balance);
function totalSupply() external view returns (uint256);
function ownerOf(uint256 tokenId) external view returns (address owner);
function receiveRewards(uint256 _reward) external;
function myInfoFull()
external
view
returns (
uint256 rank,
uint256 level,
uint256 possibleClaimAmount,
uint256 blocksLeftToClaim,
uint256 buyVolumeETH,
uint256 sellVolumeETH,
uint256 lastLevelUpVolume,
uint256 claimedRewards
);
function getIdForAccount(address _acc) external view returns (uint256);
function getBlocksUntilClaim(address _account) external returns (uint256);
function getRights(uint256 _tokenId)
external
view
returns (
uint256,
uint256,
uint256
);
function getNextRankRights(uint256 _tokenId)
external
view
returns (
uint256,
uint256,
uint256
);
function canEvolve(address _account) external returns (bool);
function getClaimBlock(address _account) external returns (uint256);
function canMint(address _account) external view returns (bool);
function create(
address _account,
uint256 _buyVolume,
uint256 _amount
) external returns (uint256 tokenId);
function getMintPriceETH() external view returns (uint256);
function getNextMintPriceETH() external view returns (uint256);
function syncFund() external;
}
interface ICollectibleNFT {
function create(address _account, uint256 _royalId) external;
function getRarity(uint256 _tokenId) external view returns (uint256);
}
interface IRewardNFT {
function create(address _account, uint256 _zenSpotId) external;
function balanceOf(address account) external view returns (uint256);
}
interface IHelper {
function getRarity(
address _nftContract,
uint256 _nftId,
address _account
) external view returns (uint256 currentRank);
function canOwn(
address _nftContract,
uint256 _nftId,
address _account
) external view returns (bool can);
}
contract Marketplace is Ownable {
/*************
* Constants *
*************/
uint256 public PROTOCOL_LISTING_FEE;
uint256 public PROTOCOL_BUYING_FEE;
uint256 public ROYALTY_FEE;
uint256 public MIN_PRICE;
uint256 public BID_WITHDRAW_CD;
uint256 public MAX_OFFER_BLOCKS;
/*************
* Variables *
*************/
struct Offer {
uint256 nftId;
IZenERC20 nftContract;
address seller;
uint256 startPrice;
uint256 instantBuyPrice;
uint256 rarity;
uint256 madeBlock;
uint256 expiryBlock;
}
struct Bid {
Offer offer;
address bidder;
uint256 amount;
uint256 madeBlock;
}
// nftContract -> nftId
mapping(IZenERC20 => mapping(uint256 => Offer)) public offers;
mapping(IZenERC20 => mapping(uint256 => Bid)) public bids;
IZenERC20[] public whitelist;
mapping(IZenERC20 => uint256[]) public contractToIds;
IHelper public Helper;
/* Used in Getters */
struct OfferPreview {
uint256 nftId;
IZenERC20 nftContract;
uint256 madeBlock;
uint256 bidPrice;
uint256 instantBuyPrice;
uint256 rarity;
}
/**********
* Events *
**********/
event NewOffer(
IZenERC20 nftContract,
uint256 nftId,
address seller,
uint256 startPrice,
uint256 instantBuyPrice,
uint256 rarity,
uint256 expiryBlock
);
event NewBid(
IZenERC20 nftContract,
uint256 nftId,
address oldBidder,
address newBidder,
uint256 oldAmount,
uint256 newAmount
);
event AcceptedOffer(
IZenERC20 nftContract,
uint256 nftId,
address seller,
address buyer,
uint256 amount
);
event InstantBought(
IZenERC20 nftContract,
uint256 nftId,
address seller,
address buyer,
uint256 amount
);
event RemovedOffer(
IZenERC20 nftContract,
uint256 nftId,
address seller,
uint256 startPrice
);
event Refunded(
IZenERC20 nftContract,
uint256 nftId,
address bidder,
uint256 bidAmount
);
event WithdrawnBid(
IZenERC20 nftContract,
uint256 nftId,
address bidder,
uint256 amount
);
event DistributedProtocolFee(
IZenERC20 fromNftContract,
uint256 _fromNftId,
uint256 _amount
);
event DistributedRoyalty(
IZenERC20 nftContract,
uint256 nftId,
address _toMinter,
uint256 _amount
);
event OwnershipChanged(
IZenERC20 nftContract,
uint256 nftId,
address _from,
address _to,
uint256 _amount
);
event Purged(IZenERC20 nftContract, uint256 nftId, bool ownershipChanged);
event ExtendedOffer(
IZenERC20 nftContract,
uint256 nftId,
uint256 newExpiryBlock,
uint256 extendedWith
);
constructor(address _helperAddr) {
Helper = IHelper(_helperAddr);
MIN_PRICE = 5e17;
PROTOCOL_LISTING_FEE = 1e16;
// 2%, 3%
PROTOCOL_BUYING_FEE = 200;
ROYALTY_FEE = 300;
// 3h
BID_WITHDRAW_CD = 1200 * 3;
// ~ 2 months
MAX_OFFER_BLOCKS = 28800 * 60;
}
/**********************
* Function Modifiers *
**********************/
uint256 private unlocked = 1;
modifier antiReentrant() {
require(unlocked == 1, 'ERROR: Anti-Reentrant');
unlocked = 0;
_;
unlocked = 1;
}
modifier onlyWhitelisted(IZenERC20 _nftContract) {
require(address(_nftContract) != address(0), 'ERROR: Zero address');
require(this.inWhitelist(_nftContract), 'ERROR: Not Whitelisted');
_;
}
function inWhitelist(IZenERC20 _nftContract) public view returns (bool) {
uint256 l = whitelist.length;
if (l == 0) {
return false;
}
for (uint256 i = 0; i < l; i++) {
if (address(whitelist[i]) == address(_nftContract)) {
return true;
}
}
return false;
}
/* --------- CREATE --------- */
function offerNftForSale(
IZenERC20 _nftContract,
uint256 _nftId,
uint256 _startPrice,
uint256 _instantBuyPrice
) external payable antiReentrant onlyWhitelisted(_nftContract) {
require(msg.sender == tx.origin, 'EOA');
// EXACT FEE not more otherwise STUCK
require(msg.value == PROTOCOL_LISTING_FEE, 'Not correct listing fee.');
require(
offers[_nftContract][_nftId].seller == address(0),
'Already listed !'
);
require(_startPrice < 1e24 && _instantBuyPrice < 1e24, "Don't Troll");
address ownerOfNftId = _nftContract.ownerOf(_nftId);
require(msg.sender == ownerOfNftId, 'Not NFT Owner');
require(ownerOfNftId != address(0), '0 address');
require(_startPrice >= MIN_PRICE, 'Min. Price');
require(
_instantBuyPrice >= _startPrice,
'Instant Buy Should be bigger than bid start price'
);
uint256 rarity = getRarity(address(_nftContract), _nftId, msg.sender);
// Listing Fee
payable(this.owner()).transfer(PROTOCOL_LISTING_FEE);
uint256 expiryBlock = block.number + MAX_OFFER_BLOCKS;
offers[_nftContract][_nftId] = Offer({
nftId: _nftId,
nftContract: _nftContract,
seller: msg.sender,
startPrice: _startPrice,
instantBuyPrice: _instantBuyPrice,
madeBlock: block.number,
expiryBlock: expiryBlock,
rarity: rarity
});
contractToIds[_nftContract].push(_nftId);
emit NewOffer(
_nftContract,
_nftId,
msg.sender,
_startPrice,
_instantBuyPrice,
rarity,
expiryBlock
);
emit DistributedProtocolFee(_nftContract, _nftId, PROTOCOL_LISTING_FEE);
}
/* --------- DELETE --------- */
function removeOffer(IZenERC20 _nftContract, uint256 _nftId)
external
antiReentrant
onlyWhitelisted(_nftContract)
{
require(msg.sender == tx.origin, 'EOA');
address ownerOfNftId = _nftContract.ownerOf(_nftId);
require(ownerOfNftId != address(0), '0 address');
require(msg.sender == ownerOfNftId, 'Not NFT Owner');
deleteOffer(_nftContract, _nftId);
refundBidder(_nftContract, _nftId);
}
function refundBidder(IZenERC20 _nftContract, uint256 _nftId)
internal
returns (bool success)
{
Bid memory bid = bids[_nftContract][_nftId];
if (bid.amount > 0) {
payable(bid.bidder).transfer(bid.amount);
delete bids[_nftContract][_nftId];
emit Refunded(_nftContract, _nftId, bid.bidder, bid.amount);
return true;
}
return false;
}
function deleteOffer(IZenERC20 _nftContract, uint256 _nftId) internal {
Offer memory offer = offers[_nftContract][_nftId];
delete offers[_nftContract][_nftId];
bool success = removeOfferAt(_nftContract, _nftId);
require(success, "wasn't able to remove");
emit RemovedOffer(_nftContract, _nftId, offer.seller, offer.startPrice);
}
function removeOfferAt(IZenERC20 _nftContract, uint256 _nftId)
internal
returns (bool)
{
uint256 length = contractToIds[_nftContract].length;
if (length == 0) {
return false;
}
if (contractToIds[_nftContract][length - 1] == _nftId) {
contractToIds[_nftContract].pop();
return true;
}
bool found = false;
for (uint256 i = 0; i < length - 1; i++) {
if (contractToIds[_nftContract][i] == _nftId) {
found = true;
}
if (found) {
contractToIds[_nftContract][i] = contractToIds[_nftContract][
i + 1
];
}
}
if (found) {
contractToIds[_nftContract].pop();
}
return found;
}
/* --------- BUY & BID --------- */
function buyNft(IZenERC20 _nftContract, uint256 _nftId)
external
payable
antiReentrant
{
require(msg.sender == tx.origin, 'EOA');
Offer memory offer = offers[_nftContract][_nftId];
require(offer.seller != msg.sender, 'Cant buy your own offer');
bool canOwn = Helper.canOwn(address(_nftContract), _nftId, msg.sender);
require(canOwn, 'Your account cant own any more nfts of this type !');
(
uint256 amountToSeller,
uint256 amountFromBuyer,
uint256 serviceFee,
uint256 royaltyFee
) = this.getFinalBuyPrice(_nftContract, _nftId);
require(msg.value == amountFromBuyer, 'Not exact instantBuy price');
// 1) Send NFT, 2) Send Fees
transferNftAndFees(
_nftContract,
_nftId,
serviceFee,
royaltyFee,
offer.seller,
msg.sender
);
payable(offer.seller).transfer(amountToSeller);
deleteOffer(_nftContract, _nftId);
refundBidder(_nftContract, _nftId);
emit InstantBought(
_nftContract,
_nftId,
offer.seller,
msg.sender,
msg.value
);
}
function enterBid(IZenERC20 _nftContract, uint256 _nftId)
external
payable
antiReentrant
{
require(msg.value > MIN_PRICE, 'No value');
require(msg.value < 1e24, 'ERROR_TOO_MUCH_FOMO');
require(msg.sender == tx.origin, 'EOA');
Offer memory offer = offers[_nftContract][_nftId];
Bid memory existingBid = bids[_nftContract][_nftId];
// Get Minimum Bid For NFT
// if no bid, existing is 0
require(
msg.value > this.getMinimumBidAmount(_nftContract, _nftId),
'Less than current bid or starting price'
);
require(offer.seller != msg.sender, 'Cant bid on your offers !');
bool canOwn = Helper.canOwn(address(_nftContract), _nftId, msg.sender);
require(canOwn, 'Your account cant own any more nfts of this type !');
// Refund the PREVIOUS bid
if (existingBid.bidder != address(0)) {
payable(existingBid.bidder).transfer(existingBid.amount);
emit Refunded(
_nftContract,
_nftId,
existingBid.bidder,
existingBid.amount
);
}
bids[_nftContract][_nftId].bidder = msg.sender;
bids[_nftContract][_nftId].amount = msg.value;
bids[_nftContract][_nftId].madeBlock = block.number;
//protocol fee is included in msg.value
emit NewBid(
_nftContract,
_nftId,
existingBid.bidder,
msg.sender,
existingBid.amount,
msg.value
);
// If bid price >= Instant Buy Price => Make Buy Automatically
uint256 instBuyPrice = offer.instantBuyPrice;
if (msg.value >= instBuyPrice) {
handleAccept(
_nftContract,
_nftId,
instBuyPrice,
offer.seller,
msg.sender
);
emit InstantBought(
_nftContract,
_nftId,
offer.seller,
msg.sender,
instBuyPrice
);
uint256 toRefundIfAny = msg.value - instBuyPrice;
if (toRefundIfAny > 10000 wei) {
payable(msg.sender).transfer(toRefundIfAny);
}
} else {
// max = 7h
uint256 maxExtendedToBlock = offer.madeBlock +
MAX_OFFER_BLOCKS +
7200;
uint256 extendBlocks = 200;
// If Bid is made in last 200blocks before expiry
// And is before max extend period
// Increase offer expiry by 10 minutes
// Untill Max Extend Block Reached
if (
block.number >= offer.expiryBlock - extendBlocks &&
offer.expiryBlock + extendBlocks <= maxExtendedToBlock
) {
offers[_nftContract][_nftId].expiryBlock =
offer.expiryBlock +
extendBlocks;
emit ExtendedOffer(
_nftContract,
_nftId,
offers[_nftContract][_nftId].expiryBlock,
extendBlocks
);
}
}
}
/* Sends NFT & Distributes fees */
function transferNftAndFees(
IZenERC20 _nftContract,
uint256 _nftId,
uint256 _serviceFee,
uint256 _royaltyFee,
address _from,
address _to
) internal {
IZenERC20 NftContract = IZenERC20(_nftContract);
// Royalty Payout
address minter = NftContract.getMinter(_nftId);
payable(minter).transfer(_royaltyFee);
// Service Fee
payable(this.owner()).transfer(_serviceFee);
// Send Nft to msg.sender [ buyer ]
NftContract.marketTransfer(_from, _to, _nftId);
// Ensure transfer from worked
// Ensure ownership is changed
address newOwner = NftContract.ownerOf(_nftId);
require(newOwner == _to, "Buyer didn't receive his NFT");
emit DistributedProtocolFee(_nftContract, _nftId, _serviceFee);
emit DistributedRoyalty(_nftContract, _nftId, minter, _royaltyFee);
}
function acceptBid(IZenERC20 _nftContract, uint256 _nftId)
external
antiReentrant
{
Offer memory offer = offers[_nftContract][_nftId];
require(msg.sender == offer.seller, 'Not your offer !');
address nftOwner = _nftContract.ownerOf(_nftId);
require(nftOwner != address(0), '0 address');
require(msg.sender == nftOwner, 'Not NFT Owner');
Bid memory bid = bids[_nftContract][_nftId];
require(bid.amount > 0, 'No bids');
handleAccept(
_nftContract,
_nftId,
bid.amount,
offer.seller,
bid.bidder
);
}
function autoAcceptBid(IZenERC20 _nftContract, uint256 _nftId)
external
antiReentrant
{
Offer memory offer = offers[_nftContract][_nftId];
Bid memory bid = bids[_nftContract][_nftId];
require(bid.amount > 0, 'No bids');
require(block.number >= offer.expiryBlock, 'Not time yet !');
handleAccept(
_nftContract,
_nftId,
bid.amount,
offer.seller,
bid.bidder
);
}
function handleAccept(
IZenERC20 _nftContract,
uint256 _nftId,
uint256 amount,
address seller,
address buyer
) internal {
uint256 serviceFee = (amount * PROTOCOL_BUYING_FEE) / 10000;
uint256 royaltyFee = (amount * ROYALTY_FEE) / 10000;
uint256 amountToSeller = amount - royaltyFee - serviceFee;
deleteOffer(_nftContract, _nftId);
delete bids[_nftContract][_nftId];
transferNftAndFees(
_nftContract,
_nftId,
serviceFee,
royaltyFee,
seller,
buyer
);
payable(seller).transfer(amountToSeller);
emit AcceptedOffer(_nftContract, _nftId, seller, buyer, amount);
}
function withdrawBid(IZenERC20 _nftContract, uint256 _nftId)
external
antiReentrant
{
Bid memory bid = bids[_nftContract][_nftId];
require(bid.bidder == msg.sender, "You're not the bidder !");
require(
block.number >= bid.madeBlock + BID_WITHDRAW_CD,
"Can't withdraw yet !"
);
delete bids[_nftContract][_nftId];
// Refund the bid
payable(msg.sender).transfer(bid.amount);
emit WithdrawnBid(_nftContract, _nftId, msg.sender, bid.amount);
}
/* --------- PURGE --------- Ensures the safety of the marketplace */
function getShouldPurge(Offer memory offer)
external
view
returns (
bool should,
bool ownership,
bool rank
)
{
try IZenERC20(offer.nftContract).ownerOf(offer.nftId) returns (
address theOwner
) {
ownership = offer.seller != theOwner;
rank =
offer.rarity !=
getRarity(
address(offer.nftContract),
offer.nftId,
offer.seller
);
should = ownership || rank;
return (should, ownership, rank);
} catch {
return (true, true, false);
}
}
function getPurgeCount() public view returns (uint256 countP) {
uint256 count;
uint256 l;
uint256 id;
Offer memory offer;
for (uint256 c = 0; c < whitelist.length; c++) {
IZenERC20 contr = whitelist[c];
l = contractToIds[contr].length;
for (uint256 i = 0; i < l; i++) {
id = contractToIds[contr][i];
offer = offers[contr][id];
(bool should, , ) = this.getShouldPurge(offer);
if (should) {
count++;
}
}
}
return count;
}
function checkPurge()
external
view
returns (
bool shouldPurge,
address[] memory contracts,
uint256[] memory ids
)
{
uint256 l = getPurgeCount();
if (l == 0) {
return (false, new address[](0), new uint256[](0));
}
address[] memory foundContracts = new address[](l);
uint256[] memory foundIds = new uint256[](l);
uint256 count;
for (uint256 c = 0; c < whitelist.length; c++) {
IZenERC20 contr = whitelist[c];
uint256 f = contractToIds[contr].length;
for (uint256 i = 0; i < f; i++) {
uint256 id = contractToIds[contr][i];
Offer memory offer = offers[contr][id];
(bool should, , ) = this.getShouldPurge(offer);
if (should) {
foundContracts[count] = address(offer.nftContract);
foundIds[count] = id;
count++;
}
}
}
return (count != 0, foundContracts, foundIds);
}
function purgeOffer(IZenERC20 _nftContract, uint256 _nftId) external {
Offer memory offer = offers[_nftContract][_nftId];
(bool should, bool ownership, ) = this.getShouldPurge(offer);
if (should) {
deleteOffer(offer.nftContract, _nftId);
refundBidder(offer.nftContract, _nftId);
emit Purged(offer.nftContract, _nftId, ownership);
}
}
/* --- GETTERS --- */
function getRarity(
address _nftContract,
uint256 _nftId,
address _account
) public view returns (uint256 currentRank) {
return Helper.getRarity(_nftContract, _nftId, _account);
}
function getOfferMadeBlockAndExpiry(IZenERC20 _nftContract, uint256 _nftId)
external
view
returns (uint256 _madeBlock, uint256 _expiryBlock)
{
return (
offers[_nftContract][_nftId].madeBlock,
offers[_nftContract][_nftId].expiryBlock
);
}
// Gets the amount of the minimum bid per Nft id
function getMinimumBidAmount(IZenERC20 _nftContract, uint256 _nftId)
external
view
returns (uint256 _nextPossibleAmt)
{
Offer memory offer = offers[_nftContract][_nftId];
Bid memory existingBid = bids[_nftContract][_nftId];
if (existingBid.amount == 0) {
// No Bid
return offer.startPrice;
}
return existingBid.amount;
}
function getFinalBuyPrice(IZenERC20 _nftContract, uint256 _nftId)
external
view
returns (
uint256 amountToSeller,
uint256 amountFromBuyer,
uint256 serviceFee,
uint256 royaltyFee
)
{
uint256 buyPrice = offers[_nftContract][_nftId].instantBuyPrice;
serviceFee = (buyPrice * PROTOCOL_BUYING_FEE) / 10000;
royaltyFee = (buyPrice * ROYALTY_FEE) / 10000;
amountToSeller = buyPrice - royaltyFee - serviceFee;
return (amountToSeller, buyPrice, serviceFee, royaltyFee);
}
function getAllContracts() public view returns (address[] memory) {
uint256 l = whitelist.length;
address[] memory contracts = new address[](l);
for (uint256 i = 0; i < l; i++) {
contracts[i] = address(whitelist[i]);
}
return contracts;
}
function getIds(IZenERC20 _nftContract)
public
view
returns (uint256[] memory ids)
{
ids = contractToIds[_nftContract];
return ids;
}
/* --------- BIDS --------- */
function getBidsCountForAccount(address _account)
public
view
returns (uint256 count)
{
uint256 whiteL = whitelist.length;
uint256 l;
uint256 id;
Bid memory bid;
for (uint256 c = 0; c < whiteL; c++) {
IZenERC20 contr = whitelist[c];
l = contractToIds[contr].length;
for (uint256 i = 0; i < l; i++) {
id = contractToIds[contr][i];
bid = bids[contr][id];
if (bid.bidder == _account) {
count++;
}
}
}
return count;
}
function getBidsForAccount(address _account, uint256 _count)
public
view
returns (
address[] memory contracts,
uint256[] memory ids,
uint256[] memory amounts,
uint256[] memory madeBlocks
)
{
if (_count == 0) {
_count = getBidsCountForAccount(_account);
}
contracts = new address[](_count);
ids = new uint256[](_count);
amounts = new uint256[](_count);
madeBlocks = new uint256[](_count);
if (_count == 0) {
return (contracts, ids, amounts, madeBlocks);
}
uint256 whiteL = whitelist.length;
uint256 l;
uint256 id;
Bid memory bid;
uint256 foundCount;
for (uint256 c = 0; c < whiteL; c++) {
IZenERC20 contr = whitelist[c];
l = contractToIds[contr].length;
for (uint256 i = 0; i < l; i++) {
id = contractToIds[contr][i];
bid = bids[contr][id];
if (bid.bidder == _account) {
contracts[foundCount] = address(contr);
ids[foundCount] = id;
amounts[foundCount] = bid.amount;
madeBlocks[foundCount] = bid.madeBlock;
foundCount++;
}
}
}
return (contracts, ids, amounts, madeBlocks);
}
/* --------- OFFERS --------- */
function getOffersCount() public view returns (uint256 count) {
uint256 l = whitelist.length;
for (uint256 i = 0; i < l; i++) {
count += contractToIds[whitelist[i]].length;
}
return count;
}
function getOffers(
uint256 start,
uint256 count,
uint256 sortBy,
bool highToLow
)
public
view
returns (
address[] memory contracts,
uint256[] memory ids,
uint256 totalCount
)
{
// Always with full length. If filters are passed --> replaces the first X items and overrides the "l" --> everything after l is ignored
IZenERC20[] memory contractList = whitelist;
uint256 totalL;
uint256 l = whitelist.length;
for (uint256 i = 0; i < l; i++) {
totalL += contractToIds[contractList[i]].length;
}
if (start == 0 && count == 0) {
// Client wants all.
count = totalL;
} else {
require(start < totalL, 'No items');
}
OfferPreview[] memory preview = getOfferPreview(
totalL,
l,
contractList
);
{
// Sorts by mutating the preview[]
if (sortBy == 1) {
quickSortBlock(preview);
} else if (sortBy == 2) {
quickSortBid(preview);
} else if (sortBy == 3) {
quickSortBuyPrice(preview);
} else if (sortBy == 4) {
quickSortRarity(preview);
}
}
uint256 returnL = count;
uint256 end = start + count;
if (end > totalL) {
end = totalL;
returnL = totalL - start;
}
return getResult(start, end, totalL, returnL, preview, highToLow);
}
function getOffersWithFilter(
address[] calldata _nftContracts,
uint256 start,
uint256 count,
uint256 sortBy,
bool highToLow
)
public
view
returns (
address[] memory contracts,
uint256[] memory ids,
uint256 totalCount
)
{
// Always with full length. If filters are passed --> replaces the first X items and overrides the "l" --> everything after l is ignored
uint256 totalL;
uint256 l = _nftContracts.length;
IZenERC20[] memory contractList = new IZenERC20[](l);
for (uint256 i = 0; i < l; i++) {
contractList[i] = IZenERC20(_nftContracts[i]);
}
for (uint256 i = 0; i < l; i++) {
totalL += contractToIds[contractList[i]].length;
}
if (start == 0 && count == 0) {
// Client wants all.
count = totalL;
} else {
require(start < totalL, 'No items');
}
OfferPreview[] memory preview = getOfferPreview(
totalL,
l,
contractList
);
{
// Sorts by mutating the preview[]
if (sortBy == 1) {
quickSortBlock(preview);
} else if (sortBy == 2) {
quickSortBid(preview);
} else if (sortBy == 3) {
quickSortBuyPrice(preview);
} else if (sortBy == 4) {
quickSortRarity(preview);
}
}
uint256 returnL = count;
uint256 end = start + count;
if (end > totalL) {
end = totalL;
returnL = totalL - start;
}
return getResult(start, end, totalL, returnL, preview, highToLow);
}
function getOfferPreview(
uint256 totalL,
uint256 l,
IZenERC20[] memory contractList
) internal view returns (OfferPreview[] memory) {
OfferPreview[] memory preview = new OfferPreview[](totalL);
uint256 currL;
for (uint256 i = 0; i < l; i++) {
IZenERC20 contr = contractList[i];
uint256 idL = contractToIds[contr].length;
for (uint256 j = 0; j < idL; j++) {
uint256 nftId = contractToIds[contr][j];
uint256 bidPrice = bids[contr][nftId].amount;
if (bidPrice == 0) {
bidPrice = offers[contr][nftId].startPrice;
}
preview[currL] = OfferPreview({
nftId: nftId,
nftContract: contr,
madeBlock: offers[contr][nftId].madeBlock,
rarity: offers[contr][nftId].rarity,
instantBuyPrice: offers[contr][nftId].instantBuyPrice,
bidPrice: bidPrice
});
currL++;
}
}
return preview;
}
function getResult(
uint256 _start,
uint256 _end,
uint256 _totalL,
uint256 _returnL,
OfferPreview[] memory _preview,
bool _highToLow
)
internal
view
returns (
address[] memory contracts,
uint256[] memory ids,
uint256 totalCount
)
{
address[] memory addresses = new address[](_returnL);
uint256[] memory ids = new uint256[](_returnL);
uint256 cl;
if (_highToLow) {
uint256 index;
for (uint256 i = _start; i < _end; i++) {
index = _totalL - i - 1;
addresses[cl] = address(_preview[index].nftContract);
ids[cl] = _preview[index].nftId;
cl++;
}
} else {
for (uint256 i = _start; i < _end; i++) {
addresses[cl] = address(_preview[i].nftContract);
ids[cl] = _preview[i].nftId;
cl++;
}
}
return (addresses, ids, _totalL);
}
/********
* SORT *
********/
function quickSortBlock(OfferPreview[] memory preview) internal pure {
if (preview.length > 1) {
quickByBlock(preview, 0, preview.length - 1);
}
}
function quickSortBid(OfferPreview[] memory preview) internal pure {
if (preview.length > 1) {
quickByBid(preview, 0, preview.length - 1);
}
}
function quickSortBuyPrice(OfferPreview[] memory preview) internal pure {
if (preview.length > 1) {
quickByBuyPrice(preview, 0, preview.length - 1);
}
}
function quickSortRarity(OfferPreview[] memory preview) internal pure {
if (preview.length > 1) {
quickByRarity(preview, 0, preview.length - 1);
}
}
function quickByBlock(
OfferPreview[] memory preview,
uint256 _low,
uint256 _high
) internal pure {
if (_low < _high) {
uint256 pivotVal = preview[(_low + _high) / 2].madeBlock;
uint256 low1 = _low;
uint256 high1 = _high;
for (;;) {
while (preview[low1].madeBlock < pivotVal) low1++;
while (preview[high1].madeBlock > pivotVal) high1--;
if (low1 >= high1) {
break;
}
(preview[low1], preview[high1]) = (
preview[high1],
preview[low1]
);
low1++;
high1--;
}
if (_low < high1) {
quickByBlock(preview, _low, high1);
}
high1++;
if (high1 < _high) {
quickByBlock(preview, high1, _high);
}
}
}
function quickByBid(
OfferPreview[] memory preview,
uint256 _low,
uint256 _high
) internal pure {
if (_low < _high) {
uint256 pivotVal = preview[(_low + _high) / 2].bidPrice;
uint256 low1 = _low;
uint256 high1 = _high;
for (;;) {
while (preview[low1].bidPrice < pivotVal) low1++;
while (preview[high1].bidPrice > pivotVal) high1--;
if (low1 >= high1) {
break;
}
(preview[low1], preview[high1]) = (
preview[high1],
preview[low1]
);
low1++;
high1--;
}
if (_low < high1) {
quickByBid(preview, _low, high1);
}
high1++;
if (high1 < _high) {
quickByBid(preview, high1, _high);
}
}
}
function quickByBuyPrice(
OfferPreview[] memory preview,
uint256 _low,
uint256 _high
) internal pure {
if (_low < _high) {
uint256 pivotVal = preview[(_low + _high) / 2].instantBuyPrice;
uint256 low1 = _low;
uint256 high1 = _high;
for (;;) {
while (preview[low1].instantBuyPrice < pivotVal) low1++;
while (preview[high1].instantBuyPrice > pivotVal) high1--;
if (low1 >= high1) {
break;
}
(preview[low1], preview[high1]) = (
preview[high1],
preview[low1]
);
low1++;
high1--;
}
if (_low < high1) {
quickByBuyPrice(preview, _low, high1);
}
high1++;
if (high1 < _high) {
quickByBuyPrice(preview, high1, _high);
}
}
}
function quickByRarity(
OfferPreview[] memory preview,
uint256 _low,
uint256 _high
) internal pure {
if (_low < _high) {
uint256 pivotVal = preview[(_low + _high) / 2].rarity;
uint256 low1 = _low;
uint256 high1 = _high;
for (;;) {
while (preview[low1].rarity < pivotVal) low1++;
while (preview[high1].rarity > pivotVal) high1--;
if (low1 >= high1) {
break;
}
(preview[low1], preview[high1]) = (
preview[high1],
preview[low1]
);
low1++;
high1--;
}
if (_low < high1) {
quickByRarity(preview, _low, high1);
}
high1++;
if (high1 < _high) {
quickByRarity(preview, high1, _high);
}
}
}
/*******************************
* Authorized Setter Functions *
*******************************/
function setProtocolValues(
uint256 _listingFee,
uint256 _buyingFee,
uint256 _floor,
uint256 _royalty
) external onlyOwner {
PROTOCOL_LISTING_FEE = _listingFee;
PROTOCOL_BUYING_FEE = _buyingFee;
MIN_PRICE = _floor;
ROYALTY_FEE = _royalty;
}
function addToWhitelist(IZenERC20 _nftContract) external onlyOwner {
require(inWhitelist(_nftContract) == false, 'Already in whitelist');
uint256 l = whitelist.length;
bool replaced = false;
for (uint256 i = 0; i < l; i++) {
if (address(whitelist[i]) == address(0)) {
whitelist[i] = _nftContract;
replaced = true;
}
}
if (!replaced) {
whitelist.push(_nftContract);
}
}
function removeFromWhite(IZenERC20 _nftContract)
external
onlyOwner
onlyWhitelisted(_nftContract)
{
uint256 l = whitelist.length;
for (uint256 i = 0; i < l; i++) {
if (address(whitelist[l]) == address(_nftContract)) {
delete whitelist[l];
}
}
}
function setHelperAddress(address _helperAddr) external onlyOwner {
require(_helperAddr != address(0), 'Zero Addr');
Helper = IHelper(_helperAddr);
}
function setCd(uint256 _bidCd, uint256 _maxOBlocks) external onlyOwner {
BID_WITHDRAW_CD = _bidCd;
MAX_OFFER_BLOCKS = _maxOBlocks;
}
// When v2 is released
function massBidRefund() external onlyOwner {
uint256 l = whitelist.length;
for (uint256 i = 0; i < l; i++) {
uint256 idsL = contractToIds[whitelist[i]].length;
for (uint256 j = 0; j < idsL; j++) {
refundBidder(whitelist[i], contractToIds[whitelist[i]][j]);
}
}
}
// In case massBidRefund reverts for some reason
function tryMassRefund() external onlyOwner {
try this.massBidRefund() {} catch {
payable(owner()).transfer(address(this).balance);
}
}
// Deal with ETH
fallback() external payable {}
receive() external payable {}
}
| --------- BUY & BID --------- / 1) Send NFT, 2) Send Fees | function buyNft(IZenERC20 _nftContract, uint256 _nftId)
external
payable
antiReentrant
{
require(msg.sender == tx.origin, 'EOA');
Offer memory offer = offers[_nftContract][_nftId];
require(offer.seller != msg.sender, 'Cant buy your own offer');
bool canOwn = Helper.canOwn(address(_nftContract), _nftId, msg.sender);
require(canOwn, 'Your account cant own any more nfts of this type !');
(
uint256 amountToSeller,
uint256 amountFromBuyer,
uint256 serviceFee,
uint256 royaltyFee
) = this.getFinalBuyPrice(_nftContract, _nftId);
require(msg.value == amountFromBuyer, 'Not exact instantBuy price');
transferNftAndFees(
_nftContract,
_nftId,
serviceFee,
royaltyFee,
offer.seller,
msg.sender
);
payable(offer.seller).transfer(amountToSeller);
deleteOffer(_nftContract, _nftId);
refundBidder(_nftContract, _nftId);
emit InstantBought(
_nftContract,
_nftId,
offer.seller,
msg.sender,
msg.value
);
}
| 15,842,297 |
./full_match/56/0x422ec55a4ca16e3e4C41Fd6BBa86919Ae6733a35/sources/project:/contracts/BIOZAffiliateOne.sol | Function to update pass price with signature verification Create a unique message hash incorporating nonce and uid Verify that the signature has not been used before Verify the signature Calculate the new price as the difference between the current and old price Update user's pass counts Decrement the count for the previous pass | function updatePass(uint256 passId, uint256 previousPassId, uint256 nonce, string memory uid, bytes memory signature, string memory userId) external {
require(passId > 0 && passId < passPrices.length, "Invalid pass ID");
require(previousPassId == 0 || userPassCounts[msg.sender][previousPassId] > 0, "No previous pass purchased");
bytes32 messageHash = keccak256(abi.encodePacked(msg.sender, passId, previousPassId, nonce, uid));
require(!usedSignatures[signature], "Signature has already been used");
address recoveredSigner = ECDSA.recover(messageHash, signature);
require(recoveredSigner == owner, "Signature verification failed");
uint256 newPrice = passPrices[passId] - passPrices[previousPassId];
require(
usdtToken.transferFrom(msg.sender, address(this), newPrice),
"USDT transfer failed"
);
uint256 fortyFivePercentAmount = (newPrice * 45) / 100;
require(usdtToken.transfer(company, fortyFivePercentAmount), "Transfer to company failed");
if (previousPassId > 0) {
userPassCounts[msg.sender][previousPassId]--;
}
}
| 3,241,375 |
//Address: 0x25b16c95f3ebb1d8583a1c173f81257bc916a9be
//Contract name: SignalsCrowdsale
//Balance: 0 Ether
//Verification Date: 3/12/2018
//Transacion Count: 1706
// CODE STARTS HERE
pragma solidity ^0.4.20;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
/**
* @title Pausable token
*
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will 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;
}
}
/*
* Company reserve pool where the tokens will be locked for two years
* @title Company token reserve
*/
contract AdviserTimeLock is Ownable{
SignalsToken token;
uint256 withdrawn;
uint start;
event TokensWithdrawn(address owner, uint amount);
/*
* Constructor changing owner to owner multisig & setting time lock
* @param address of the Signals Token contract
* @param address of the owner multisig
*/
function AdviserTimeLock(address _token, address _owner) public{
token = SignalsToken(_token);
owner = _owner;
start = now;
}
/*
* Only function for periodical tokens withdrawal (with monthly allowance)
* @dev Will withdraw the whole allowance;
*/
function withdraw() onlyOwner public {
require(now - start >= 25920000);
uint toWithdraw = canWithdraw();
token.transfer(owner, toWithdraw);
withdrawn += toWithdraw;
TokensWithdrawn(owner, toWithdraw);
}
/*
* Only function for the tokens withdrawal (with two years time lock)
* @dev Based on division down rounding
*/
function canWithdraw() public view returns (uint256) {
uint256 sinceStart = now - start;
uint256 allowed = (sinceStart/2592000)*504546000000000;
uint256 toWithdraw;
if (allowed > token.balanceOf(address(this))) {
toWithdraw = token.balanceOf(address(this));
} else {
toWithdraw = allowed - withdrawn;
}
return toWithdraw;
}
/*
* Function to clean up the state and moved not allocated tokens to custody
*/
function cleanUp() onlyOwner public {
require(token.balanceOf(address(this)) == 0);
selfdestruct(owner);
}
}
/*
* Pre-allocation pool for company advisers
* @title Advisory pool
*/
contract AdvisoryPool is Ownable{
SignalsToken token;
/*
* @dev constant addresses of all advisers
*/
address constant ADVISER1 = 0x7915D5A865FE68C63112be5aD3DCA5187EB08f24;
address constant ADVISER2 = 0x31cFF39AA68B91fa7C957272A6aA8fB8F7b69Cb0;
address constant ADVISER3 = 0x358b3aeec9fae5ab15fe28d2fe6c7c9fda596857;
address constant ADVISER4 = 0x1011FC646261eb5d4aB875886f1470d4919d83c8;
address constant ADVISER5 = 0xcc04Cd98da89A9172372aEf4B62BEDecd01A7F5a;
address constant ADVISER6 = 0xECD791f8E548D46A9711D853Ead7edC685Ca4ee8;
address constant ADVISER7 = 0x38B58e5783fd4D077e422B3362E9d6B265484e3f;
address constant ADVISER8 = 0x2934205135A129F995AC891C143cCae83ce175c7;
address constant ADVISER9 = 0x9F5D00F4A383bAd14DEfA9aee53C5AF2ad9ad32F;
address constant ADVISER10 = 0xBE993c982Fc5a0C0360CEbcEf9e4d2727339d96B;
address constant ADVISER11 = 0xdf1E2126eB638335eFAb91a834db4c57Cbe18735;
address constant ADVISER12 = 0x8A404969Ad1BCD3F566A7796722f535eD9cA22b2;
address constant ADVISER13 = 0x066a8aD6fA94AC83e1AFB5Aa7Dc62eD1D2654bB2;
address constant ADVISER14 = 0xA1425Fa987d1b724306d93084b93D62F37482c4b;
address constant ADVISER15 = 0x4633515904eE5Bc18bEB70277455525e84a51e90;
address constant ADVISER16 = 0x230783Afd438313033b07D39E3B9bBDBC7817759;
address constant ADVISER17 = 0xe8b9b07c1cca9aE9739Cec3D53004523Ab206CAc;
address constant ADVISER18 = 0x0E73f16CfE7F545C0e4bB63A9Eef18De8d7B422d;
address constant ADVISER19 = 0x6B4c6B603ca72FE7dde971CF833a58415737826D;
address constant ADVISER20 = 0x823D3123254a3F9f9d3759FE3Fd7d15e21a3C5d8;
address constant ADVISER21 = 0x0E48bbc496Ae61bb790Fc400D1F1a57520f772Df;
address constant ADVISER22 = 0x06Ee8eCc0145CcaCEc829490e3c557f577BE0e85;
address constant ADVISER23 = 0xbE56bFF75A1cB085674Cc37a5C8746fF6C43C442;
address constant ADVISER24 = 0xb442b5297E4aEf19E489530E69dFef7fae27F4A5;
address constant ADVISER25 = 0x50EF1d6a7435C7FB3dB7c204b74EB719b1EE3dab;
address constant ADVISER26 = 0x3e9fed606822D5071f8a28d2c8B51E6964160CB2;
AdviserTimeLock public tokenLocker23;
/*
* Constructor changing owner to owner multisig & calling the allocation
* @param address of the Signals Token contract
* @param address of the owner multisig
*/
function AdvisoryPool(address _token, address _owner) public {
owner = _owner;
token = SignalsToken(_token);
}
/*
* Allocation function, tokens get allocated from this contract as current token owner
* @dev only accessible from the constructor
*/
function initiate() public onlyOwner {
require(token.balanceOf(address(this)) == 18500000000000000);
tokenLocker23 = new AdviserTimeLock(address(token), ADVISER23);
token.transfer(ADVISER1, 380952380000000);
token.transfer(ADVISER2, 380952380000000);
token.transfer(ADVISER3, 659200000000000);
token.transfer(ADVISER4, 95238100000000);
token.transfer(ADVISER5, 1850000000000000);
token.transfer(ADVISER6, 15384620000000);
token.transfer(ADVISER7, 62366450000000);
token.transfer(ADVISER8, 116805560000000);
token.transfer(ADVISER9, 153846150000000);
token.transfer(ADVISER10, 10683760000000);
token.transfer(ADVISER11, 114285710000000);
token.transfer(ADVISER12, 576923080000000);
token.transfer(ADVISER13, 76190480000000);
token.transfer(ADVISER14, 133547010000000);
token.transfer(ADVISER15, 96153850000000);
token.transfer(ADVISER16, 462500000000000);
token.transfer(ADVISER17, 462500000000000);
token.transfer(ADVISER18, 399865380000000);
token.transfer(ADVISER19, 20032050000000);
token.transfer(ADVISER20, 35559130000000);
token.transfer(ADVISER21, 113134000000000);
token.transfer(ADVISER22, 113134000000000);
token.transfer(address(tokenLocker23), 5550000000000000);
token.transfer(ADVISER23, 1850000000000000);
token.transfer(ADVISER24, 100000000000000);
token.transfer(ADVISER25, 100000000000000);
token.transfer(ADVISER26, 2747253000000000);
}
/*
* Clean up function for token loss prevention and cleaning up Ethereum blockchain
* @dev call to clean up the contract
*/
function cleanUp() onlyOwner public {
uint256 notAllocated = token.balanceOf(address(this));
token.transfer(owner, notAllocated);
selfdestruct(owner);
}
}
/*
* Pre-allocation pool for the community, will be govern by a company multisig
* @title Community pool
*/
contract CommunityPool is Ownable{
SignalsToken token;
event CommunityTokensAllocated(address indexed member, uint amount);
/*
* Constructor changing owner to owner multisig
* @param address of the Signals Token contract
* @param address of the owner multisig
*/
function CommunityPool(address _token, address _owner) public{
token = SignalsToken(_token);
owner = _owner;
}
/*
* Function to alloc tokens to a community member
* @param address of community member
* @param uint amount units of tokens to be given away
*/
function allocToMember(address member, uint amount) public onlyOwner {
require(amount > 0);
token.transfer(member, amount);
CommunityTokensAllocated(member, amount);
}
/*
* Clean up function
* @dev call to clean up the contract after all tokens were assigned
*/
function clean() public onlyOwner {
require(token.balanceOf(address(this)) == 0);
selfdestruct(owner);
}
}
/*
* Company reserve pool where the tokens will be locked for two years
* @title Company token reserve
*/
contract CompanyReserve is Ownable{
SignalsToken token;
uint256 withdrawn;
uint start;
/*
* Constructor changing owner to owner multisig & setting time lock
* @param address of the Signals Token contract
* @param address of the owner multisig
*/
function CompanyReserve(address _token, address _owner) public {
token = SignalsToken(_token);
owner = _owner;
start = now;
}
event TokensWithdrawn(address owner, uint amount);
/*
* Only function for the tokens withdrawal (3% anytime, 5% after one year, 10% after two year)
* @dev Will withdraw the whole allowance;
*/
function withdraw() onlyOwner public {
require(now - start >= 25920000);
uint256 toWithdraw = canWithdraw();
withdrawn += toWithdraw;
token.transfer(owner, toWithdraw);
TokensWithdrawn(owner, toWithdraw);
}
/*
* Checker function to find out how many tokens can be withdrawn.
* note: percentage of the token.totalSupply
* @dev Based on division down rounding
*/
function canWithdraw() public view returns (uint256) {
uint256 sinceStart = now - start;
uint256 allowed;
if (sinceStart >= 0) {
allowed = 555000000000000;
} else if (sinceStart >= 31536000) { // one year difference
allowed = 1480000000000000;
} else if (sinceStart >= 63072000) { // two years difference
allowed = 3330000000000000;
} else {
return 0;
}
return allowed - withdrawn;
}
/*
* Function to clean up the state and moved not allocated tokens to custody
*/
function cleanUp() onlyOwner public {
require(token.balanceOf(address(this)) == 0);
selfdestruct(owner);
}
}
/**
* @title Signals token
* @dev Mintable token created for Signals.Network
*/
contract PresaleToken is PausableToken, MintableToken {
// Standard token variables
string constant public name = "SGNPresaleToken";
string constant public symbol = "SGN";
uint8 constant public decimals = 9;
event TokensBurned(address initiatior, address indexed _partner, uint256 _tokens);
/*
* Constructor which pauses the token at the time of creation
*/
function PresaleToken() public {
pause();
}
/*
* @dev Token burn function to be called at the time of token swap
* @param _partner address to use for token balance buring
* @param _tokens uint256 amount of tokens to burn
*/
function burnTokens(address _partner, uint256 _tokens) public onlyOwner {
require(balances[_partner] >= _tokens);
balances[_partner] -= _tokens;
totalSupply -= _tokens;
TokensBurned(msg.sender, _partner, _tokens);
}
}
/**
* @title Signals token
* @dev Mintable token created for Signals.Network
*/
contract SignalsToken is PausableToken, MintableToken {
// Standard token variables
string constant public name = "Signals Network Token";
string constant public symbol = "SGN";
uint8 constant public decimals = 9;
}
contract PrivateRegister is Ownable {
struct contribution {
bool approved;
uint8 extra;
}
mapping (address => contribution) verified;
event ApprovedInvestor(address indexed investor);
event BonusesRegistered(address indexed investor, uint8 extra);
/*
* Approve function to adjust allowance to investment of each individual investor
* @param _investor address sets the beneficiary for later use
* @param _referral address to pay a commission in token to
* @param _commission uint8 expressed as a number between 0 and 5
*/
function approve(address _investor, uint8 _extra) onlyOwner public{
require(!isContract(_investor));
verified[_investor].approved = true;
if (_extra <= 100) {
verified[_investor].extra = _extra;
BonusesRegistered(_investor, _extra);
}
ApprovedInvestor(_investor);
}
/*
* Constant call to find out if an investor is registered
* @param _investor address to be checked
* @return bool is true is _investor was approved
*/
function approved(address _investor) view public returns (bool) {
return verified[_investor].approved;
}
/*
* Constant call to find out the referral and commission to bound to an investor
* @param _investor address to be checked
* @return address of the referral, returns 0x0 if there is none
* @return uint8 commission to be paid out on any investment
*/
function getBonuses(address _investor) view public returns (uint8 extra) {
return verified[_investor].extra;
}
/*
* Check if address is a contract to prevent contracts from participating the direct sale.
* @param addr address to be checked
* @return boolean of it is or isn't an contract address
* @credits Manuel Aráoz
*/
function isContract(address addr) public view returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
}
contract CrowdsaleRegister is Ownable {
struct contribution {
bool approved;
uint8 commission;
uint8 extra;
}
mapping (address => contribution) verified;
event ApprovedInvestor(address indexed investor);
event BonusesRegistered(address indexed investor, uint8 commission, uint8 extra);
/*
* Approve function to adjust allowance to investment of each individual investor
* @param _investor address sets the beneficiary for later use
* @param _referral address to pay a commission in token to
* @param _commission uint8 expressed as a number between 0 and 5
*/
function approve(address _investor, uint8 _commission, uint8 _extra) onlyOwner public{
require(!isContract(_investor));
verified[_investor].approved = true;
if (_commission <= 15 && _extra <= 5) {
verified[_investor].commission = _commission;
verified[_investor].extra = _extra;
BonusesRegistered(_investor, _commission, _extra);
}
ApprovedInvestor(_investor);
}
/*
* Constant call to find out if an investor is registered
* @param _investor address to be checked
* @return bool is true is _investor was approved
*/
function approved(address _investor) view public returns (bool) {
return verified[_investor].approved;
}
/*
* Constant call to find out the referral and commission to bound to an investor
* @param _investor address to be checked
* @return address of the referral, returns 0x0 if there is none
* @return uint8 commission to be paid out on any investment
*/
function getBonuses(address _investor) view public returns (uint8 commission, uint8 extra) {
return (verified[_investor].commission, verified[_investor].extra);
}
/*
* Check if address is a contract to prevent contracts from participating the direct sale.
* @param addr address to be checked
* @return boolean of it is or isn't an contract address
* @credits Manuel Aráoz
*/
function isContract(address addr) public view returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
}
/*
* Token pool for the presale tokens swap
* @title PresalePool
* @dev Requires to transfer ownership of both PresaleToken contracts to this contract
*/
contract PresalePool is Ownable {
PresaleToken public PublicPresale;
PresaleToken public PartnerPresale;
SignalsToken token;
CrowdsaleRegister registry;
/*
* Compensation coefficient based on the difference between the max ETHUSD price during the presale
* and price fix for mainsale
*/
uint256 compensation1;
uint256 compensation2;
// Date after which all tokens left will be transfered to the company reserve
uint256 deadLine;
event SupporterResolved(address indexed supporter, uint256 burned, uint256 created);
event PartnerResolved(address indexed partner, uint256 burned, uint256 created);
/*
* Constructor changing owner to owner multisig, setting all the contract addresses & compensation rates
* @param address of the Signals Token contract
* @param address of the KYC registry
* @param address of the owner multisig
* @param uint rate of the compensation for early investors
* @param uint rate of the compensation for partners
*/
function PresalePool(address _token, address _registry, address _owner, uint comp1, uint comp2) public {
owner = _owner;
PublicPresale = PresaleToken(0x15fEcCA27add3D28C55ff5b01644ae46edF15821);
PartnerPresale = PresaleToken(0xa70435D1a3AD4149B0C13371E537a22002Ae530d);
token = SignalsToken(_token);
registry = CrowdsaleRegister(_registry);
compensation1 = comp1;
compensation2 = comp2;
deadLine = now + 30 days;
}
/*
* Fallback function for simple contract usage, only calls the swap()
* @dev left for simpler interaction
*/
function() public {
swap();
}
/*
* Function swapping the presale tokens for the Signal tokens regardless on the presale pool
* @dev requires having ownership of the two presale contracts
* @dev requires the calling party to finish the KYC process fully
*/
function swap() public {
require(registry.approved(msg.sender));
uint256 oldBalance;
uint256 newBalance;
if (PublicPresale.balanceOf(msg.sender) > 0) {
oldBalance = PublicPresale.balanceOf(msg.sender);
newBalance = oldBalance * compensation1 / 100;
PublicPresale.burnTokens(msg.sender, oldBalance);
token.transfer(msg.sender, newBalance);
SupporterResolved(msg.sender, oldBalance, newBalance);
}
if (PartnerPresale.balanceOf(msg.sender) > 0) {
oldBalance = PartnerPresale.balanceOf(msg.sender);
newBalance = oldBalance * compensation2 / 100;
PartnerPresale.burnTokens(msg.sender, oldBalance);
token.transfer(msg.sender, newBalance);
PartnerResolved(msg.sender, oldBalance, newBalance);
}
}
/*
* Function swapping the presale tokens for the Signal tokens regardless on the presale pool
* @dev initiated from Signals (passing the ownership to a oracle to handle a script is recommended)
* @dev requires having ownership of the two presale contracts
* @dev requires the calling party to finish the KYC process fully
*/
function swapFor(address whom) onlyOwner public returns(bool) {
require(registry.approved(whom));
uint256 oldBalance;
uint256 newBalance;
if (PublicPresale.balanceOf(whom) > 0) {
oldBalance = PublicPresale.balanceOf(whom);
newBalance = oldBalance * compensation1 / 100;
PublicPresale.burnTokens(whom, oldBalance);
token.transfer(whom, newBalance);
SupporterResolved(whom, oldBalance, newBalance);
}
if (PartnerPresale.balanceOf(whom) > 0) {
oldBalance = PartnerPresale.balanceOf(whom);
newBalance = oldBalance * compensation2 / 100;
PartnerPresale.burnTokens(whom, oldBalance);
token.transfer(whom, newBalance);
SupporterResolved(whom, oldBalance, newBalance);
}
return true;
}
/*
* Function to clean up the state and moved not allocated tokens to custody
*/
function clean() onlyOwner public {
require(now >= deadLine);
uint256 notAllocated = token.balanceOf(address(this));
token.transfer(owner, notAllocated);
selfdestruct(owner);
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale.
* Crowdsales have a start and end timestamps, where investors can make
* token purchases and the crowdsale will assign them tokens based
* on a token per ETH rate. Funds collected are forwarded to a wallet
* as they arrive.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
SignalsToken public token;
// address where funds are collected
address public wallet;
// amount of raised money in wei
uint256 public weiRaised;
// start/end related
uint256 public startTime;
bool public hasEnded;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale(address _token, address _wallet) public {
require(_wallet != 0x0);
token = SignalsToken(_token);
wallet = _wallet;
}
// fallback function can be used to buy tokens
function () public payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) private {}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
wallet.transfer(msg.value);
}
// @return true if the transaction can buy tokens
function validPurchase() internal constant returns (bool) {}
}
/**
* @title FinalizableCrowdsale
* @dev Extension of Crowdsale where an owner can do extra work
* after finishing.
*/
contract FinalizableCrowdsale is Crowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
require(hasEnded);
finalization();
Finalized();
isFinalized = true;
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal {
}
}
contract SignalsCrowdsale is FinalizableCrowdsale {
// Cap & price related values
uint256 public constant HARD_CAP = 18000*(10**18);
uint256 public toBeRaised = 18000*(10**18);
uint256 public constant PRICE = 360000;
uint256 public tokensSold;
uint256 public constant maxTokens = 185000000*(10**9);
// Allocation constants
uint constant ADVISORY_SHARE = 18500000*(10**9); //FIXED
uint constant BOUNTY_SHARE = 3700000*(10**9); // FIXED
uint constant COMMUNITY_SHARE = 37000000*(10**9); //FIXED
uint constant COMPANY_SHARE = 33300000*(10**9); //FIXED
uint constant PRESALE_SHARE = 7856217611546440; // FIXED;
// Address pointers
address constant ADVISORS = 0x98280b2FD517a57a0B8B01b674457Eb7C6efa842; // TODO: change
address constant BOUNTY = 0x8726D7ac344A0BaBFd16394504e1cb978c70479A; // TODO: change
address constant COMMUNITY = 0x90CDbC88aB47c432Bd47185b9B0FDA1600c22102; // TODO: change
address constant COMPANY = 0xC010b2f2364372205055a299B28ef934f090FE92; // TODO: change
address constant PRESALE = 0x7F3a38fa282B16973feDD1E227210Ec020F2481e; // TODO: change
CrowdsaleRegister register;
PrivateRegister register2;
// Start & End related vars
bool public ready;
// Events
event SaleWillStart(uint256 time);
event SaleReady();
event SaleEnds(uint256 tokensLeft);
function SignalsCrowdsale(address _token, address _wallet, address _register, address _register2) public
FinalizableCrowdsale()
Crowdsale(_token, _wallet)
{
register = CrowdsaleRegister(_register);
register2 = PrivateRegister(_register2);
}
// @return true if the transaction can buy tokens
function validPurchase() internal constant returns (bool) {
bool started = (startTime <= now);
bool nonZeroPurchase = msg.value != 0;
bool capNotReached = (weiRaised < HARD_CAP);
bool approved = register.approved(msg.sender);
bool approved2 = register2.approved(msg.sender);
return ready && started && !hasEnded && nonZeroPurchase && capNotReached && (approved || approved2);
}
/*
* Buy in function to be called from the fallback function
* @param beneficiary address
*/
function buyTokens(address beneficiary) private {
require(beneficiary != 0x0);
require(validPurchase());
uint256 weiAmount = msg.value;
// base discount
uint256 discount = ((toBeRaised*10000)/HARD_CAP)*15;
// calculate token amount to be created
uint256 tokens;
// update state
weiRaised = weiRaised.add(weiAmount);
toBeRaised = toBeRaised.sub(weiAmount);
uint commission;
uint extra;
uint premium;
if (register.approved(beneficiary)) {
(commission, extra) = register.getBonuses(beneficiary);
// If extra access granted then give additional %
if (extra > 0) {
discount += extra*10000;
}
tokens = howMany(msg.value, discount);
// If referral was involved, give some percent to the source
if (commission > 0) {
premium = tokens.mul(commission).div(100);
token.mint(BOUNTY, premium);
}
} else {
extra = register2.getBonuses(beneficiary);
if (extra > 0) {
discount = extra*10000;
tokens = howMany(msg.value, discount);
}
}
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
tokensSold += tokens + premium;
forwardFunds();
assert(token.totalSupply() <= maxTokens);
}
/*
* Helper token emission functions
* @param value uint256 of the wei amount that gets invested
* @return uint256 of how many tokens can one get
*/
function howMany(uint256 value, uint256 discount) public view returns (uint256){
uint256 actualPrice = PRICE * (1000000 - discount) / 1000000;
return value / actualPrice;
}
/*
* Function to do preallocations - MANDATORY to continue
* @dev It's separated so it doesn't have to run in constructor
*/
function initialize() public onlyOwner {
require(!ready);
// Pre-allocation to pools
token.mint(ADVISORS,ADVISORY_SHARE);
token.mint(BOUNTY,BOUNTY_SHARE);
token.mint(COMMUNITY,COMMUNITY_SHARE);
token.mint(COMPANY,COMPANY_SHARE);
token.mint(PRESALE,PRESALE_SHARE);
tokensSold = PRESALE_SHARE;
ready = true;
SaleReady();
}
/*
* Function to do set or adjust the startTime - NOT MANDATORY but good for future start
*/
function changeStart(uint256 _time) public onlyOwner {
startTime = _time;
SaleWillStart(_time);
}
/*
* Function end or pause the sale
* @dev It's MANDATORY to finalize()
*/
function endSale(bool end) public onlyOwner {
require(startTime <= now);
uint256 tokensLeft = maxTokens - token.totalSupply();
if (tokensLeft > 0) {
token.mint(wallet, tokensLeft);
}
hasEnded = end;
SaleEnds(tokensLeft);
}
/*
* Adjust finalization to transfer token ownership to the fund holding address for further use
*/
function finalization() internal {
token.finishMinting();
token.transferOwnership(wallet);
}
/*
* Clean up function to get the contract selfdestructed - OPTIONAL
*/
function cleanUp() public onlyOwner {
require(isFinalized);
selfdestruct(owner);
}
}
| Approve function to adjust allowance to investment of each individual investor _investor address sets the beneficiary for later use _referral address to pay a commission in token to _commission uint8 expressed as a number between 0 and 5/ | function approve(address _investor, uint8 _extra) onlyOwner public{
require(!isContract(_investor));
verified[_investor].approved = true;
if (_extra <= 100) {
verified[_investor].extra = _extra;
BonusesRegistered(_investor, _extra);
}
ApprovedInvestor(_investor);
}
| 14,091,134 |
./full_match/80001/0x4dd461A3C95802DC5be4A706b73DCc0bEf0c71c8/sources/contracts/4_PeanutsContract.sol | 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];
}
| 861,398 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
/// @title NFT MEMORY GAME
/// @notice NFT Memery Game smart contract
/// @notice inhert NFT (ERC721) contracts from openzeppelin.
import '@openzeppelin/contracts/token/ERC721/ERC721.sol';
/**
* @dev Optional enumeration implementation for ERC-721 non-fungible token standard.
*/
import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol';
/**
* @dev ERC721 token with storage based token URI management.
*/
import '@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol';
///@dev Wrappers over Solidity's arithmetic operations.
import '@openzeppelin/contracts/utils/math/SafeMath.sol';
contract MemoryToken is ERC721, ERC721Enumerable, ERC721URIStorage {
using SafeMath for uint256;
/**
@notice Initializes the contract by setting a name and a symbol to the token collection.
*/
constructor() ERC721('Memory Token', 'MEMORY') {}
/**
@notice Hook that is called before any token transfer. This includes minting and burning.
@dev calling condition When from and to are both non-zero, from's tokenId will be transferred to to
@param from address token from
@param to address to tranfer token to
@param tokenId the token ID
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
/**
@notice Internal function to burn a specific token. Reverts if the token does not exist.
@param tokenId the token ID
*/
function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) {
super._burn(tokenId);
}
/**@dev Returns the URI for a given token ID. May return an empty string.
If the token’s URI is non-empty and a base URI was set (via _setBaseURI), it will be added to the token ID’s URI as a prefix.
Reverts if the token ID does not exist.
@param tokenId the token ID
*/
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return super.tokenURI(tokenId);
}
///@notice Returns true if account supports the IERC165 interface,
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
/**
/// @notice This is a minting function
/** @dev the function takes player addrress and nft uri and
incremnt number of nft the player gained and assign token uri to
player address and finally returns boolean value(True) if minting was sucessfull
*/
///@notice totalSupply Returns the total amount of tokens stored by the contract.
/// @param _to player address
///@param _tokenURI nft uri
function mint(address _to, string memory _tokenURI) public returns (bool) {
uint256 _tokenId = totalSupply().add(1);
_mint(_to, _tokenId);
_setTokenURI(_tokenId, _tokenURI);
return true;
}
}
| Returns true if account supports the IERC165 interface, | function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
player address and finally returns boolean value(True) if minting was sucessfull
| 6,379,827 |
//Address: 0x255d597951300a913d5e327c6e92ddc05923febe
//Contract name: CPCrowdsale
//Balance: 0 Ether
//Verification Date: 9/30/2017
//Transacion Count: 2593
// CODE STARTS HERE
pragma solidity 0.4.15;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
/**
* @title 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 Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
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;
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will 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;
}
}
/**
* @title LimitedTransferToken
* @dev LimitedTransferToken defines the generic interface and the implementation to limit token
* transferability for different events. It is intended to be used as a base class for other token
* contracts.
* LimitedTransferToken has been designed to allow for different limiting factors,
* this can be achieved by recursively calling super.transferableTokens() until the base class is
* hit. For example:
* function transferableTokens(address holder, uint64 time) constant public returns (uint256) {
* return min256(unlockedTokens, super.transferableTokens(holder, time));
* }
* A working example is VestedToken.sol:
* https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/VestedToken.sol
*/
contract LimitedTransferToken is ERC20 {
/**
* @dev Checks whether it can transfer or otherwise throws.
*/
modifier canTransfer(address _sender, uint256 _value) {
require(_value <= transferableTokens(_sender, uint64(now)));
_;
}
/**
* @dev Checks modifier and allows transfer if tokens are not locked.
* @param _to The address that will receive the tokens.
* @param _value The amount of tokens to be transferred.
*/
function transfer(address _to, uint256 _value) canTransfer(msg.sender, _value) public returns (bool) {
return super.transfer(_to, _value);
}
/**
* @dev Checks modifier and allows transfer if tokens are not locked.
* @param _from The address that will send the tokens.
* @param _to The address that will receive the tokens.
* @param _value The amount of tokens to be transferred.
*/
function transferFrom(address _from, address _to, uint256 _value) canTransfer(_from, _value) public returns (bool) {
return super.transferFrom(_from, _to, _value);
}
/**
* @dev Default transferable tokens function returns all tokens for a holder (no limit).
* @dev Overwriting transferableTokens(address holder, uint64 time) is the way to provide the
* specific logic for limiting token transferability for a holder over time.
*/
function transferableTokens(address holder, uint64 time) public constant returns (uint256) {
return balanceOf(holder);
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale.
* Crowdsales have a start and end timestamps, where investors can make
* token purchases and the crowdsale will assign them tokens based
* on a token per ETH rate. Funds collected are forwarded to a wallet
* as they arrive.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
MintableToken public token;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// address where funds are collected
address public wallet;
// how many token units a buyer gets per wei
uint256 public rate;
// amount of raised money in wei
uint256 public weiRaised;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_rate > 0);
require(_wallet != 0x0);
token = createTokenContract();
startTime = _startTime;
endTime = _endTime;
rate = _rate;
wallet = _wallet;
}
// creates the token to be sold.
// override this method to have crowdsale of a specific mintable token.
function createTokenContract() internal returns (MintableToken) {
return new MintableToken();
}
// fallback function can be used to buy tokens
function () payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) public payable {
require(beneficiary != 0x0);
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(rate);
// update state
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
wallet.transfer(msg.value);
}
// @return true if the transaction can buy tokens
function validPurchase() internal constant returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
// @return true if crowdsale event has ended
function hasEnded() public constant returns (bool) {
return now > endTime;
}
}
/**
* @title CappedCrowdsale
* @dev Extension of Crowdsale with a max amount of funds raised
*/
contract CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public cap;
function CappedCrowdsale(uint256 _cap) {
require(_cap > 0);
cap = _cap;
}
// overriding Crowdsale#validPurchase to add extra cap logic
// @return true if investors can buy at the moment
function validPurchase() internal constant returns (bool) {
bool withinCap = weiRaised.add(msg.value) <= cap;
return super.validPurchase() && withinCap;
}
// overriding Crowdsale#hasEnded to add cap logic
// @return true if crowdsale event has ended
function hasEnded() public constant returns (bool) {
bool capReached = weiRaised >= cap;
return super.hasEnded() || capReached;
}
}
/**
* @title FinalizableCrowdsale
* @dev Extension of Crowdsale where an owner can do extra work
* after finishing.
*/
contract FinalizableCrowdsale is Crowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
require(hasEnded());
finalization();
Finalized();
isFinalized = true;
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal {
}
}
contract Tiers {
using SafeMath for uint256;
uint256 public cpCap = 45000 ether;
uint256 public presaleWeiSold = 18000 ether;
uint256[6] public tierAmountCaps = [ presaleWeiSold
, presaleWeiSold + 5000 ether
, presaleWeiSold + 10000 ether
, presaleWeiSold + 15000 ether
, presaleWeiSold + 21000 ether
, cpCap
];
uint256[6] public tierRates = [ 2000 // tierRates[0] should never be used, but it is accurate
, 1500 // Tokens are purchased at a rate of 105-150
, 1350 // per deciEth, depending on purchase tier.
, 1250 // tierRates[i] is the purchase rate of tier_i
, 1150
, 1050
];
function tierIndexByWeiAmount(uint256 weiLevel) public constant returns (uint256) {
require(weiLevel <= cpCap);
for (uint256 i = 0; i < tierAmountCaps.length; i++) {
if (weiLevel <= tierAmountCaps[i]) {
return i;
}
}
}
/**
* @dev Calculates how many tokens a given amount of wei can buy at
* a particular level of weiRaised. Takes into account tiers of purchase
* bonus
*/
function calculateTokens(uint256 _amountWei, uint256 _weiRaised) public constant returns (uint256) {
uint256 currentTier = tierIndexByWeiAmount(_weiRaised);
uint256 startWeiLevel = _weiRaised;
uint256 endWeiLevel = _amountWei.add(_weiRaised);
uint256 tokens = 0;
for (uint256 i = currentTier; i < tierAmountCaps.length; i++) {
if (endWeiLevel <= tierAmountCaps[i]) {
tokens = tokens.add((endWeiLevel.sub(startWeiLevel)).mul(tierRates[i]));
break;
} else {
tokens = tokens.add((tierAmountCaps[i].sub(startWeiLevel)).mul(tierRates[i]));
startWeiLevel = tierAmountCaps[i];
}
}
return tokens;
}
}
contract CPToken is MintableToken, LimitedTransferToken {
string public name = "BLOCKMASON CREDIT PROTOCOL TOKEN";
string public symbol = "BCPT";
uint256 public decimals = 18;
bool public saleOver = false;
function CPToken() {
}
function endSale() public onlyOwner {
require (!saleOver);
saleOver = true;
}
/**
* @dev returns all user's tokens if time >= releaseTime
*/
function transferableTokens(address holder, uint64 time) public constant returns (uint256) {
if (saleOver)
return balanceOf(holder);
else
return 0;
}
}
contract DPIcoWhitelist {
address public admin;
bool public isOn;
mapping (address => bool) public whitelist;
address[] public users;
modifier signUpOpen() {
if (!isOn) revert();
_;
}
modifier isAdmin() {
if (msg.sender != admin) revert();
_;
}
modifier newAddr() {
if (whitelist[msg.sender]) revert();
_;
}
function DPIcoWhitelist() {
admin = msg.sender;
isOn = false;
}
function () {
signUp();
}
// Public functions
function setSignUpOnOff(bool state) public isAdmin {
isOn = state;
}
function signUp() public signUpOpen newAddr {
whitelist[msg.sender] = true;
users.push(msg.sender);
}
function getAdmin() public constant returns (address) {
return admin;
}
function signUpOn() public constant returns (bool) {
return isOn;
}
function isSignedUp(address addr) public constant returns (bool) {
return whitelist[addr];
}
function getUsers() public constant returns (address[]) {
return users;
}
function numUsers() public constant returns (uint) {
return users.length;
}
function userAtIndex(uint idx) public constant returns (address) {
return users[idx];
}
}
contract CPCrowdsale is CappedCrowdsale, FinalizableCrowdsale, Pausable {
using SafeMath for uint256;
DPIcoWhitelist private aw;
Tiers private at;
mapping (address => bool) private hasPurchased; // has whitelist address purchased already
uint256 public whitelistEndTime;
uint256 public maxWhitelistPurchaseWei;
uint256 public openWhitelistEndTime;
function CPCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _whitelistEndTime, uint256 _openWhitelistEndTime, address _wallet, address _tiersContract, address _whitelistContract, address _airdropWallet, address _advisorWallet, address _stakingWallet, address _privateSaleWallet)
CappedCrowdsale(45000 ether) // crowdsale capped at 45000 ether
FinalizableCrowdsale()
Crowdsale(_startTime, _endTime, 1, _wallet) // rate = 1 is a dummy value; we use tiers instead
{
token.mint(_wallet, 23226934 * (10 ** 18));
token.mint(_airdropWallet, 5807933 * (10 ** 18));
token.mint(_advisorWallet, 5807933 * (10 ** 18));
token.mint(_stakingWallet, 11615867 * (10 ** 18));
token.mint(_privateSaleWallet, 36000000 * (10 ** 18));
aw = DPIcoWhitelist(_whitelistContract);
require (aw.numUsers() > 0);
at = Tiers(_tiersContract);
whitelistEndTime = _whitelistEndTime;
openWhitelistEndTime = _openWhitelistEndTime;
weiRaised = 18000 ether; // 18K ether was sold during presale
maxWhitelistPurchaseWei = (cap.sub(weiRaised)).div(aw.numUsers());
}
// Public functions
function buyTokens(address beneficiary) public payable whenNotPaused {
uint256 weiAmount = msg.value;
require(beneficiary != 0x0);
require(validPurchase());
require(!isWhitelistPeriod()
|| whitelistValidPurchase(msg.sender, beneficiary, weiAmount));
require(!isOpenWhitelistPeriod()
|| openWhitelistValidPurchase(msg.sender, beneficiary));
hasPurchased[beneficiary] = true;
uint256 tokens = at.calculateTokens(weiAmount, weiRaised);
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
// Internal functions
function createTokenContract() internal returns (MintableToken) {
return new CPToken();
}
/**
* @dev Overriden to add finalization logic.
* Mints remaining tokens to dev wallet
*/
function finalization() internal {
uint256 remainingWei = cap.sub(weiRaised);
if (remainingWei > 0) {
uint256 remainingDevTokens = at.calculateTokens(remainingWei, weiRaised);
token.mint(wallet, remainingDevTokens);
}
CPToken(token).endSale();
token.finishMinting();
super.finalization();
}
// Private functions
// can't override `validPurchase` because need to pass additional values
function whitelistValidPurchase(address buyer, address beneficiary, uint256 amountWei) private constant returns (bool) {
bool beneficiaryPurchasedPreviously = hasPurchased[beneficiary];
bool belowMaxWhitelistPurchase = amountWei <= maxWhitelistPurchaseWei;
return (openWhitelistValidPurchase(buyer, beneficiary)
&& !beneficiaryPurchasedPreviously
&& belowMaxWhitelistPurchase);
}
// @return true if `now` is within the bounds of the whitelist period
function isWhitelistPeriod() private constant returns (bool) {
return (now <= whitelistEndTime && now >= startTime);
}
// can't override `validPurchase` because need to pass additional values
function openWhitelistValidPurchase(address buyer, address beneficiary) private constant returns (bool) {
bool buyerIsBeneficiary = buyer == beneficiary;
bool signedup = aw.isSignedUp(beneficiary);
return (buyerIsBeneficiary && signedup);
}
// @return true if `now` is within the bounds of the open whitelist period
function isOpenWhitelistPeriod() private constant returns (bool) {
bool cappedWhitelistOver = now > whitelistEndTime;
bool openWhitelistPeriod = now <= openWhitelistEndTime;
return cappedWhitelistOver && openWhitelistPeriod;
}
}
| return true if `now` is within the bounds of the whitelist period | function isWhitelistPeriod() private constant returns (bool) {
return (now <= whitelistEndTime && now >= startTime);
}
| 13,012,957 |
./partial_match/4/0x7a7704053B671c0b94ae12f24421F0bB471cA98a/sources/BondlyStaking.sol | unstake current staking/ | function unstake() public onlyWhitelisted {
require(stakingBalance[_msgSender()].total > 0, "Not staking");
STAKE_DETAIL storage _stake = stakingBalance[_msgSender()];
uint256 reward = rewardOf(_msgSender());
uint256 totalAmount = _stake.total.add(reward);
require(
bondlyToken.transfer(_msgSender(), totalAmount),
"Unstake: BondlyToken.Transfer: Failed to Unstake!"
);
totalStakes = totalStakes.sub(_stake.total);
totalRewards = totalRewards.sub(reward);
_stake.total = 0;
_stake.rewardSoFar = _stake.rewardSoFar.add(reward);
delete _stake.stakes;
emit Unstake(_msgSender(), totalAmount);
}
| 8,599,734 |
// Sources flattened with hardhat v2.3.0 https://hardhat.org
// File @openzeppelin/contracts/math/[email protected]
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/[email protected]
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/access/[email protected]
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;
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
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);
}
// File @openzeppelin/contracts/utils/[email protected]
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/token/ERC20/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using 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");
}
}
}
// File contracts/Vesting.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
contract Vesting is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct Program {
uint256 amount;
uint256 start;
uint256 cliff;
uint256 end;
uint256 claimed;
}
IERC20 private immutable _token;
mapping(address => Program) private _programs;
uint256 private _totalVesting;
event ProgramCreated(address indexed owner, uint256 amount);
event ProgramCanceled(address indexed owner);
event Claimed(address indexed owner, uint256 amount);
/**
* @dev Constructor that initializes the address of the Vesting contract.
*/
constructor(IERC20 token) public {
require(address(token) != address(0), "INVALID_ADDRESS");
_token = token;
}
/**
* @dev Returns a program for a given owner.
*/
function program(address owner)
external
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256
)
{
Program memory p = _programs[owner];
return (p.amount, p.start, p.cliff, p.end, p.claimed);
}
/**
* @dev Returns the total remaining vesting tokens in the contract.
*/
function totalVesting() external view returns (uint256) {
return _totalVesting;
}
/**
* @dev Creates a new vesting program for a given owner.
*/
function addProgram(
address owner,
uint256 amount,
uint256 start,
uint256 cliff,
uint256 end
) external onlyOwner {
require(owner != address(0), "INVALID_ADDRESS");
require(amount > 0, "INVALID_AMOUNT");
require(start <= cliff && cliff <= end, "INVALID_TIME");
require(_programs[owner].amount == 0, "ALREADY_EXISTS");
_programs[owner] = Program({ amount: amount, start: start, cliff: cliff, end: end, claimed: 0 });
_totalVesting = _totalVesting.add(amount);
emit ProgramCreated(owner, amount);
}
/**
* @dev Cancels an existing vesting program (including unclaimed vested tokens).
*/
function cancelProgram(address owner) external onlyOwner {
Program memory p = _programs[owner];
require(p.amount > 0, "INVALID_ADDRESS");
_totalVesting = _totalVesting.sub(p.amount.sub(p.claimed));
delete _programs[owner];
emit ProgramCanceled(owner);
}
/**
* @dev Returns the current claimable vested amount.
*/
function claimable(address owner) external view returns (uint256) {
return _claimable(_programs[owner]);
}
/**
* @dev Claims vested tokens and sends them to the owner.
*/
function claim() external {
Program storage p = _programs[msg.sender];
require(p.amount > 0, "INVALID_ADDRESS");
uint256 unclaimed = _claimable(p);
if (unclaimed == 0) {
return;
}
p.claimed = p.claimed.add(unclaimed);
_totalVesting = _totalVesting.sub(unclaimed);
_token.safeTransfer(msg.sender, unclaimed);
emit Claimed(msg.sender, unclaimed);
}
/**
* @dev Admin-only emergency transfer of contract's funds.
*/
function withdraw(
IERC20 token,
address target,
uint256 amount
) external onlyOwner {
require(target != address(0), "INVALID_ADDRESS");
token.safeTransfer(target, amount);
}
/**
* @dev Returns the current claimable amount.
*/
function _claimable(Program memory p) private view returns (uint256) {
if (p.amount == 0) {
return 0;
}
uint256 vested = _vested(p);
if (vested == 0) {
return 0;
}
return vested.sub(p.claimed);
}
/**
* @dev Returns the current claimable amount for a owner at the specific time.
*/
function _vested(Program memory p) private view returns (uint256) {
uint256 time = _time();
if (time < p.cliff) {
return 0;
}
if (time >= p.end) {
return p.amount;
}
// Interpolate vesting: claimable = amount * ((time - start) / (end - start)).
return p.amount.mul(time.sub(p.start)).div(p.end.sub(p.start));
}
/**
* @dev Returns the current time (and used for testing).
*/
function _time() internal view virtual returns (uint256) {
return block.timestamp;
}
} | Returns the total remaining vesting tokens in the contract./ | function totalVesting() external view returns (uint256) {
return _totalVesting;
}
| 1,141,011 |
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @title Whitelist contract
* @dev Whitelist for wallets.
*/
contract Whitelist is Ownable {
mapping(address => bool) whitelist;
uint256 public whitelistLength = 0;
address private addressApi;
modifier onlyPrivilegeAddresses {
require(msg.sender == addressApi || msg.sender == owner);
_;
}
/**
* @dev Set backend Api address.
* @dev Accept request from the owner only.
* @param _api The address of backend API to set.
*/
function setApiAddress(address _api) public onlyOwner {
require(_api != address(0));
addressApi = _api;
}
/**
* @dev Add wallet to whitelist.
* @dev Accept request from the privileged addresses only.
* @param _wallet The address of wallet to add.
*/
function addWallet(address _wallet) public onlyPrivilegeAddresses {
require(_wallet != address(0));
require(!isWhitelisted(_wallet));
whitelist[_wallet] = true;
whitelistLength++;
}
/**
* @dev Remove wallet from whitelist.
* @dev Accept request from the owner only.
* @param _wallet The address of whitelisted wallet to remove.
*/
function removeWallet(address _wallet) public onlyOwner {
require(_wallet != address(0));
require(isWhitelisted(_wallet));
whitelist[_wallet] = false;
whitelistLength--;
}
/**
* @dev Check the specified wallet whether it is in the whitelist.
* @param _wallet The address of wallet to check.
*/
function isWhitelisted(address _wallet) public view returns (bool) {
return whitelist[_wallet];
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
uint256 internal totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender)
public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract VeiagToken is StandardToken, Ownable, Pausable {
string constant public name = "Veiag Token";
string constant public symbol = "VEIAG";
uint8 constant public decimals = 18;
uint256 constant public INITIAL_TOTAL_SUPPLY = 1e9 * (uint256(10) ** decimals);
address private addressIco;
modifier onlyIco() {
require(msg.sender == addressIco);
_;
}
/**
* @dev Create VeiagToken contract and set pause
* @param _ico The address of ICO contract.
*/
function VeiagToken (address _ico) public {
require(_ico != address(0));
addressIco = _ico;
totalSupply_ = totalSupply_.add(INITIAL_TOTAL_SUPPLY);
balances[_ico] = balances[_ico].add(INITIAL_TOTAL_SUPPLY);
Transfer(address(0), _ico, INITIAL_TOTAL_SUPPLY);
pause();
}
/**
* @dev Transfer token for a specified address with pause feature for owner.
* @dev Only applies when the transfer is allowed by the owner.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
super.transfer(_to, _value);
}
/**
* @dev Transfer tokens from one address to another with pause feature for owner.
* @dev Only applies when the transfer is allowed by the owner.
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
super.transferFrom(_from, _to, _value);
}
/**
* @dev Transfer tokens from ICO address to another address.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transferFromIco(address _to, uint256 _value) public onlyIco returns (bool) {
super.transfer(_to, _value);
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(
ERC20Basic _token,
address _to,
uint256 _value
)
internal
{
require(_token.transfer(_to, _value));
}
function safeTransferFrom(
ERC20 _token,
address _from,
address _to,
uint256 _value
)
internal
{
require(_token.transferFrom(_from, _to, _value));
}
function safeApprove(
ERC20 _token,
address _spender,
uint256 _value
)
internal
{
require(_token.approve(_spender, _value));
}
}
/**
* @title TokenTimelock
* @dev TokenTimelock is a token holder contract that will allow a
* beneficiary to extract the tokens after a given release time
*/
contract TokenTimelock {
using SafeERC20 for ERC20Basic;
// ERC20 basic token contract being held
ERC20Basic public token;
// beneficiary of tokens after they are released
address public beneficiary;
// timestamp when token release is enabled
uint256 public releaseTime;
constructor(
ERC20Basic _token,
address _beneficiary,
uint256 _releaseTime
)
public
{
// solium-disable-next-line security/no-block-members
require(_releaseTime > block.timestamp);
token = _token;
beneficiary = _beneficiary;
releaseTime = _releaseTime;
}
/**
* @notice Transfers tokens held by timelock to beneficiary.
*/
function release() public {
// solium-disable-next-line security/no-block-members
require(block.timestamp >= releaseTime);
uint256 amount = token.balanceOf(address(this));
require(amount > 0);
token.transfer(beneficiary, amount);
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address _to,
uint256 _amount
)
public
hasMintPermission
canMint
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() public onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract LockedOutTokens is TokenTimelock {
function LockedOutTokens(
ERC20Basic _token,
address _beneficiary,
uint256 _releaseTime
) public TokenTimelock(_token, _beneficiary, _releaseTime)
{
}
function release() public {
require(beneficiary == msg.sender);
super.release();
}
}
/* solium-disable security/no-block-members */
/**
* @title TokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
*/
contract TokenVesting is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20Basic;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
constructor(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable
)
public
{
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
}
function setStart(uint256 _start) onlyOwner public {
start = _start;
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param _token ERC20 token which is being vested
*/
function release(ERC20Basic _token) public {
uint256 unreleased = releasableAmount(_token);
require(unreleased > 0);
released[_token] = released[_token].add(unreleased);
_token.transfer(beneficiary, unreleased);
emit Released(unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param _token ERC20 token which is being vested
*/
function revoke(ERC20Basic _token) public onlyOwner {
require(revocable);
require(!revoked[_token]);
uint256 balance = _token.balanceOf(address(this));
uint256 unreleased = releasableAmount(_token);
uint256 refund = balance.sub(unreleased);
revoked[_token] = true;
_token.transfer(owner, refund);
emit Revoked();
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param _token ERC20 token which is being vested
*/
function releasableAmount(ERC20Basic _token) public view returns (uint256) {
return vestedAmount(_token).sub(released[_token]);
}
/**
* @dev Calculates the amount that has already vested.
* @param _token ERC20 token which is being vested
*/
function vestedAmount(ERC20Basic _token) public view returns (uint256) {
uint256 currentBalance = _token.balanceOf(address(this));
uint256 totalBalance = currentBalance.add(released[_token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[_token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
}
contract VeiagTokenVesting is TokenVesting {
ERC20Basic public token;
function VeiagTokenVesting(
ERC20Basic _token,
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable
) TokenVesting(_beneficiary, _start, _cliff, _duration, _revocable) public
{
require(_token != address(0));
token = _token;
}
function grant() public {
release(token);
}
function release(ERC20Basic _token) public {
require(beneficiary == msg.sender);
super.release(_token);
}
}
contract Whitelistable {
Whitelist public whitelist;
modifier whenWhitelisted(address _wallet) {
// require(whitelist.isWhitelisted(_wallet));
_;
}
/**
* @dev Constructor for Whitelistable contract.
*/
function Whitelistable() public {
whitelist = new Whitelist();
}
}
contract VeiagCrowdsale is Pausable, Whitelistable {
using SafeMath for uint256;
uint256 constant private DECIMALS = 18;
uint256 constant public RESERVED_LOCKED_TOKENS = 250e6 * (10 ** DECIMALS);
uint256 constant public RESERVED_TEAMS_TOKENS = 100e6 * (10 ** DECIMALS);
uint256 constant public RESERVED_FOUNDERS_TOKENS = 100e6 * (10 ** DECIMALS);
uint256 constant public RESERVED_MARKETING_TOKENS = 50e6 * (10 ** DECIMALS);
uint256 constant public MAXCAP_TOKENS_PRE_ICO = 100e6 * (10 ** DECIMALS);
uint256 constant public MAXCAP_TOKENS_ICO = 400e6 * (10 ** DECIMALS);
uint256 constant public MIN_INVESTMENT = (10 ** 16); // 0.01 ETH
uint256 constant public MAX_INVESTMENT = 100 * (10 ** DECIMALS); // 100 ETH
uint256 public startTimePreIco = 0;
uint256 public endTimePreIco = 0;
uint256 public startTimeIco = 0;
uint256 public endTimeIco = 0;
// rate = 0.005 ETH, 1 ETH = 200 tokens
uint256 public exchangeRatePreIco = 200;
uint256 public icoFirstWeekRate = 150;
uint256 public icoSecondWeekRate = 125;
uint256 public icoThirdWeekRate = 110;
// rate = 0.01 ETH, 1 ETH = 100 tokens
uint256 public icoRate = 100;
uint256 public tokensRemainingPreIco = MAXCAP_TOKENS_PRE_ICO;
uint256 public tokensRemainingIco = MAXCAP_TOKENS_ICO;
uint256 public tokensSoldPreIco = 0;
uint256 public tokensSoldIco = 0;
uint256 public tokensSoldTotal = 0;
uint256 public weiRaisedPreIco = 0;
uint256 public weiRaisedIco = 0;
uint256 public weiRaisedTotal = 0;
VeiagToken public token = new VeiagToken(this);
LockedOutTokens public lockedTokens;
VeiagTokenVesting public teamsTokenVesting;
VeiagTokenVesting public foundersTokenVesting;
mapping (address => uint256) private totalInvestedAmount;
modifier beforeReachingPreIcoMaxCap() {
require(tokensRemainingPreIco > 0);
_;
}
modifier beforeReachingIcoMaxCap() {
require(tokensRemainingIco > 0);
_;
}
/**
* @dev Constructor for VeiagCrowdsale contract.
* @dev Set the owner who can manage whitelist and token.
* @param _startTimePreIco The pre-ICO start time.
* @param _endTimePreIco The pre-ICO end time.
* @param _startTimeIco The ICO start time.
* @param _endTimeIco The ICO end time.
* @param _lockedWallet The address for future sale.
* @param _teamsWallet The address for reserved tokens for teams.
* @param _foundersWallet The address for reserved tokens for founders.
* @param _marketingWallet The address for reserved tokens for marketing.
*/
function VeiagCrowdsale(
uint256 _startTimePreIco,
uint256 _endTimePreIco,
uint256 _startTimeIco,
uint256 _endTimeIco,
address _lockedWallet,
address _teamsWallet,
address _foundersWallet,
address _marketingWallet
) public Whitelistable()
{
require(_lockedWallet != address(0) && _teamsWallet != address(0) && _foundersWallet != address(0) && _marketingWallet != address(0));
require(_startTimePreIco > now && _endTimePreIco > _startTimePreIco);
require(_startTimeIco > _endTimePreIco && _endTimeIco > _startTimeIco);
startTimePreIco = _startTimePreIco;
endTimePreIco = _endTimePreIco;
startTimeIco = _startTimeIco;
endTimeIco = _endTimeIco;
lockedTokens = new LockedOutTokens(token, _lockedWallet, RESERVED_LOCKED_TOKENS);
teamsTokenVesting = new VeiagTokenVesting(token, _teamsWallet, 0, 1 days, 365 days, false);
foundersTokenVesting = new VeiagTokenVesting(token, _foundersWallet, 0, 1 days, 100 days, false);
token.transferFromIco(lockedTokens, RESERVED_LOCKED_TOKENS);
token.transferFromIco(teamsTokenVesting, RESERVED_TEAMS_TOKENS);
token.transferFromIco(foundersTokenVesting, RESERVED_FOUNDERS_TOKENS);
token.transferFromIco(_marketingWallet, RESERVED_MARKETING_TOKENS);
teamsTokenVesting.transferOwnership(this);
foundersTokenVesting.transferOwnership(this);
whitelist.transferOwnership(msg.sender);
token.transferOwnership(msg.sender);
}
function SetStartVesting(uint256 _startTimeVestingForFounders) public onlyOwner{
require(now > endTimeIco);
require(_startTimeVestingForFounders > endTimeIco);
teamsTokenVesting.setStart(_startTimeVestingForFounders);
foundersTokenVesting.setStart(endTimeIco);
teamsTokenVesting.transferOwnership(msg.sender);
foundersTokenVesting.transferOwnership(msg.sender);
}
function SetStartTimeIco(uint256 _startTimeIco) public onlyOwner{
uint256 deltaTime;
require(_startTimeIco > now && startTimeIco > now);
if (_startTimeIco > startTimeIco){
deltaTime = _startTimeIco.sub(startTimeIco);
endTimePreIco = endTimePreIco.add(deltaTime);
startTimeIco = startTimeIco.add(deltaTime);
endTimeIco = endTimeIco.add(deltaTime);
}
if (_startTimeIco < startTimeIco){
deltaTime = startTimeIco.sub(_startTimeIco);
endTimePreIco = endTimePreIco.sub(deltaTime);
startTimeIco = startTimeIco.sub(deltaTime);
endTimeIco = endTimeIco.sub(deltaTime);
}
}
/**
* @dev Fallback function can be used to buy tokens.
*/
function() public payable {
if (isPreIco()) {
sellTokensPreIco();
} else if (isIco()) {
sellTokensIco();
} else {
revert();
}
}
/**
* @dev Check whether the pre-ICO is active at the moment.
*/
function isPreIco() public view returns (bool) {
return now >= startTimePreIco && now <= endTimePreIco;
}
/**
* @dev Check whether the ICO is active at the moment.
*/
function isIco() public view returns (bool) {
return now >= startTimeIco && now <= endTimeIco;
}
/**
* @dev Calculate rate for ICO phase.
*/
function exchangeRateIco() public view returns(uint256) {
require(now >= startTimeIco && now <= endTimeIco);
if (now < startTimeIco + 1 weeks)
return icoFirstWeekRate;
if (now < startTimeIco + 2 weeks)
return icoSecondWeekRate;
if (now < startTimeIco + 3 weeks)
return icoThirdWeekRate;
return icoRate;
}
function setExchangeRatePreIco(uint256 _exchangeRatePreIco) public onlyOwner{
exchangeRatePreIco = _exchangeRatePreIco;
}
function setIcoFirstWeekRate(uint256 _icoFirstWeekRate) public onlyOwner{
icoFirstWeekRate = _icoFirstWeekRate;
}
function setIcoSecondWeekRate(uint256 _icoSecondWeekRate) public onlyOwner{
icoSecondWeekRate = _icoSecondWeekRate;
}
function setIcoThirdWeekRate(uint256 _icoThirdWeekRate) public onlyOwner{
icoThirdWeekRate = _icoThirdWeekRate;
}
function setIcoRate(uint256 _icoRate) public onlyOwner{
icoRate = _icoRate;
}
/**
* @dev Sell tokens during Pre-ICO stage.
*/
function sellTokensPreIco() public payable whenWhitelisted(msg.sender) beforeReachingPreIcoMaxCap whenNotPaused {
require(isPreIco());
require(msg.value >= MIN_INVESTMENT);
uint256 senderTotalInvestment = totalInvestedAmount[msg.sender].add(msg.value);
require(senderTotalInvestment <= MAX_INVESTMENT);
uint256 weiAmount = msg.value;
uint256 excessiveFunds = 0;
uint256 tokensAmount = weiAmount.mul(exchangeRatePreIco);
if (tokensAmount > tokensRemainingPreIco) {
uint256 weiToAccept = tokensRemainingPreIco.div(exchangeRatePreIco);
excessiveFunds = weiAmount.sub(weiToAccept);
tokensAmount = tokensRemainingPreIco;
weiAmount = weiToAccept;
}
addPreIcoPurchaseInfo(weiAmount, tokensAmount);
owner.transfer(weiAmount);
token.transferFromIco(msg.sender, tokensAmount);
if (excessiveFunds > 0) {
msg.sender.transfer(excessiveFunds);
}
}
/**
* @dev Sell tokens during ICO stage.
*/
function sellTokensIco() public payable whenWhitelisted(msg.sender) beforeReachingIcoMaxCap whenNotPaused {
require(isIco());
require(msg.value >= MIN_INVESTMENT);
uint256 senderTotalInvestment = totalInvestedAmount[msg.sender].add(msg.value);
require(senderTotalInvestment <= MAX_INVESTMENT);
uint256 weiAmount = msg.value;
uint256 excessiveFunds = 0;
uint256 tokensAmount = weiAmount.mul(exchangeRateIco());
if (tokensAmount > tokensRemainingIco) {
uint256 weiToAccept = tokensRemainingIco.div(exchangeRateIco());
excessiveFunds = weiAmount.sub(weiToAccept);
tokensAmount = tokensRemainingIco;
weiAmount = weiToAccept;
}
addIcoPurchaseInfo(weiAmount, tokensAmount);
owner.transfer(weiAmount);
token.transferFromIco(msg.sender, tokensAmount);
if (excessiveFunds > 0) {
msg.sender.transfer(excessiveFunds);
}
}
/**
* @dev Manual send tokens to the specified address.
* @param _address The address of a investor.
* @param _tokensAmount Amount of tokens.
*/
function manualSendTokens(address _address, uint256 _tokensAmount) public whenWhitelisted(_address) onlyOwner {
require(_address != address(0));
require(_tokensAmount > 0);
if (isPreIco() && _tokensAmount <= tokensRemainingPreIco) {
token.transferFromIco(_address, _tokensAmount);
addPreIcoPurchaseInfo(0, _tokensAmount);
} else if (isIco() && _tokensAmount <= tokensRemainingIco) {
token.transferFromIco(_address, _tokensAmount);
addIcoPurchaseInfo(0, _tokensAmount);
} else {
revert();
}
}
/**
* @dev Update the pre-ICO investments statistic.
* @param _weiAmount The investment received from a pre-ICO investor.
* @param _tokensAmount The tokens that will be sent to pre-ICO investor.
*/
function addPreIcoPurchaseInfo(uint256 _weiAmount, uint256 _tokensAmount) internal {
totalInvestedAmount[msg.sender] = totalInvestedAmount[msg.sender].add(_weiAmount);
tokensSoldPreIco = tokensSoldPreIco.add(_tokensAmount);
tokensSoldTotal = tokensSoldTotal.add(_tokensAmount);
tokensRemainingPreIco = tokensRemainingPreIco.sub(_tokensAmount);
weiRaisedPreIco = weiRaisedPreIco.add(_weiAmount);
weiRaisedTotal = weiRaisedTotal.add(_weiAmount);
}
/**
* @dev Update the ICO investments statistic.
* @param _weiAmount The investment received from a ICO investor.
* @param _tokensAmount The tokens that will be sent to ICO investor.
*/
function addIcoPurchaseInfo(uint256 _weiAmount, uint256 _tokensAmount) internal {
totalInvestedAmount[msg.sender] = totalInvestedAmount[msg.sender].add(_weiAmount);
tokensSoldIco = tokensSoldIco.add(_tokensAmount);
tokensSoldTotal = tokensSoldTotal.add(_tokensAmount);
tokensRemainingIco = tokensRemainingIco.sub(_tokensAmount);
weiRaisedIco = weiRaisedIco.add(_weiAmount);
weiRaisedTotal = weiRaisedTotal.add(_weiAmount);
}
}
contract Factory {
VeiagCrowdsale public crowdsale;
function createCrowdsale (
uint256 _startTimePreIco,
uint256 _endTimePreIco,
uint256 _startTimeIco,
uint256 _endTimeIco,
address _lockedWallet,
address _teamsWallet,
address _foundersWallet,
address _marketingWallet
) public
{
crowdsale = new VeiagCrowdsale(
_startTimePreIco,
_endTimePreIco,
_startTimeIco,
_endTimeIco,
_lockedWallet,
_teamsWallet,
_foundersWallet,
_marketingWallet
);
Whitelist whitelist = crowdsale.whitelist();
whitelist.transferOwnership(msg.sender);
VeiagToken token = crowdsale.token();
token.transferOwnership(msg.sender);
crowdsale.transferOwnership(msg.sender);
}
} | Calculates the amount that has already vested but hasn't been released yet. _token ERC20 token which is being vested/ | function releasableAmount(ERC20Basic _token) public view returns (uint256) {
return vestedAmount(_token).sub(released[_token]);
}
| 318,852 |
/**
*Submitted for verification at Etherscan.io on 2021-10-09
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// Global Enums and Structs
struct StrategyParams {
uint256 performanceFee;
uint256 activation;
uint256 debtRatio;
uint256 minDebtPerHarvest;
uint256 maxDebtPerHarvest;
uint256 lastReport;
uint256 totalDebt;
uint256 totalGain;
uint256 totalLoss;
}
// Part: Account
library Account {
enum Status {Normal, Liquid, Vapor}
struct Info {
address owner; // The address that owns the account
uint256 number; // A nonce that allows a single address to control many accounts
}
struct Storage {
mapping(uint256 => Types.Par) balances; // Mapping from marketId to principal
Status status;
}
}
// Part: Actions
library Actions {
enum ActionType {
Deposit, // supply tokens
Withdraw, // borrow tokens
Transfer, // transfer balance between accounts
Buy, // buy an amount of some token (publicly)
Sell, // sell an amount of some token (publicly)
Trade, // trade tokens against another account
Liquidate, // liquidate an undercollateralized or expiring account
Vaporize, // use excess tokens to zero-out a completely negative account
Call // send arbitrary data to an address
}
enum AccountLayout {OnePrimary, TwoPrimary, PrimaryAndSecondary}
enum MarketLayout {ZeroMarkets, OneMarket, TwoMarkets}
struct ActionArgs {
ActionType actionType;
uint256 accountId;
Types.AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
struct DepositArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 market;
address from;
}
struct WithdrawArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 market;
address to;
}
struct TransferArgs {
Types.AssetAmount amount;
Account.Info accountOne;
Account.Info accountTwo;
uint256 market;
}
struct BuyArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 makerMarket;
uint256 takerMarket;
address exchangeWrapper;
bytes orderData;
}
struct SellArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 takerMarket;
uint256 makerMarket;
address exchangeWrapper;
bytes orderData;
}
struct TradeArgs {
Types.AssetAmount amount;
Account.Info takerAccount;
Account.Info makerAccount;
uint256 inputMarket;
uint256 outputMarket;
address autoTrader;
bytes tradeData;
}
struct LiquidateArgs {
Types.AssetAmount amount;
Account.Info solidAccount;
Account.Info liquidAccount;
uint256 owedMarket;
uint256 heldMarket;
}
struct VaporizeArgs {
Types.AssetAmount amount;
Account.Info solidAccount;
Account.Info vaporAccount;
uint256 owedMarket;
uint256 heldMarket;
}
struct CallArgs {
Account.Info account;
address callee;
bytes data;
}
}
library Decimal {
struct D256 {
uint256 value;
}
}
library Interest {
struct Rate {
uint256 value;
}
struct Index {
uint96 borrow;
uint96 supply;
uint32 lastUpdate;
}
}
library Monetary {
struct Price {
uint256 value;
}
struct Value {
uint256 value;
}
}
library Storage {
// All information necessary for tracking a market
struct Market {
// Contract address of the associated ERC20 token
address token;
// Total aggregated supply and borrow amount of the entire market
Types.TotalPar totalPar;
// Interest index of the market
Interest.Index index;
// Contract address of the price oracle for this market
address priceOracle;
// Contract address of the interest setter for this market
address interestSetter;
// Multiplier on the marginRatio for this market
Decimal.D256 marginPremium;
// Multiplier on the liquidationSpread for this market
Decimal.D256 spreadPremium;
// Whether additional borrows are allowed for this market
bool isClosing;
}
// The global risk parameters that govern the health and security of the system
struct RiskParams {
// Required ratio of over-collateralization
Decimal.D256 marginRatio;
// Percentage penalty incurred by liquidated accounts
Decimal.D256 liquidationSpread;
// Percentage of the borrower's interest fee that gets passed to the suppliers
Decimal.D256 earningsRate;
// The minimum absolute borrow value of an account
// There must be sufficient incentivize to liquidate undercollateralized accounts
Monetary.Value minBorrowedValue;
}
// The maximum RiskParam values that can be set
struct RiskLimits {
uint64 marginRatioMax;
uint64 liquidationSpreadMax;
uint64 earningsRateMax;
uint64 marginPremiumMax;
uint64 spreadPremiumMax;
uint128 minBorrowedValueMax;
}
// The entire storage state of Solo
struct State {
// number of markets
uint256 numMarkets;
// marketId => Market
mapping(uint256 => Market) markets;
// owner => account number => Account
mapping(address => mapping(uint256 => Account.Storage)) accounts;
// Addresses that can control other users accounts
mapping(address => mapping(address => bool)) operators;
// Addresses that can control all users accounts
mapping(address => bool) globalOperators;
// mutable risk parameters of the system
RiskParams riskParams;
// immutable risk limits of the system
RiskLimits riskLimits;
}
}
// Part: ICallee
/**
* @title ICallee
* @author dYdX
*
* Interface that Callees for Solo must implement in order to ingest data.
*/
interface ICallee {
// ============ Public Functions ============
/**
* Allows users to send this contract arbitrary data.
*
* @param sender The msg.sender to Solo
* @param accountInfo The account from which the data is being sent
* @param data Arbitrary data given by the sender
*/
function callFunction(
address sender,
Account.Info memory accountInfo,
bytes memory data
) external;
}
// Part: ISoloMargin
interface ISoloMargin {
struct OperatorArg {
address operator1;
bool trusted;
}
function ownerSetSpreadPremium(uint256 marketId, Decimal.D256 memory spreadPremium) external;
function getIsGlobalOperator(address operator1) external view returns (bool);
function getMarketTokenAddress(uint256 marketId) external view returns (address);
function ownerSetInterestSetter(uint256 marketId, address interestSetter) external;
function getAccountValues(Account.Info memory account) external view returns (Monetary.Value memory, Monetary.Value memory);
function getMarketPriceOracle(uint256 marketId) external view returns (address);
function getMarketInterestSetter(uint256 marketId) external view returns (address);
function getMarketSpreadPremium(uint256 marketId) external view returns (Decimal.D256 memory);
function getNumMarkets() external view returns (uint256);
function ownerWithdrawUnsupportedTokens(address token, address recipient) external returns (uint256);
function ownerSetMinBorrowedValue(Monetary.Value memory minBorrowedValue) external;
function ownerSetLiquidationSpread(Decimal.D256 memory spread) external;
function ownerSetEarningsRate(Decimal.D256 memory earningsRate) external;
function getIsLocalOperator(address owner, address operator1) external view returns (bool);
function getAccountPar(Account.Info memory account, uint256 marketId) external view returns (Types.Par memory);
function ownerSetMarginPremium(uint256 marketId, Decimal.D256 memory marginPremium) external;
function getMarginRatio() external view returns (Decimal.D256 memory);
function getMarketCurrentIndex(uint256 marketId) external view returns (Interest.Index memory);
function getMarketIsClosing(uint256 marketId) external view returns (bool);
function getRiskParams() external view returns (Storage.RiskParams memory);
function getAccountBalances(Account.Info memory account)
external
view
returns (
address[] memory,
Types.Par[] memory,
Types.Wei[] memory
);
function renounceOwnership() external;
function getMinBorrowedValue() external view returns (Monetary.Value memory);
function setOperators(OperatorArg[] memory args) external;
function getMarketPrice(uint256 marketId) external view returns (address);
function owner() external view returns (address);
function isOwner() external view returns (bool);
function ownerWithdrawExcessTokens(uint256 marketId, address recipient) external returns (uint256);
function ownerAddMarket(
address token,
address priceOracle,
address interestSetter,
Decimal.D256 memory marginPremium,
Decimal.D256 memory spreadPremium
) external;
function operate(Account.Info[] memory accounts, Actions.ActionArgs[] memory actions) external;
function getMarketWithInfo(uint256 marketId)
external
view
returns (
Storage.Market memory,
Interest.Index memory,
Monetary.Price memory,
Interest.Rate memory
);
function ownerSetMarginRatio(Decimal.D256 memory ratio) external;
function getLiquidationSpread() external view returns (Decimal.D256 memory);
function getAccountWei(Account.Info memory account, uint256 marketId) external view returns (Types.Wei memory);
function getMarketTotalPar(uint256 marketId) external view returns (Types.TotalPar memory);
function getLiquidationSpreadForPair(uint256 heldMarketId, uint256 owedMarketId) external view returns (Decimal.D256
memory);
function getNumExcessTokens(uint256 marketId) external view returns (Types.Wei memory);
function getMarketCachedIndex(uint256 marketId) external view returns (Interest.Index memory);
function getAccountStatus(Account.Info memory account) external view returns (uint8);
function getEarningsRate() external view returns (Decimal.D256 memory);
function ownerSetPriceOracle(uint256 marketId, address priceOracle) external;
function getRiskLimits() external view returns (Storage.RiskLimits memory);
function getMarket(uint256 marketId) external view returns (Storage.Market memory);
function ownerSetIsClosing(uint256 marketId, bool isClosing) external;
function ownerSetGlobalOperator(address operator1, bool approved) external;
function transferOwnership(address newOwner) external;
function getAdjustedAccountValues(Account.Info memory account) external view returns (Monetary.Value memory, Monetary.Value memory);
function getMarketMarginPremium(uint256 marketId) external view returns (Decimal.D256 memory);
function getMarketInterestRate(uint256 marketId) external view returns (Interest.Rate memory);
}
// Part: IUniswapAnchoredView
interface IUniswapAnchoredView {
function price(string memory) external returns (uint);
}
// Part: IUniswapV2Router01
interface IUniswapV2Router01 {
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);
}
// Part: IUniswapV3SwapCallback
/// @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;
}
// Part: InterestRateModel
interface InterestRateModel {
/**
* @notice Calculates the current borrow interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @return The borrow rate per block (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(
uint256 cash,
uint256 borrows,
uint256 reserves
) external view returns (uint256, uint256);
/**
* @notice Calculates the current supply interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per block (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(
uint256 cash,
uint256 borrows,
uint256 reserves,
uint256 reserveFactorMantissa
) external view returns (uint256);
}
// Part: OpenZeppelin/[email protected]/Address
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory)
{
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// Part: OpenZeppelin/[email protected]/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/[email protected]/Math
/**
* @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);
}
}
// Part: OpenZeppelin/[email protected]/SafeMath
/**
* @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;
}
}
// Part: Types
library Types {
enum AssetDenomination {
Wei, // the amount is denominated in wei
Par // the amount is denominated in par
}
enum AssetReference {
Delta, // the amount is given as a delta from the current value
Target // the amount is given as an exact number to end up at
}
struct AssetAmount {
bool sign; // true if positive
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
struct TotalPar {
uint128 borrow;
uint128 supply;
}
struct Par {
bool sign; // true if positive
uint128 value;
}
struct Wei {
bool sign; // true if positive
uint256 value;
}
}
// Part: iearn-finance/[email protected]/HealthCheck
interface HealthCheck {
function check(
uint256 profit,
uint256 loss,
uint256 debtPayment,
uint256 debtOutstanding,
uint256 totalDebt
) external view returns (bool);
}
// Part: CTokenI
interface CTokenI {
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint256 mintAmount, uint256 mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint256 repayAmount, uint256 accountBorrows, uint256 totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(address liquidator, address borrower, uint256 repayAmount, address cTokenCollateral, uint256 seizeTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint256 addAmount, uint256 newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint256 reduceAmount, uint256 newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint256 amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Failure event
*/
event Failure(uint256 error, uint256 info, uint256 detail);
function transfer(address dst, uint256 amount) external returns (bool);
function transferFrom(
address src,
address dst,
uint256 amount
) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint256);
function getAccountSnapshot(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function borrowRatePerBlock() external view returns (uint256);
function supplyRatePerBlock() external view returns (uint256);
function totalBorrowsCurrent() external returns (uint256);
function borrowBalanceCurrent(address account) external returns (uint256);
function borrowBalanceStored(address account) external view returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function accrualBlockNumber() external view returns (uint256);
function exchangeRateStored() external view returns (uint256);
function getCash() external view returns (uint256);
function accrueInterest() external returns (uint256);
function interestRateModel() external view returns (InterestRateModel);
function totalReserves() external view returns (uint256);
function reserveFactorMantissa() external view returns (uint256);
function seize(
address liquidator,
address borrower,
uint256 seizeTokens
) external returns (uint256);
function totalBorrows() external view returns (uint256);
function totalSupply() external view returns (uint256);
}
// Part: IERC20Extended
interface IERC20Extended is IERC20 {
function decimals() external view returns (uint8);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
}
// Part: IUniswapV2Router02
interface IUniswapV2Router02 is IUniswapV2Router01 {
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;
}
// Part: IUniswapV3Router
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface IUniswapV3Router 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);
}
// Part: IWETH
interface IWETH is IERC20 {
function deposit() payable external;
function withdraw(uint256) external;
}
// Part: OpenZeppelin/[email protected]/SafeERC20
/**
* @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");
}
}
}
// Part: iearn-finance/[email protected]/VaultAPI
interface VaultAPI is IERC20 {
function name() external view returns (string calldata);
function symbol() external view returns (string calldata);
function decimals() external view returns (uint256);
function apiVersion() external pure returns (string memory);
function permit(
address owner,
address spender,
uint256 amount,
uint256 expiry,
bytes calldata signature
) external returns (bool);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function deposit() external returns (uint256);
function deposit(uint256 amount) external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function withdraw() external returns (uint256);
function withdraw(uint256 maxShares) external returns (uint256);
function withdraw(uint256 maxShares, address recipient) external returns (uint256);
function token() external view returns (address);
function strategies(address _strategy) external view returns (StrategyParams memory);
function pricePerShare() external view returns (uint256);
function totalAssets() external view returns (uint256);
function depositLimit() external view returns (uint256);
function maxAvailableShares() external view returns (uint256);
/**
* View how much the Vault would increase this Strategy's borrow limit,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function creditAvailable() external view returns (uint256);
/**
* View how much the Vault would like to pull back from the Strategy,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function debtOutstanding() external view returns (uint256);
/**
* View how much the Vault expect this Strategy to return at the current
* block, based on its present performance (since its last report). Can be
* used to determine expectedReturn in your Strategy.
*/
function expectedReturn() external view returns (uint256);
/**
* This is the main contact point where the Strategy interacts with the
* Vault. It is critical that this call is handled as intended by the
* Strategy. Therefore, this function will be called by BaseStrategy to
* make sure the integration is correct.
*/
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external returns (uint256);
/**
* This function should only be used in the scenario where the Strategy is
* being retired but no migration of the positions are possible, or in the
* extreme scenario that the Strategy needs to be put into "Emergency Exit"
* mode in order for it to exit as quickly as possible. The latter scenario
* could be for any reason that is considered "critical" that the Strategy
* exits its position as fast as possible, such as a sudden change in
* market conditions leading to losses, or an imminent failure in an
* external dependency.
*/
function revokeStrategy() external;
/**
* View the governance address of the Vault to assert privileged functions
* can only be called by governance. The Strategy serves the Vault, so it
* is subject to governance defined by the Vault.
*/
function governance() external view returns (address);
/**
* View the management address of the Vault to assert privileged functions
* can only be called by management. The Strategy serves the Vault, so it
* is subject to management defined by the Vault.
*/
function management() external view returns (address);
/**
* View the guardian address of the Vault to assert privileged functions
* can only be called by guardian. The Strategy serves the Vault, so it
* is subject to guardian defined by the Vault.
*/
function guardian() external view returns (address);
}
// Part: CErc20I
interface CErc20I is CTokenI {
function mint(uint256 mintAmount) external returns (uint256);
function redeem(uint256 redeemTokens) external returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
function borrow(uint256 borrowAmount) external returns (uint256);
function repayBorrow(uint256 repayAmount) external returns (uint256);
function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256);
function liquidateBorrow(
address borrower,
uint256 repayAmount,
CTokenI cTokenCollateral
) external returns (uint256);
function underlying() external view returns (address);
}
// Part: CEtherI
interface CEtherI is CTokenI {
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
function redeem(uint256 redeemTokens) external returns (uint256);
function liquidateBorrow(address borrower, CTokenI cTokenCollateral) external payable;
function borrow(uint256 borrowAmount) external returns (uint);
function mint() external payable;
function repayBorrow() external payable;
}
// Part: ComptrollerI
interface ComptrollerI {
function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory);
function exitMarket(address cToken) external returns (uint256);
/*** Policy Hooks ***/
function mintAllowed(
address cToken,
address minter,
uint256 mintAmount
) external returns (uint256);
function mintVerify(
address cToken,
address minter,
uint256 mintAmount,
uint256 mintTokens
) external;
function redeemAllowed(
address cToken,
address redeemer,
uint256 redeemTokens
) external returns (uint256);
function redeemVerify(
address cToken,
address redeemer,
uint256 redeemAmount,
uint256 redeemTokens
) external;
function borrowAllowed(
address cToken,
address borrower,
uint256 borrowAmount
) external returns (uint256);
function borrowVerify(
address cToken,
address borrower,
uint256 borrowAmount
) external;
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint256 repayAmount
) external returns (uint256);
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint256 repayAmount,
uint256 borrowerIndex
) external;
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint256 repayAmount
) external returns (uint256);
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint256 repayAmount,
uint256 seizeTokens
) external;
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint256 seizeTokens
) external returns (uint256);
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint256 seizeTokens
) external;
function transferAllowed(
address cToken,
address src,
address dst,
uint256 transferTokens
) external returns (uint256);
function transferVerify(
address cToken,
address src,
address dst,
uint256 transferTokens
) external;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address cTokenBorrowed,
address cTokenCollateral,
uint256 repayAmount
) external view returns (uint256, uint256);
function getAccountLiquidity(address account)
external
view
returns (
uint256,
uint256,
uint256
);
/*** Comp claims ****/
function claimComp(address holder) external;
function claimComp(address holder, CTokenI[] memory cTokens) external;
function markets(address ctoken)
external
view
returns (
bool,
uint256,
bool
);
function compSpeeds(address ctoken) external view returns (uint256); // will be deprecated
function compSupplySpeeds(address ctoken) external view returns (uint256);
function compBorrowSpeeds(address ctoken) external view returns (uint256);
function oracle() external view returns (address);
}
// Part: iearn-finance/[email protected]/BaseStrategy
/**
* @title Yearn Base Strategy
* @author yearn.finance
* @notice
* BaseStrategy implements all of the required functionality to interoperate
* closely with the Vault contract. This contract should be inherited and the
* abstract methods implemented to adapt the Strategy to the particular needs
* it has to create a return.
*
* Of special interest is the relationship between `harvest()` and
* `vault.report()'. `harvest()` may be called simply because enough time has
* elapsed since the last report, and not because any funds need to be moved
* or positions adjusted. This is critical so that the Vault may maintain an
* accurate picture of the Strategy's performance. See `vault.report()`,
* `harvest()`, and `harvestTrigger()` for further details.
*/
abstract contract BaseStrategy {
using SafeMath for uint256;
using SafeERC20 for IERC20;
string public metadataURI;
// health checks
bool public doHealthCheck;
address public healthCheck;
/**
* @notice
* Used to track which version of `StrategyAPI` this Strategy
* implements.
* @dev The Strategy's version must match the Vault's `API_VERSION`.
* @return A string which holds the current API version of this contract.
*/
function apiVersion() public pure returns (string memory) {
return "0.4.3";
}
/**
* @notice This Strategy's name.
* @dev
* You can use this field to manage the "version" of this Strategy, e.g.
* `StrategySomethingOrOtherV1`. However, "API Version" is managed by
* `apiVersion()` function above.
* @return This Strategy's name.
*/
function name() external view virtual returns (string memory);
/**
* @notice
* The amount (priced in want) of the total assets managed by this strategy should not count
* towards Yearn's TVL calculations.
* @dev
* You can override this field to set it to a non-zero value if some of the assets of this
* Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault.
* Note that this value must be strictly less than or equal to the amount provided by
* `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets.
* Also note that this value is used to determine the total assets under management by this
* strategy, for the purposes of computing the management fee in `Vault`
* @return
* The amount of assets this strategy manages that should not be included in Yearn's Total Value
* Locked (TVL) calculation across it's ecosystem.
*/
function delegatedAssets() external view virtual returns (uint256) {
return 0;
}
VaultAPI public vault;
address public strategist;
address public rewards;
address public keeper;
IERC20 public want;
// So indexers can keep track of this
event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding);
event UpdatedStrategist(address newStrategist);
event UpdatedKeeper(address newKeeper);
event UpdatedRewards(address rewards);
event UpdatedMinReportDelay(uint256 delay);
event UpdatedMaxReportDelay(uint256 delay);
event UpdatedProfitFactor(uint256 profitFactor);
event UpdatedDebtThreshold(uint256 debtThreshold);
event EmergencyExitEnabled();
event UpdatedMetadataURI(string metadataURI);
// The minimum number of seconds between harvest calls. See
// `setMinReportDelay()` for more details.
uint256 public minReportDelay;
// The maximum number of seconds between harvest calls. See
// `setMaxReportDelay()` for more details.
uint256 public maxReportDelay;
// The minimum multiple that `callCost` must be above the credit/profit to
// be "justifiable". See `setProfitFactor()` for more details.
uint256 public profitFactor;
// Use this to adjust the threshold at which running a debt causes a
// harvest trigger. See `setDebtThreshold()` for more details.
uint256 public debtThreshold;
// See note on `setEmergencyExit()`.
bool public emergencyExit;
// modifiers
modifier onlyAuthorized() {
require(msg.sender == strategist || msg.sender == governance(), "!authorized");
_;
}
modifier onlyEmergencyAuthorized() {
require(
msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(),
"!authorized"
);
_;
}
modifier onlyStrategist() {
require(msg.sender == strategist, "!strategist");
_;
}
modifier onlyGovernance() {
require(msg.sender == governance(), "!authorized");
_;
}
modifier onlyKeepers() {
require(
msg.sender == keeper ||
msg.sender == strategist ||
msg.sender == governance() ||
msg.sender == vault.guardian() ||
msg.sender == vault.management(),
"!authorized"
);
_;
}
modifier onlyVaultManagers() {
require(msg.sender == vault.management() || msg.sender == governance(), "!authorized");
_;
}
constructor(address _vault) public {
_initialize(_vault, msg.sender, msg.sender, msg.sender);
}
/**
* @notice
* Initializes the Strategy, this is called only once, when the
* contract is deployed.
* @dev `_vault` should implement `VaultAPI`.
* @param _vault The address of the Vault responsible for this Strategy.
* @param _strategist The address to assign as `strategist`.
* The strategist is able to change the reward address
* @param _rewards The address to use for pulling rewards.
* @param _keeper The adddress of the _keeper. _keeper
* can harvest and tend a strategy.
*/
function _initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) internal {
require(address(want) == address(0), "Strategy already initialized");
vault = VaultAPI(_vault);
want = IERC20(vault.token());
want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas)
strategist = _strategist;
rewards = _rewards;
keeper = _keeper;
// initialize variables
minReportDelay = 0;
maxReportDelay = 86400;
profitFactor = 100;
debtThreshold = 0;
vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled
}
function setHealthCheck(address _healthCheck) external onlyVaultManagers {
healthCheck = _healthCheck;
}
function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers {
doHealthCheck = _doHealthCheck;
}
/**
* @notice
* Used to change `strategist`.
*
* This may only be called by governance or the existing strategist.
* @param _strategist The new address to assign as `strategist`.
*/
function setStrategist(address _strategist) external onlyAuthorized {
require(_strategist != address(0));
strategist = _strategist;
emit UpdatedStrategist(_strategist);
}
/**
* @notice
* Used to change `keeper`.
*
* `keeper` is the only address that may call `tend()` or `harvest()`,
* other than `governance()` or `strategist`. However, unlike
* `governance()` or `strategist`, `keeper` may *only* call `tend()`
* and `harvest()`, and no other authorized functions, following the
* principle of least privilege.
*
* This may only be called by governance or the strategist.
* @param _keeper The new address to assign as `keeper`.
*/
function setKeeper(address _keeper) external onlyAuthorized {
require(_keeper != address(0));
keeper = _keeper;
emit UpdatedKeeper(_keeper);
}
/**
* @notice
* Used to change `rewards`. EOA or smart contract which has the permission
* to pull rewards from the vault.
*
* This may only be called by the strategist.
* @param _rewards The address to use for pulling rewards.
*/
function setRewards(address _rewards) external onlyStrategist {
require(_rewards != address(0));
vault.approve(rewards, 0);
rewards = _rewards;
vault.approve(rewards, uint256(-1));
emit UpdatedRewards(_rewards);
}
/**
* @notice
* Used to change `minReportDelay`. `minReportDelay` is the minimum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the minimum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The minimum number of seconds to wait between harvests.
*/
function setMinReportDelay(uint256 _delay) external onlyAuthorized {
minReportDelay = _delay;
emit UpdatedMinReportDelay(_delay);
}
/**
* @notice
* Used to change `maxReportDelay`. `maxReportDelay` is the maximum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the maximum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The maximum number of seconds to wait between harvests.
*/
function setMaxReportDelay(uint256 _delay) external onlyAuthorized {
maxReportDelay = _delay;
emit UpdatedMaxReportDelay(_delay);
}
/**
* @notice
* Used to change `profitFactor`. `profitFactor` is used to determine
* if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _profitFactor A ratio to multiply anticipated
* `harvest()` gas cost against.
*/
function setProfitFactor(uint256 _profitFactor) external onlyAuthorized {
profitFactor = _profitFactor;
emit UpdatedProfitFactor(_profitFactor);
}
/**
* @notice
* Sets how far the Strategy can go into loss without a harvest and report
* being required.
*
* By default this is 0, meaning any losses would cause a harvest which
* will subsequently report the loss to the Vault for tracking. (See
* `harvestTrigger()` for more details.)
*
* This may only be called by governance or the strategist.
* @param _debtThreshold How big of a loss this Strategy may carry without
* being required to report to the Vault.
*/
function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized {
debtThreshold = _debtThreshold;
emit UpdatedDebtThreshold(_debtThreshold);
}
/**
* @notice
* Used to change `metadataURI`. `metadataURI` is used to store the URI
* of the file describing the strategy.
*
* This may only be called by governance or the strategist.
* @param _metadataURI The URI that describe the strategy.
*/
function setMetadataURI(string calldata _metadataURI) external onlyAuthorized {
metadataURI = _metadataURI;
emit UpdatedMetadataURI(_metadataURI);
}
/**
* Resolve governance address from Vault contract, used to make assertions
* on protected functions in the Strategy.
*/
function governance() internal view returns (address) {
return vault.governance();
}
/**
* @notice
* Provide an accurate conversion from `_amtInWei` (denominated in wei)
* to `want` (using the native decimal characteristics of `want`).
* @dev
* Care must be taken when working with decimals to assure that the conversion
* is compatible. As an example:
*
* given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals),
* with USDC/ETH = 1800, this should give back 1800000000 (180 USDC)
*
* @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want`
* @return The amount in `want` of `_amtInEth` converted to `want`
**/
function ethToWant(uint256 _amtInWei) public view virtual returns (uint256);
/**
* @notice
* Provide an accurate estimate for the total amount of assets
* (principle + return) that this Strategy is currently managing,
* denominated in terms of `want` tokens.
*
* This total should be "realizable" e.g. the total value that could
* *actually* be obtained from this Strategy if it were to divest its
* entire position based on current on-chain conditions.
* @dev
* Care must be taken in using this function, since it relies on external
* systems, which could be manipulated by the attacker to give an inflated
* (or reduced) value produced by this function, based on current on-chain
* conditions (e.g. this function is possible to influence through
* flashloan attacks, oracle manipulations, or other DeFi attack
* mechanisms).
*
* It is up to governance to use this function to correctly order this
* Strategy relative to its peers in the withdrawal queue to minimize
* losses for the Vault based on sudden withdrawals. This value should be
* higher than the total debt of the Strategy and higher than its expected
* value to be "safe".
* @return The estimated total assets in this Strategy.
*/
function estimatedTotalAssets() public view virtual returns (uint256);
/*
* @notice
* Provide an indication of whether this strategy is currently "active"
* in that it is managing an active position, or will manage a position in
* the future. This should correlate to `harvest()` activity, so that Harvest
* events can be tracked externally by indexing agents.
* @return True if the strategy is actively managing a position.
*/
function isActive() public view returns (bool) {
return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0;
}
/**
* Perform any Strategy unwinding or other calls necessary to capture the
* "free return" this Strategy has generated since the last time its core
* position(s) were adjusted. Examples include unwrapping extra rewards.
* This call is only used during "normal operation" of a Strategy, and
* should be optimized to minimize losses as much as possible.
*
* This method returns any realized profits and/or realized losses
* incurred, and should return the total amounts of profits/losses/debt
* payments (in `want` tokens) for the Vault's accounting (e.g.
* `want.balanceOf(this) >= _debtPayment + _profit`).
*
* `_debtOutstanding` will be 0 if the Strategy is not past the configured
* debt limit, otherwise its value will be how far past the debt limit
* the Strategy is. The Strategy's debt limit is configured in the Vault.
*
* NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`.
* It is okay for it to be less than `_debtOutstanding`, as that
* should only used as a guide for how much is left to pay back.
* Payments should be made to minimize loss from slippage, debt,
* withdrawal fees, etc.
*
* See `vault.debtOutstanding()`.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
);
/**
* Perform any adjustments to the core position(s) of this Strategy given
* what change the Vault made in the "investable capital" available to the
* Strategy. Note that all "free capital" in the Strategy after the report
* was made is available for reinvestment. Also note that this number
* could be 0, and you should handle that scenario accordingly.
*
* See comments regarding `_debtOutstanding` on `prepareReturn()`.
*/
function adjustPosition(uint256 _debtOutstanding) internal virtual;
/**
* Liquidate up to `_amountNeeded` of `want` of this strategy's positions,
* irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.
* This function should return the amount of `want` tokens made available by the
* liquidation. If there is a difference between them, `_loss` indicates whether the
* difference is due to a realized loss, or if there is some other sitution at play
* (e.g. locked funds) where the amount made available is less than what is needed.
*
* NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained
*/
function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss);
/**
* Liquidate everything and returns the amount that got freed.
* This function is used during emergency exit instead of `prepareReturn()` to
* liquidate all of the Strategy's positions back to the Vault.
*/
function liquidateAllPositions() internal virtual returns (uint256 _amountFreed);
/**
* @notice
* Provide a signal to the keeper that `tend()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `tend()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `tend()` is not called
* shortly, then this can return `true` even if the keeper might be
* "at a loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCostInWei` must be priced in terms of `wei` (1e-18 ETH).
*
* This call and `harvestTrigger()` should never return `true` at the same
* time.
* @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei).
* @return `true` if `tend()` should be called, `false` otherwise.
*/
function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) {
// We usually don't need tend, but if there are positions that need
// active maintainence, overriding this function is how you would
// signal for that.
// If your implementation uses the cost of the call in want, you can
// use uint256 callCost = ethToWant(callCostInWei);
return false;
}
/**
* @notice
* Adjust the Strategy's position. The purpose of tending isn't to
* realize gains, but to maximize yield by reinvesting any returns.
*
* See comments on `adjustPosition()`.
*
* This may only be called by governance, the strategist, or the keeper.
*/
function tend() external onlyKeepers {
// Don't take profits with this call, but adjust for better gains
adjustPosition(vault.debtOutstanding());
}
/**
* @notice
* Provide a signal to the keeper that `harvest()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `harvest()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `harvest()` is not called
* shortly, then this can return `true` even if the keeper might be "at a
* loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCostInWei` must be priced in terms of `wei` (1e-18 ETH).
*
* This call and `tendTrigger` should never return `true` at the
* same time.
*
* See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the
* strategist-controlled parameters that will influence whether this call
* returns `true` or not. These parameters will be used in conjunction
* with the parameters reported to the Vault (see `params`) to determine
* if calling `harvest()` is merited.
*
* It is expected that an external system will check `harvestTrigger()`.
* This could be a script run off a desktop or cloud bot (e.g.
* https://github.com/iearn-finance/yearn-vaults/blob/main/scripts/keep.py),
* or via an integration with the Keep3r network (e.g.
* https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol).
* @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei).
* @return `true` if `harvest()` should be called, `false` otherwise.
*/
function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) {
uint256 callCost = ethToWant(callCostInWei);
StrategyParams memory params = vault.strategies(address(this));
// Should not trigger if Strategy is not activated
if (params.activation == 0) return false;
// Should not trigger if we haven't waited long enough since previous harvest
if (block.timestamp.sub(params.lastReport) < minReportDelay) return false;
// Should trigger if hasn't been called in a while
if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true;
// If some amount is owed, pay it back
// NOTE: Since debt is based on deposits, it makes sense to guard against large
// changes to the value from triggering a harvest directly through user
// behavior. This should ensure reasonable resistance to manipulation
// from user-initiated withdrawals as the outstanding debt fluctuates.
uint256 outstanding = vault.debtOutstanding();
if (outstanding > debtThreshold) return true;
// Check for profits and losses
uint256 total = estimatedTotalAssets();
// Trigger if we have a loss to report
if (total.add(debtThreshold) < params.totalDebt) return true;
uint256 profit = 0;
if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit!
// Otherwise, only trigger if it "makes sense" economically (gas cost
// is <N% of value moved)
uint256 credit = vault.creditAvailable();
return (profitFactor.mul(callCost) < credit.add(profit));
}
/**
* @notice
* Harvests the Strategy, recognizing any profits or losses and adjusting
* the Strategy's position.
*
* In the rare case the Strategy is in emergency shutdown, this will exit
* the Strategy's position.
*
* This may only be called by governance, the strategist, or the keeper.
* @dev
* When `harvest()` is called, the Strategy reports to the Vault (via
* `vault.report()`), so in some cases `harvest()` must be called in order
* to take in profits, to borrow newly available funds from the Vault, or
* otherwise adjust its position. In other cases `harvest()` must be
* called to report to the Vault on the Strategy's position, especially if
* any losses have occurred.
*/
function harvest() external onlyKeepers {
uint256 profit = 0;
uint256 loss = 0;
uint256 debtOutstanding = vault.debtOutstanding();
uint256 debtPayment = 0;
if (emergencyExit) {
// Free up as much capital as possible
uint256 amountFreed = liquidateAllPositions();
if (amountFreed < debtOutstanding) {
loss = debtOutstanding.sub(amountFreed);
} else if (amountFreed > debtOutstanding) {
profit = amountFreed.sub(debtOutstanding);
}
debtPayment = debtOutstanding.sub(loss);
} else {
// Free up returns for Vault to pull
(profit, loss, debtPayment) = prepareReturn(debtOutstanding);
}
// Allow Vault to take up to the "harvested" balance of this contract,
// which is the amount it has earned since the last time it reported to
// the Vault.
uint256 totalDebt = vault.strategies(address(this)).totalDebt;
debtOutstanding = vault.report(profit, loss, debtPayment);
// Check if free returns are left, and re-invest them
adjustPosition(debtOutstanding);
// call healthCheck contract
if (doHealthCheck && healthCheck != address(0)) {
require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck");
} else {
doHealthCheck = true;
}
emit Harvested(profit, loss, debtPayment, debtOutstanding);
}
/**
* @notice
* Withdraws `_amountNeeded` to `vault`.
*
* This may only be called by the Vault.
* @param _amountNeeded How much `want` to withdraw.
* @return _loss Any realized losses
*/
function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) {
require(msg.sender == address(vault), "!vault");
// Liquidate as much as possible to `want`, up to `_amountNeeded`
uint256 amountFreed;
(amountFreed, _loss) = liquidatePosition(_amountNeeded);
// Send it directly back (NOTE: Using `msg.sender` saves some gas here)
want.safeTransfer(msg.sender, amountFreed);
// NOTE: Reinvest anything leftover on next `tend`/`harvest`
}
/**
* Do anything necessary to prepare this Strategy for migration, such as
* transferring any reserve or LP tokens, CDPs, or other tokens or stores of
* value.
*/
function prepareMigration(address _newStrategy) internal virtual;
/**
* @notice
* Transfers all `want` from this Strategy to `_newStrategy`.
*
* This may only be called by the Vault.
* @dev
* The new Strategy's Vault must be the same as this Strategy's Vault.
* The migration process should be carefully performed to make sure all
* the assets are migrated to the new address, which should have never
* interacted with the vault before.
* @param _newStrategy The Strategy to migrate to.
*/
function migrate(address _newStrategy) external {
require(msg.sender == address(vault));
require(BaseStrategy(_newStrategy).vault() == vault);
prepareMigration(_newStrategy);
want.safeTransfer(_newStrategy, want.balanceOf(address(this)));
}
/**
* @notice
* Activates emergency exit. Once activated, the Strategy will exit its
* position upon the next harvest, depositing all funds into the Vault as
* quickly as is reasonable given on-chain conditions.
*
* This may only be called by governance or the strategist.
* @dev
* See `vault.setEmergencyShutdown()` and `harvest()` for further details.
*/
function setEmergencyExit() external onlyEmergencyAuthorized {
emergencyExit = true;
vault.revokeStrategy();
emit EmergencyExitEnabled();
}
/**
* Override this to add all tokens/tokenized positions this contract
* manages on a *persistent* basis (e.g. not just for swapping back to
* want ephemerally).
*
* NOTE: Do *not* include `want`, already included in `sweep` below.
*
* Example:
* ```
* function protectedTokens() internal override view returns (address[] memory) {
* address[] memory protected = new address[](3);
* protected[0] = tokenA;
* protected[1] = tokenB;
* protected[2] = tokenC;
* return protected;
* }
* ```
*/
function protectedTokens() internal view virtual returns (address[] memory);
/**
* @notice
* Removes tokens from this Strategy that are not the type of tokens
* managed by this Strategy. This may be used in case of accidentally
* sending the wrong kind of token to this Strategy.
*
* Tokens will be sent to `governance()`.
*
* This will fail if an attempt is made to sweep `want`, or any tokens
* that are protected by this Strategy.
*
* This may only be called by governance.
* @dev
* Implement `protectedTokens()` to specify any additional tokens that
* should be protected from sweeping in addition to `want`.
* @param _token The token to transfer out of this vault.
*/
function sweep(address _token) external onlyGovernance {
require(_token != address(want), "!want");
require(_token != address(vault), "!shares");
address[] memory _protectedTokens = protectedTokens();
for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected");
IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this)));
}
}
// Part: FlashLoanLib
library FlashLoanLib {
using SafeMath for uint256;
event Leverage(uint256 amountRequested, uint256 amountGiven, bool deficit, address flashLoan);
uint256 constant private PRICE_DECIMALS = 1e6;
uint256 constant private WETH_DECIMALS = 1e18;
uint256 constant private COLLAT_RATIO_ETH = 0.74 ether;
address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address private constant WBTC = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599;
ComptrollerI private constant COMP = ComptrollerI(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
ISoloMargin public constant SOLO = ISoloMargin(0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e);
CEtherI public constant CETH = CEtherI(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5);
function doDyDxFlashLoan(bool deficit, uint256 amountDesired, address want) public returns (uint256) {
if(amountDesired == 0){
return 0;
}
// calculate amount of ETH we need
(uint256 requiredETH, uint256 amountWant)= getFlashLoanParams(want, amountDesired);
// Array of actions to be done during FlashLoan
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
// 1. Take FlashLoan
operations[0] = _getWithdrawAction(0, requiredETH); // hardcoded market ID to 0 (ETH)
// 2. Encode arguments of functions and create action for calling it
bytes memory data = abi.encode(deficit, amountWant);
operations[1] = _getCallAction(
data
);
// 3. Repay FlashLoan
operations[2] = _getDepositAction(0, requiredETH.add(2));
// Create Account Info
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
SOLO.operate(accountInfos, operations);
emit Leverage(amountDesired, requiredETH, deficit, address(SOLO));
return amountWant; // we need to return the amount of Want we have changed our position in
}
function getFlashLoanParams(address want, uint256 amountDesired) internal returns (uint256 requiredETH, uint256 amountWant) {
(uint256 priceETHWant, uint256 decimalsDifference, uint256 _requiredETH) = getPriceETHWant(want, amountDesired);
// to avoid stack too deep
requiredETH = _requiredETH;
amountWant = amountDesired;
// Not enough want in DyDx. So we take all we can
uint256 dxdyLiquidity = IERC20(WETH).balanceOf(address(SOLO));
if(requiredETH > dxdyLiquidity) {
requiredETH = dxdyLiquidity;
// NOTE: if we cap amountETH, we reduce amountWant we are taking too
amountWant = requiredETH.mul(COLLAT_RATIO_ETH).div(priceETHWant).div(1e18).div(decimalsDifference);
}
}
function getPriceETHWant(address want, uint256 amountDesired) internal returns (uint256 priceETHWant, uint256 decimalsDifference, uint256 requiredETH) {
uint256 wantDecimals = 10 ** uint256(IERC20Extended(want).decimals());
decimalsDifference = WETH_DECIMALS > wantDecimals ? WETH_DECIMALS.div(wantDecimals) : wantDecimals.div(WETH_DECIMALS);
if(want == WETH) {
requiredETH = amountDesired.mul(1e18).div(COLLAT_RATIO_ETH);
priceETHWant = 1e6; // 1:1
} else {
priceETHWant = getOraclePrice(WETH).mul(PRICE_DECIMALS).div(getOraclePrice(want));
// requiredETH = desiredWantInETH / COLLAT_RATIO_ETH
// desiredWBTCInETH = (desiredWant / priceETHWant)
// NOTE: decimals need adjustment (e.g. BTC: 8 / ETH: 18)
requiredETH = amountDesired.mul(PRICE_DECIMALS).mul(1e18).mul(decimalsDifference).div(priceETHWant).div(COLLAT_RATIO_ETH);
}
}
function getOraclePrice(address token) internal returns (uint256) {
string memory symbol = IERC20Extended(token).symbol();
// Symbol for WBTC is BTC in oracle
if(token == WBTC) {
symbol = "BTC";
} else if (token == WETH) {
symbol = "ETH";
}
IUniswapAnchoredView oracle = IUniswapAnchoredView(COMP.oracle());
return oracle.price(symbol);
}
function loanLogic(
bool deficit,
uint256 amount,
CErc20I cToken
) public {
uint256 wethBalance = IERC20(WETH).balanceOf(address(this));
// 0. Unwrap WETH
IWETH(WETH).withdraw(wethBalance);
// 1. Deposit ETH in Compound as collateral
// will revert if it fails
CETH.mint{value: wethBalance}();
//if in deficit we repay amount and then withdraw
if (deficit) {
// 2a. if in deficit withdraw amount and repay it
require(cToken.redeemUnderlying(amount) == 0, "!redeem_down");
require(cToken.repayBorrow(IERC20(cToken.underlying()).balanceOf(address(this))) == 0, "!repay_down");
} else {
// 2b. if levering up borrow and deposit
require(cToken.borrow(amount) == 0, "!borrow_up");
require(cToken.mint(IERC20(cToken.underlying()).balanceOf(address(this))) == 0, "!mint_up");
}
// 3. Redeem collateral (ETH borrowed from DyDx) from Compound
require(CETH.redeemUnderlying(wethBalance) == 0, "!redeem");
// 4. Wrap ETH into WETH
IWETH(WETH).deposit{value: address(this).balance}();
// NOTE: after this, WETH will be taken by DyDx
}
function _getAccountInfo() internal view returns (Account.Info memory) {
return Account.Info({owner: address(this), number: 1});
}
function _getWithdrawAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) { return
Actions.ActionArgs({
actionType: Actions.ActionType.Withdraw,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: ""
});
}
function _getCallAction(bytes memory data) internal view returns (Actions.ActionArgs memory) {
return
Actions.ActionArgs({
actionType: Actions.ActionType.Call,
accountId: 0,
amount: Types.AssetAmount({sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0}),
primaryMarketId: 0,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: data
});
}
function _getDepositAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) {
return
Actions.ActionArgs({
actionType: Actions.ActionType.Deposit,
accountId: 0,
amount: Types.AssetAmount({
sign: true,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: ""
});
}
}
// Part: Strategy
contract Strategy is BaseStrategy, ICallee {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
// @notice emitted when trying to do Flash Loan. flashLoan address is 0x00 when no flash loan used
event Leverage(uint256 amountRequested, uint256 amountGiven, bool deficit, address flashLoan);
// Comptroller address for compound.finance
ComptrollerI private constant compound = ComptrollerI(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
//Only three tokens we use
address private constant comp = 0xc00e94Cb662C3520282E6f5717214004A7f26888;
address private constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
CErc20I public cToken;
bool public useUniV3;
// fee pool to use in UniV3 in basis points(default: 0.3% = 3000)
uint24 public compToWethSwapFee;
uint24 public wethToWantSwapFee;
IUniswapV2Router02 public currentV2Router;
IUniswapV2Router02 private constant UNI_V2_ROUTER =
IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
IUniswapV2Router02 private constant SUSHI_V2_ROUTER =
IUniswapV2Router02(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F);
IUniswapV3Router private constant UNI_V3_ROUTER =
IUniswapV3Router(0xE592427A0AEce92De3Edee1F18E0157C05861564);
uint256 public collateralTarget; // total borrow / total supply ratio we are targeting (100% = 1e18)
uint256 public blocksToLiquidationDangerZone; // minimum number of blocks before liquidation
uint256 public minWant; // minimum amount of want to act on
// Rewards handling
bool public dontClaimComp; // enable/disables COMP claiming
uint256 public minCompToSell; // minimum amount of COMP to be sold
bool public DyDxActive; // To deactivate flash loan provider if needed
bool public forceMigrate;
constructor(address _vault, address _cToken) public BaseStrategy(_vault) {
_initializeThis(_cToken);
}
function approveTokenMax(address token, address spender) internal {
IERC20(token).safeApprove(spender, type(uint256).max);
}
// To receive ETH from compound and WETH contract
receive() external payable {}
function name() external override view returns (string memory){
return "GenLevCompV2";
}
function initialize(
address _vault,
address _cToken
) external {
_initialize(_vault, msg.sender, msg.sender, msg.sender);
_initializeThis(_cToken);
}
function _initializeThis(address _cToken) internal {
cToken = CErc20I(address(_cToken));
currentV2Router = SUSHI_V2_ROUTER;
//pre-set approvals
approveTokenMax(comp, address(UNI_V2_ROUTER));
approveTokenMax(comp, address(SUSHI_V2_ROUTER));
approveTokenMax(comp, address(UNI_V3_ROUTER));
approveTokenMax(address(want), address(cToken));
approveTokenMax(weth, address(FlashLoanLib.SOLO));
// Enter Compound's ETH market to take it into account when using ETH as collateral
address[] memory markets = new address[](2);
markets[0] = address(FlashLoanLib.CETH);
markets[1] = address(cToken);
compound.enterMarkets(markets);
//comp speed is amount to borrow or deposit (so half the total distribution for want)
compToWethSwapFee = 3000;
wethToWantSwapFee = 3000;
// You can set these parameters on deployment to whatever you want
maxReportDelay = 86400; // once per 24 hours
profitFactor = 100; // multiple before triggering harvest
minCompToSell = 0.1 ether;
collateralTarget = 0.63 ether;
blocksToLiquidationDangerZone = 46500;
DyDxActive = true;
}
/*
* Control Functions
*/
function setUniV3PathFees(uint24 _compToWethSwapFee, uint24 _wethToWantSwapFee) external management {
compToWethSwapFee = _compToWethSwapFee;
wethToWantSwapFee = _wethToWantSwapFee;
}
function setDontClaimComp(bool _dontClaimComp) external management {
dontClaimComp = _dontClaimComp;
}
function setUseUniV3(bool _useUniV3) external management {
useUniV3 = _useUniV3;
}
function setToggleV2Router() external management {
currentV2Router = currentV2Router == SUSHI_V2_ROUTER ? UNI_V2_ROUTER : SUSHI_V2_ROUTER;
}
function setDyDx(bool _dydx) external management {
DyDxActive = _dydx;
}
function setForceMigrate(bool _force) external onlyGovernance {
forceMigrate = _force;
}
function setMinCompToSell(uint256 _minCompToSell) external management {
minCompToSell = _minCompToSell;
}
function setMinWant(uint256 _minWant) external management {
minWant = _minWant;
}
function setCollateralTarget(uint256 _collateralTarget) external management {
(, uint256 collateralFactorMantissa, ) = compound.markets(address(cToken));
require(collateralFactorMantissa > _collateralTarget);
collateralTarget = _collateralTarget;
}
/*
* Base External Facing Functions
*/
/*
* An accurate estimate for the total amount of assets (principle + return)
* that this strategy is currently managing, denominated in terms of want tokens.
*/
function estimatedTotalAssets() public override view returns (uint256) {
(uint256 deposits, uint256 borrows) = getCurrentPosition();
uint256 _claimableComp = predictCompAccrued();
uint256 currentComp = balanceOfToken(comp);
// Use touch price. it doesnt matter if we are wrong as this is not used for decision making
uint256 estimatedWant = priceCheck(comp, address(want),_claimableComp.add(currentComp));
uint256 conservativeWant = estimatedWant.mul(9).div(10); //10% pessimist
return balanceOfToken(address(want)).add(deposits).add(conservativeWant).sub(borrows);
}
function balanceOfToken(address token) internal view returns (uint256) {
return IERC20(token).balanceOf(address(this));
}
//predicts our profit at next report
function expectedReturn() public view returns (uint256) {
uint256 estimateAssets = estimatedTotalAssets();
uint256 debt = vault.strategies(address(this)).totalDebt;
if (debt > estimateAssets) {
return 0;
} else {
return estimateAssets.sub(debt);
}
}
/*
* Provide a signal to the keeper that `tend()` should be called.
* (keepers are always reimbursed by yEarn)
*
* NOTE: this call and `harvestTrigger` should never return `true` at the same time.
* tendTrigger should be called with same gasCost as harvestTrigger
*/
function tendTrigger(uint256 gasCost) public override view returns (bool) {
if (harvestTrigger(gasCost)) {
//harvest takes priority
return false;
}
return getblocksUntilLiquidation() <= blocksToLiquidationDangerZone;
}
//WARNING. manipulatable and simple routing. Only use for safe functions
function priceCheck(address start, address end, uint256 _amount) public view returns (uint256) {
if (_amount == 0) {
return 0;
}
uint256[] memory amounts = currentV2Router.getAmountsOut(_amount, getTokenOutPathV2(start, end));
return amounts[amounts.length - 1];
}
/*****************
* Public non-base function
******************/
//Calculate how many blocks until we are in liquidation based on current interest rates
//WARNING does not include compounding so the estimate becomes more innacurate the further ahead we look
//equation. Compound doesn't include compounding for most blocks
//((deposits*colateralThreshold - borrows) / (borrows*borrowrate - deposits*colateralThreshold*interestrate));
function getblocksUntilLiquidation() public view returns (uint256) {
(, uint256 collateralFactorMantissa, ) = compound.markets(address(cToken));
(uint256 deposits, uint256 borrows) = getCurrentPosition();
uint256 borrrowRate = cToken.borrowRatePerBlock();
uint256 supplyRate = cToken.supplyRatePerBlock();
uint256 collateralisedDeposit1 = deposits.mul(collateralFactorMantissa).div(1e18);
uint256 collateralisedDeposit = collateralisedDeposit1;
uint256 denom1 = borrows.mul(borrrowRate);
uint256 denom2 = collateralisedDeposit.mul(supplyRate);
if (denom2 >= denom1) {
return type(uint256).max;
} else {
uint256 numer = collateralisedDeposit.sub(borrows);
uint256 denom = denom1.sub(denom2);
//minus 1 for this block
return numer.mul(1e18).div(denom);
}
}
// This function makes a prediction on how much comp is accrued
// It is not 100% accurate as it uses current balances in Compound to predict into the past
function predictCompAccrued() public view returns (uint256) {
(uint256 deposits, uint256 borrows) = getCurrentPosition();
if (deposits == 0) {
return 0; // should be impossible to have 0 balance and positive comp accrued
}
uint256 distributionPerBlockSupply = compound.compSupplySpeeds(address(cToken));
uint256 distributionPerBlockBorrow = compound.compBorrowSpeeds(address(cToken));
uint256 totalBorrow = cToken.totalBorrows();
//total supply needs to be echanged to underlying using exchange rate
uint256 totalSupplyCtoken = cToken.totalSupply();
uint256 totalSupply = totalSupplyCtoken.mul(cToken.exchangeRateStored()).div(1e18);
uint256 blockShareSupply = 0;
if(totalSupply > 0) {
blockShareSupply = deposits.mul(distributionPerBlockSupply).div(totalSupply);
}
uint256 blockShareBorrow = 0;
if(totalBorrow > 0) {
blockShareBorrow = borrows.mul(distributionPerBlockBorrow).div(totalBorrow);
}
//how much we expect to earn per block
uint256 blockShare = blockShareSupply.add(blockShareBorrow);
//last time we ran harvest
uint256 lastReport = vault.strategies(address(this)).lastReport;
uint256 blocksSinceLast= (block.timestamp.sub(lastReport)).div(13); //roughly 13 seconds per block
return blocksSinceLast.mul(blockShare);
}
//Returns the current position
//WARNING - this returns just the balance at last time someone touched the cToken token. Does not accrue interst in between
//cToken is very active so not normally an issue.
function getCurrentPosition() public view returns (uint256 deposits, uint256 borrows) {
(, uint256 ctokenBalance, uint256 borrowBalance, uint256 exchangeRate) = cToken.getAccountSnapshot(address(this));
borrows = borrowBalance;
deposits = ctokenBalance.mul(exchangeRate).div(1e18);
}
//statechanging version
function getLivePosition() public returns (uint256 deposits, uint256 borrows) {
deposits = cToken.balanceOfUnderlying(address(this));
//we can use non state changing now because we updated state with balanceOfUnderlying call
borrows = cToken.borrowBalanceStored(address(this));
}
//Same warning as above
function netBalanceLent() public view returns (uint256) {
(uint256 deposits, uint256 borrows) = getCurrentPosition();
return deposits.sub(borrows);
}
/***********
* internal core logic
*********** */
/*
* A core method.
* Called at beggining of harvest before providing report to owner
* 1 - claim accrued comp
* 2 - if enough to be worth it we sell
* 3 - because we lose money on our loans we need to offset profit from comp.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
_profit = 0;
_loss = 0; //for clarity. also reduces bytesize
if (balanceOfToken(address(cToken)) == 0) {
uint256 wantBalance = balanceOfToken(address(want));
//no position to harvest
//but we may have some debt to return
//it is too expensive to free more debt in this method so we do it in adjust position
_debtPayment = Math.min(wantBalance, _debtOutstanding);
return (_profit, _loss, _debtPayment);
}
(uint256 deposits, uint256 borrows) = getLivePosition();
//claim comp accrued
_claimComp();
//sell comp
_disposeOfComp();
uint256 wantBalance = balanceOfToken(address(want));
uint256 investedBalance = deposits.sub(borrows);
uint256 balance = investedBalance.add(wantBalance);
uint256 debt = vault.strategies(address(this)).totalDebt;
//Balance - Total Debt is profit
if (balance > debt) {
_profit = balance.sub(debt);
if (wantBalance < _profit) {
//all reserve is profit
_profit = wantBalance;
} else if (wantBalance > _profit.add(_debtOutstanding)) {
_debtPayment = _debtOutstanding;
} else {
_debtPayment = wantBalance.sub(_profit);
}
} else {
//we will lose money until we claim comp then we will make money
//this has an unintended side effect of slowly lowering our total debt allowed
_loss = debt.sub(balance);
_debtPayment = Math.min(wantBalance, _debtOutstanding);
}
}
/*
* Second core function. Happens after report call.
*
* Similar to deposit function from V1 strategy
*/
function adjustPosition(uint256 _debtOutstanding) internal override {
//emergency exit is dealt with in prepareReturn
if (emergencyExit) {
return;
}
//we are spending all our cash unless we have debt outstanding
uint256 _wantBal = balanceOfToken(address(want));
if(_wantBal < _debtOutstanding){
//this is graceful withdrawal. dont use backup
//we use more than 1 because withdrawunderlying causes problems with 1 token due to different decimals
if(balanceOfToken(address(cToken)) > 1){
_withdrawSome(_debtOutstanding.sub(_wantBal));
}
return;
}
(uint256 position, bool deficit) = _calculateDesiredPosition(_wantBal - _debtOutstanding, true);
//if we are below minimun want change it is not worth doing
//need to be careful in case this pushes to liquidation
if (position > minWant) {
//if dydx is not active we just try our best with basic leverage
if (!DyDxActive) {
uint i = 0;
while(position > 0){
position = position.sub(_noFlashLoan(position, deficit));
if(i >= 6){
break;
}
i++;
}
} else {
//if there is huge position to improve we want to do normal leverage. it is quicker
if (position > want.balanceOf(address(FlashLoanLib.SOLO))) {
position = position.sub(_noFlashLoan(position, deficit));
}
//flash loan to position
if(position > minWant){
doDyDxFlashLoan(deficit, position);
}
}
}
}
/*************
* Very important function
* Input: amount we want to withdraw and whether we are happy to pay extra for Aave.
* cannot be more than we have
* Returns amount we were able to withdraw. notall if user has some balance left
*
* Deleverage position -> redeem our cTokens
******************** */
function _withdrawSome(uint256 _amount) internal returns (bool notAll) {
(uint256 position, bool deficit) = _calculateDesiredPosition(_amount, false);
//If there is no deficit we dont need to adjust position
//if the position change is tiny do nothing
if (deficit && position > minWant) {
//we do a flash loan to give us a big gap. from here on out it is cheaper to use normal deleverage.
if (DyDxActive) {
position = position.sub(doDyDxFlashLoan(deficit, position));
}
uint8 i = 0;
//position will equal 0 unless we haven't been able to deleverage enough with flash loan
//if we are not in deficit we dont need to do flash loan
while (position > minWant.add(100)) {
position = position.sub(_noFlashLoan(position, true));
i++;
//A limit set so we don't run out of gas
if (i >= 5) {
notAll = true;
break;
}
}
}
//now withdraw
//if we want too much we just take max
//This part makes sure our withdrawal does not force us into liquidation
(uint256 depositBalance, uint256 borrowBalance) = getCurrentPosition();
uint256 tempColla = collateralTarget;
uint256 reservedAmount = 0;
if(tempColla == 0){
tempColla = 1e15; // 0.001 * 1e18. lower we have issues
}
reservedAmount = borrowBalance.mul(1e18).div(tempColla);
if(depositBalance >= reservedAmount){
uint256 redeemable = depositBalance.sub(reservedAmount);
if (redeemable < _amount) {
cToken.redeemUnderlying(redeemable);
} else {
cToken.redeemUnderlying(_amount);
}
}
if(collateralTarget == 0 && balanceOfToken(address(want)) > borrowBalance){
cToken.repayBorrow(borrowBalance);
}
}
/***********
* This is the main logic for calculating how to change our lends and borrows
* Input: balance. The net amount we are going to deposit/withdraw.
* Input: dep. Is it a deposit or withdrawal
* Output: position. The amount we want to change our current borrow position.
* Output: deficit. True if we are reducing position size
*
* For instance deficit =false, position 100 means increase borrowed balance by 100
****** */
function _calculateDesiredPosition(uint256 balance, bool dep) internal returns (uint256 position, bool deficit) {
//we want to use statechanging for safety
(uint256 deposits, uint256 borrows) = getLivePosition();
//When we unwind we end up with the difference between borrow and supply
uint256 unwoundDeposit = deposits.sub(borrows);
//we want to see how close to collateral target we are.
//So we take our unwound deposits and add or remove the balance we are are adding/removing.
//This gives us our desired future undwoundDeposit (desired supply)
uint256 desiredSupply = 0;
if (dep) {
desiredSupply = unwoundDeposit.add(balance);
} else {
if(balance > unwoundDeposit) balance = unwoundDeposit;
desiredSupply = unwoundDeposit.sub(balance);
}
//(ds *c)/(1-c)
uint256 num = desiredSupply.mul(collateralTarget);
uint256 den = uint256(1e18).sub(collateralTarget);
uint256 desiredBorrow = num.div(den);
if (desiredBorrow > 1e5) {
//stop us going right up to the wire
desiredBorrow = desiredBorrow.sub(1e5);
}
//now we see if we want to add or remove balance
// if the desired borrow is less than our current borrow we are in deficit. so we want to reduce position
if (desiredBorrow < borrows) {
deficit = true;
position = borrows.sub(desiredBorrow); //safemath check done in if statement
} else {
//otherwise we want to increase position
deficit = false;
position = desiredBorrow.sub(borrows);
}
}
/*
* Liquidate as many assets as possible to `want`, irregardless of slippage,
* up to `_amount`. Any excess should be re-invested here as well.
*/
function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) {
uint256 _balance = balanceOfToken(address(want));
uint256 assets = netBalanceLent().add(_balance);
uint256 debtOutstanding = vault.debtOutstanding();
if(debtOutstanding > assets){
_loss = debtOutstanding.sub(assets);
}
if (assets < _amountNeeded) {
//if we cant afford to withdraw we take all we can
//withdraw all we can
(uint256 deposits, uint256 borrows) = getLivePosition();
//1 token causes rounding error with withdrawUnderlying
if(balanceOfToken(address(cToken)) > 1){
_withdrawSome(deposits.sub(borrows));
}
_amountFreed = Math.min(_amountNeeded, balanceOfToken(address(want)));
} else {
if (_balance < _amountNeeded) {
_withdrawSome(_amountNeeded.sub(_balance));
//overflow error if we return more than asked for
_amountFreed = Math.min(_amountNeeded, balanceOfToken(address(want)));
}else{
_amountFreed = _amountNeeded;
}
}
}
function _claimComp() internal {
if(dontClaimComp) {
return;
}
CTokenI[] memory tokens = new CTokenI[](1);
tokens[0] = cToken;
compound.claimComp(address(this), tokens);
}
//sell comp function
function _disposeOfComp() internal {
uint256 _comp = balanceOfToken(comp);
if (_comp < minCompToSell) {
return;
}
if (useUniV3) {
UNI_V3_ROUTER.exactInput(
IUniswapV3Router.ExactInputParams(
getTokenOutPathV3(comp, address(want)),
address(this),
now,
_comp,
0
)
);
} else {
currentV2Router.swapExactTokensForTokens(
_comp,
0,
getTokenOutPathV2(comp, address(want)),
address(this),
now
);
}
}
function getTokenOutPathV2(address _tokenIn, address _tokenOut)
internal
pure
returns (address[] memory _path)
{
bool isWeth =
_tokenIn == address(weth) || _tokenOut == address(weth);
_path = new address[](isWeth ? 2 : 3);
_path[0] = _tokenIn;
if (isWeth) {
_path[1] = _tokenOut;
} else {
_path[1] = address(weth);
_path[2] = _tokenOut;
}
}
function getTokenOutPathV3(address _tokenIn, address _tokenOut)
internal
view
returns (bytes memory _path)
{
if (address(want) == weth) {
_path = abi.encodePacked(
address(_tokenIn),
compToWethSwapFee,
address(weth)
);
} else {
_path = abi.encodePacked(
address(_tokenIn),
compToWethSwapFee,
address(weth),
wethToWantSwapFee,
address(_tokenOut)
);
}
}
//lets leave
//if we can't deleverage in one go set collateralFactor to 0 and call harvest multiple times until delevered
function prepareMigration(address _newStrategy) internal override {
if(!forceMigrate){
(uint256 deposits, uint256 borrows) = getLivePosition();
_withdrawSome(deposits.sub(borrows));
(, , uint256 borrowBalance, ) = cToken.getAccountSnapshot(address(this));
require(borrowBalance < 10_000);
IERC20 _comp = IERC20(comp);
uint _compB = balanceOfToken(address(_comp));
if(_compB > 0){
_comp.safeTransfer(_newStrategy, _compB);
}
}
}
//Three functions covering normal leverage and deleverage situations
// max is the max amount we want to increase our borrowed balance
// returns the amount we actually did
function _noFlashLoan(uint256 max, bool deficit) internal returns (uint256 amount) {
//we can use non-state changing because this function is always called after _calculateDesiredPosition
(uint256 lent, uint256 borrowed) = getCurrentPosition();
//if we have nothing borrowed then we can't deleverage any more
if (borrowed == 0 && deficit) {
return 0;
}
(, uint256 collateralFactorMantissa, ) = compound.markets(address(cToken));
if (deficit) {
amount = _normalDeleverage(max, lent, borrowed, collateralFactorMantissa);
} else {
amount = _normalLeverage(max, lent, borrowed, collateralFactorMantissa);
}
emit Leverage(max, amount, deficit, address(0));
}
//maxDeleverage is how much we want to reduce by
function _normalDeleverage(
uint256 maxDeleverage,
uint256 lent,
uint256 borrowed,
uint256 collatRatio
) internal returns (uint256 deleveragedAmount) {
uint256 theoreticalLent = 0;
//collat ration should never be 0. if it is something is very wrong... but just incase
if(collatRatio != 0){
theoreticalLent = borrowed.mul(1e18).div(collatRatio);
}
deleveragedAmount = lent.sub(theoreticalLent);
if (deleveragedAmount >= borrowed) {
deleveragedAmount = borrowed;
}
if (deleveragedAmount >= maxDeleverage) {
deleveragedAmount = maxDeleverage;
}
uint256 exchangeRateStored = cToken.exchangeRateStored();
//redeemTokens = redeemAmountIn *1e18 / exchangeRate. must be more than 0
//a rounding error means we need another small addition
if(deleveragedAmount.mul(1e18) >= exchangeRateStored && deleveragedAmount > 10){
deleveragedAmount = deleveragedAmount.sub(uint256(10));
cToken.redeemUnderlying(deleveragedAmount);
//our borrow has been increased by no more than maxDeleverage
cToken.repayBorrow(deleveragedAmount);
}
}
//maxDeleverage is how much we want to increase by
function _normalLeverage(
uint256 maxLeverage,
uint256 lent,
uint256 borrowed,
uint256 collatRatio
) internal returns (uint256 leveragedAmount) {
uint256 theoreticalBorrow = lent.mul(collatRatio).div(1e18);
leveragedAmount = theoreticalBorrow.sub(borrowed);
if (leveragedAmount >= maxLeverage) {
leveragedAmount = maxLeverage;
}
if(leveragedAmount > 10){
leveragedAmount = leveragedAmount.sub(uint256(10));
cToken.borrow(leveragedAmount);
cToken.mint(balanceOfToken(address(want)));
}
}
//emergency function that we can use to deleverage manually if something is broken
function manualDeleverage(uint256 amount) external management{
require(cToken.redeemUnderlying(amount) == 0);
require(cToken.repayBorrow(amount) == 0);
}
//emergency function that we can use to deleverage manually if something is broken
function manualReleaseWant(uint256 amount) external onlyGovernance{
require(cToken.redeemUnderlying(amount) ==0);
}
function protectedTokens() internal override view returns (address[] memory) {
}
/******************
* Flash loan stuff
****************/
// Flash loan DXDY
// amount desired is how much we are willing for position to change
function doDyDxFlashLoan(bool deficit, uint256 amountDesired) internal returns (uint256) {
return FlashLoanLib.doDyDxFlashLoan(deficit, amountDesired, address(want));
}
//returns our current collateralisation ratio. Should be compared with collateralTarget
function storedCollateralisation() public view returns (uint256 collat) {
(uint256 lend, uint256 borrow) = getCurrentPosition();
if (lend == 0) {
return 0;
}
collat = uint256(1e18).mul(borrow).div(lend);
}
//DyDx calls this function after doing flash loan
function callFunction(
address sender,
Account.Info memory account,
bytes memory data
) public override {
(bool deficit, uint256 amount) = abi.decode(data, (bool, uint256));
require(msg.sender == address(FlashLoanLib.SOLO));
require(sender == address(this));
FlashLoanLib.loanLogic(deficit, amount, cToken);
}
// -- Internal Helper functions -- //
function ethToWant(uint256 _amtInWei) public view override returns (uint256) {
return priceCheck(weth, address(want), _amtInWei);
}
function liquidateAllPositions() internal override returns (uint256 _amountFreed) {
(_amountFreed,) = liquidatePosition(vault.debtOutstanding());
(uint256 deposits, uint256 borrows) = getCurrentPosition();
uint256 position = deposits.sub(borrows);
//we want to revert if we can't liquidateall
if(!forceMigrate) {
require(position < minWant);
}
}
function mgtm_check() internal view {
require(msg.sender == governance() || msg.sender == vault.management() || msg.sender == strategist);
}
modifier management() {
mgtm_check();
_;
}
}
// File: LevCompFactory.sol
contract LevCompFactory {
address public immutable original;
event Cloned(address indexed clone);
event Deployed(address indexed original);
constructor(
address _vault,
address _cToken
) public {
Strategy _original = new Strategy(_vault, _cToken);
emit Deployed(address(_original));
original = address(_original);
_original.setStrategist(msg.sender);
}
function name() external view returns (string memory) {
return string(abi.encodePacked("Factory", Strategy(payable(original)).name(), "@", Strategy(payable(original)).apiVersion()));
}
function cloneLevComp(
address _vault,
address _cToken
) external returns (address payable newStrategy) {
// Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol
bytes20 addressBytes = bytes20(original);
assembly {
// EIP-1167 bytecode
let clone_code := mload(0x40)
mstore(
clone_code,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
mstore(add(clone_code, 0x14), addressBytes)
mstore(
add(clone_code, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
newStrategy := create(0, clone_code, 0x37)
}
Strategy(newStrategy).initialize(_vault, _cToken);
Strategy(newStrategy).setStrategist(msg.sender);
emit Cloned(newStrategy);
}
} | Part: IUniswapAnchoredView | interface IUniswapAnchoredView {
function price(string memory) external returns (uint);
}
| 2,258,850 |
/**
*Submitted for verification at Etherscan.io on 2021-05-14
*/
// File contracts/base/snx-base/interfaces/SNXRewardInterface.sol
pragma solidity 0.5.16;
interface SNXRewardInterface {
function withdraw(uint) external;
function getReward() external;
function stake(uint) external;
function balanceOf(address) external view returns (uint256);
function earned(address account) external view returns (uint256);
function exit() external;
}
// File @openzeppelin/contracts/math/[email protected]
pragma solidity ^0.5.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File @openzeppelin/contracts/math/[email protected]
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity ^0.5.0;
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @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.
*
* 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;
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
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, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File contracts/base/interface/IController.sol
pragma solidity 0.5.16;
interface IController {
event SharePriceChangeLog(
address indexed vault,
address indexed strategy,
uint256 oldSharePrice,
uint256 newSharePrice,
uint256 timestamp
);
// [Grey list]
// An EOA can safely interact with the system no matter what.
// If you're using Metamask, you're using an EOA.
// Only smart contracts may be affected by this grey list.
//
// This contract will not be able to ban any EOA from the system
// even if an EOA is being added to the greyList, he/she will still be able
// to interact with the whole system as if nothing happened.
// Only smart contracts will be affected by being added to the greyList.
// This grey list is only used in Vault.sol, see the code there for reference
function greyList(address _target) external view returns(bool);
function addVaultAndStrategy(address _vault, address _strategy) external;
function doHardWork(address _vault) external;
function hasVault(address _vault) external returns(bool);
function salvage(address _token, uint256 amount) external;
function salvageStrategy(address _strategy, address _token, uint256 amount) external;
function notifyFee(address _underlying, uint256 fee) external;
function profitSharingNumerator() external view returns (uint256);
function profitSharingDenominator() external view returns (uint256);
function feeRewardForwarder() external view returns(address);
function setFeeRewardForwarder(address _value) external;
function addHardWorker(address _worker) external;
}
// File contracts/base/interface/IFeeRewardForwarderV6.sol
pragma solidity 0.5.16;
interface IFeeRewardForwarderV6 {
function poolNotifyFixedTarget(address _token, uint256 _amount) external;
function notifyFeeAndBuybackAmounts(uint256 _feeAmount, address _pool, uint256 _buybackAmount) external;
function notifyFeeAndBuybackAmounts(address _token, uint256 _feeAmount, address _pool, uint256 _buybackAmount) external;
function profitSharingPool() external view returns (address);
function configureLiquidation(address[] calldata _path, bytes32[] calldata _dexes) external;
}
// File contracts/base/inheritance/Storage.sol
pragma solidity 0.5.16;
contract Storage {
address public governance;
address public controller;
constructor() public {
governance = msg.sender;
}
modifier onlyGovernance() {
require(isGovernance(msg.sender), "Not governance");
_;
}
function setGovernance(address _governance) public onlyGovernance {
require(_governance != address(0), "new governance shouldn't be empty");
governance = _governance;
}
function setController(address _controller) public onlyGovernance {
require(_controller != address(0), "new controller shouldn't be empty");
controller = _controller;
}
function isGovernance(address account) public view returns (bool) {
return account == governance;
}
function isController(address account) public view returns (bool) {
return account == controller;
}
}
// File contracts/base/inheritance/Governable.sol
pragma solidity 0.5.16;
contract Governable {
Storage public store;
constructor(address _store) public {
require(_store != address(0), "new storage shouldn't be empty");
store = Storage(_store);
}
modifier onlyGovernance() {
require(store.isGovernance(msg.sender), "Not governance");
_;
}
function setStorage(address _store) public onlyGovernance {
require(_store != address(0), "new storage shouldn't be empty");
store = Storage(_store);
}
function governance() public view returns (address) {
return store.governance();
}
}
// File contracts/base/inheritance/Controllable.sol
pragma solidity 0.5.16;
contract Controllable is Governable {
constructor(address _storage) Governable(_storage) public {
}
modifier onlyController() {
require(store.isController(msg.sender), "Not a controller");
_;
}
modifier onlyControllerOrGovernance(){
require((store.isController(msg.sender) || store.isGovernance(msg.sender)),
"The caller must be controller or governance");
_;
}
function controller() public view returns (address) {
return store.controller();
}
}
// File contracts/base/inheritance/RewardTokenProfitNotifier.sol
pragma solidity 0.5.16;
contract RewardTokenProfitNotifier is Controllable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 public profitSharingNumerator;
uint256 public profitSharingDenominator;
address public rewardToken;
constructor(
address _storage,
address _rewardToken
) public Controllable(_storage){
rewardToken = _rewardToken;
// persist in the state for immutability of the fee
profitSharingNumerator = 30; //IController(controller()).profitSharingNumerator();
profitSharingDenominator = 100; //IController(controller()).profitSharingDenominator();
require(profitSharingNumerator < profitSharingDenominator, "invalid profit share");
}
event ProfitLogInReward(uint256 profitAmount, uint256 feeAmount, uint256 timestamp);
event ProfitAndBuybackLog(uint256 profitAmount, uint256 feeAmount, uint256 timestamp);
function notifyProfitInRewardToken(uint256 _rewardBalance) internal {
if( _rewardBalance > 0 ){
uint256 feeAmount = _rewardBalance.mul(profitSharingNumerator).div(profitSharingDenominator);
emit ProfitLogInReward(_rewardBalance, feeAmount, block.timestamp);
IERC20(rewardToken).safeApprove(controller(), 0);
IERC20(rewardToken).safeApprove(controller(), feeAmount);
IController(controller()).notifyFee(
rewardToken,
feeAmount
);
} else {
emit ProfitLogInReward(0, 0, block.timestamp);
}
}
function notifyProfitAndBuybackInRewardToken(uint256 _rewardBalance, address pool, uint256 _buybackRatio) internal {
if( _rewardBalance > 0 ){
uint256 feeAmount = _rewardBalance.mul(profitSharingNumerator).div(profitSharingDenominator);
address forwarder = IController(controller()).feeRewardForwarder();
emit ProfitAndBuybackLog(_rewardBalance, feeAmount, block.timestamp);
IERC20(rewardToken).safeApprove(forwarder, 0);
IERC20(rewardToken).safeApprove(forwarder, _rewardBalance);
IFeeRewardForwarderV6(forwarder).notifyFeeAndBuybackAmounts(
rewardToken,
feeAmount,
pool,
_rewardBalance.sub(feeAmount).mul(_buybackRatio).div(10000)
);
} else {
emit ProfitAndBuybackLog(0, 0, block.timestamp);
}
}
}
// File contracts/base/interface/IStrategy.sol
pragma solidity 0.5.16;
interface IStrategy {
function unsalvagableTokens(address tokens) external view returns (bool);
function governance() external view returns (address);
function controller() external view returns (address);
function underlying() external view returns (address);
function vault() external view returns (address);
function withdrawAllToVault() external;
function withdrawToVault(uint256 amount) external;
function investedUnderlyingBalance() external view returns (uint256); // itsNotMuch()
// should only be called by controller
function salvage(address recipient, address token, uint256 amount) external;
function doHardWork() external;
function depositArbCheck() external view returns(bool);
}
// File contracts/base/interface/ILiquidator.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.5.16;
interface ILiquidator {
event Swap(
address indexed buyToken,
address indexed sellToken,
address indexed target,
address initiator,
uint256 amountIn,
uint256 slippage,
uint256 total
);
function swapTokenOnMultipleDEXes(
uint256 amountIn,
uint256 amountOutMin,
address target,
bytes32[] calldata dexes,
address[] calldata path
) external;
function swapTokenOnDEX(
uint256 amountIn,
uint256 amountOutMin,
address target,
bytes32 dexName,
address[] calldata path
) external;
function getAllDexes() external view returns (bytes32[] memory);
}
// File contracts/base/interface/ILiquidatorRegistry.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.5.16;
interface ILiquidatorRegistry {
function universalLiquidator() external view returns(address);
function setUniversalLiquidator(address _ul) external;
function getPath(
bytes32 dex,
address inputToken,
address outputToken
) external view returns(address[] memory);
function setPath(
bytes32 dex,
address inputToken,
address outputToken,
address[] calldata path
) external;
}
// File contracts/base/StrategyBaseULClaimable.sol
//SPDX-License-Identifier: Unlicense
pragma solidity 0.5.16;
contract StrategyBaseULClaimable is IStrategy, RewardTokenProfitNotifier {
using SafeMath for uint256;
using SafeERC20 for IERC20;
event ProfitsNotCollected(address);
event Liquidating(address, uint256);
address public underlying;
address public vault;
mapping (address => bool) public unsalvagableTokens;
address public universalLiquidatorRegistry;
address public rewardTokenForLiquidation;
bool public allowedRewardClaimable = false;
address public multiSig = 0xF49440C1F012d041802b25A73e5B0B9166a75c02;
modifier restricted() {
require(msg.sender == vault || msg.sender == address(controller()) || msg.sender == address(governance()),
"The sender has to be the controller or vault or governance");
_;
}
modifier onlyMultiSigOrGovernance() {
require(msg.sender == multiSig || msg.sender == governance(), "The sender has to be multiSig or governance");
_;
}
constructor(
address _storage,
address _underlying,
address _vault,
address _rewardTokenForLiquidation,
address _rewardTokenForProfitSharing,
address _universalLiquidatorRegistry
) RewardTokenProfitNotifier(_storage, _rewardTokenForProfitSharing) public {
rewardTokenForLiquidation = _rewardTokenForLiquidation;
underlying = _underlying;
vault = _vault;
unsalvagableTokens[_rewardTokenForLiquidation] = true;
unsalvagableTokens[_underlying] = true;
universalLiquidatorRegistry = _universalLiquidatorRegistry;
require(underlying != _rewardTokenForLiquidation, "reward token cannot be the same as underlying for StrategyBaseULClaimable");
}
function universalLiquidator() public view returns(address) {
return ILiquidatorRegistry(universalLiquidatorRegistry).universalLiquidator();
}
function setMultiSig(address _address) public onlyGovernance {
multiSig = _address;
}
// reward claiming by multiSig for some strategies
function claimReward() public onlyMultiSigOrGovernance {
require(allowedRewardClaimable, "reward claimable is not allowed");
_getReward();
uint256 rewardBalance = IERC20(rewardTokenForLiquidation).balanceOf(address(this));
IERC20(rewardTokenForLiquidation).safeTransfer(msg.sender, rewardBalance);
}
function setRewardClaimable(bool flag) public onlyGovernance {
allowedRewardClaimable = flag;
}
function _getReward() internal {
revert("Should be implemented in the derived contract");
}
}
// File contracts/base/interface/IVault.sol
pragma solidity 0.5.16;
interface IVault {
function initializeVault(
address _storage,
address _underlying,
uint256 _toInvestNumerator,
uint256 _toInvestDenominator
) external ;
function balanceOf(address) external view returns (uint256);
function underlyingBalanceInVault() external view returns (uint256);
function underlyingBalanceWithInvestment() external view returns (uint256);
// function store() external view returns (address);
function governance() external view returns (address);
function controller() external view returns (address);
function underlying() external view returns (address);
function strategy() external view returns (address);
function setStrategy(address _strategy) external;
function announceStrategyUpdate(address _strategy) external;
function setVaultFractionToInvest(uint256 numerator, uint256 denominator) external;
function deposit(uint256 amountWei) external;
function depositFor(uint256 amountWei, address holder) external;
function withdrawAll() external;
function withdraw(uint256 numberOfShares) external;
function getPricePerFullShare() external view returns (uint256);
function underlyingBalanceWithInvestmentForHolder(address holder) view external returns (uint256);
// hard work should be callable only by the controller (by the hard worker) or by governance
function doHardWork() external;
}
// File contracts/base/interface/IRewardDistributionSwitcher.sol
pragma solidity 0.5.16;
contract IRewardDistributionSwitcher {
function switchingAllowed(address) external returns(bool);
function returnOwnership(address poolAddr) external;
function enableSwitchers(address[] calldata switchers) external;
function setSwithcer(address switcher, bool allowed) external;
function setPoolRewardDistribution(address poolAddr, address newRewardDistributor) external;
}
// File contracts/base/interface/INoMintRewardPool.sol
pragma solidity 0.5.16;
interface INoMintRewardPool {
function withdraw(uint) external;
function getReward() external;
function stake(uint) external;
function balanceOf(address) external view returns (uint256);
function earned(address account) external view returns (uint256);
function exit() external;
function rewardDistribution() external view returns (address);
function lpToken() external view returns(address);
function rewardToken() external view returns(address);
// only owner
function setRewardDistribution(address _rewardDistributor) external;
function transferOwnership(address _owner) external;
function notifyRewardAmount(uint256 _reward) external;
}
// File contracts/base/snx-base/SNXReward2FarmStrategyUL.sol
pragma solidity 0.5.16;
/*
* This is a general strategy for yields that are based on the synthetix reward contract
* for example, yam, spaghetti, ham, shrimp.
*
* One strategy is deployed for one underlying asset, but the design of the contract
* should allow it to switch between different reward contracts.
*
* It is important to note that not all SNX reward contracts that are accessible via the same interface are
* suitable for this Strategy. One concrete example is CREAM.finance, as it implements a "Lock" feature and
* would not allow the user to withdraw within some timeframe after the user have deposited.
* This would be problematic to user as our "invest" function in the vault could be invoked by anyone anytime
* and thus locking/reverting on subsequent withdrawals. Another variation is the YFI Governance: it can
* activate a vote lock to stop withdrawal.
*
* Ref:
* 1. CREAM https://etherscan.io/address/0xc29e89845fa794aa0a0b8823de23b760c3d766f5#code
* 2. YAM https://etherscan.io/address/0x8538E5910c6F80419CD3170c26073Ff238048c9E#code
* 3. SHRIMP https://etherscan.io/address/0x9f83883FD3cadB7d2A83a1De51F9Bf483438122e#code
* 4. BASED https://etherscan.io/address/0x5BB622ba7b2F09BF23F1a9b509cd210A818c53d7#code
* 5. YFII https://etherscan.io/address/0xb81D3cB2708530ea990a287142b82D058725C092#code
* 6. YFIGovernance https://etherscan.io/address/0xBa37B002AbaFDd8E89a1995dA52740bbC013D992#code
*
*
*
* Respecting the current system design of choosing the best strategy under the vault, and also rewarding/funding
* the public key that invokes the switch of strategies, this smart contract should be deployed twice and linked
* to the same vault. When the governance want to rotate the crop, they would set the reward source on the strategy
* that is not active, then set that apy higher and this one lower.
*
* Consequently, in the smart contract we restrict that we can only set a new reward source when it is not active.
*
*/
contract SNXReward2FarmStrategyUL is StrategyBaseULClaimable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address public farm;
address public distributionPool;
address public distributionSwitcher;
address public rewardToken;
bool public pausedInvesting = false; // When this flag is true, the strategy will not be able to invest. But users should be able to withdraw.
SNXRewardInterface public rewardPool;
// a flag for disabling selling for simplified emergency exit
bool public sell = true;
uint256 public sellFloor = 1;
// Instead of trying to pass in the detailed liquidation path and different dexes to the liquidator,
// we just pass in the input output of the liquidation path:
// [ MIC, WETH, FARM ] , [SUSHI, UNI]
//
// This means that:
// the first dex is sushi, the input is MIC and output is WETH.
// the second dex is uni, the input is WETH and the output is FARM.
// the universal liquidator itself would record the best path to liquidate from MIC to WETH on Sushiswap
// provides the path for liquidating a token
address [] public liquidationPath;
// specifies which DEX is the token liquidated on
bytes32 [] public liquidationDexes;
event ProfitsNotCollected();
// This is only used in `investAllUnderlying()`
// The user can still freely withdraw from the strategy
modifier onlyNotPausedInvesting() {
require(!pausedInvesting, "Action blocked as the strategy is in emergency state");
_;
}
modifier onlyMultiSigOrGovernance() {
require(msg.sender == multiSig || msg.sender == governance(), "The sender has to be multiSig or governance");
_;
}
constructor(
address _storage,
address _underlying,
address _vault,
address _rewardPool,
address _rewardToken,
address _universalLiquidatorRegistry,
address _farm,
address _distributionPool
)
StrategyBaseULClaimable(_storage, _underlying, _vault, _rewardToken, _farm, _universalLiquidatorRegistry)
public {
require(_rewardToken != _underlying, "reward token shouldn't be the same as underlying");
require(_vault == INoMintRewardPool(_distributionPool).lpToken(), "distribution pool's lp must be the vault");
require(
(_farm == INoMintRewardPool(_distributionPool).rewardToken())
|| (_farm == IVault(INoMintRewardPool(_distributionPool).rewardToken()).underlying()),
"distribution pool's reward must be FARM or iFARM");
farm = _farm;
distributionPool = _distributionPool;
rewardToken = _rewardToken;
rewardPool = SNXRewardInterface(_rewardPool);
}
function depositArbCheck() public view returns(bool) {
return true;
}
// If there are multiple reward tokens, they should all be liquidated to
// rewardToken.
function _getReward() internal {
if (address(rewardPool) != address(0)) {
rewardPool.getReward();
}
}
/*
* In case there are some issues discovered about the pool or underlying asset
* Governance can exit the pool properly
* The function is only used for emergency to exit the pool
*/
function emergencyExit() public onlyGovernance {
rewardPool.exit();
pausedInvesting = true;
}
/*
* Resumes the ability to invest into the underlying reward pools
*/
function continueInvesting() public onlyGovernance {
pausedInvesting = false;
}
function setLiquidationPaths(address [] memory _liquidationPath, bytes32[] memory _dexes) public onlyGovernance {
liquidationPath = _liquidationPath;
liquidationDexes = _dexes;
}
function _liquidateReward() internal {
uint256 rewardBalance = IERC20(rewardToken).balanceOf(address(this));
if (!sell || rewardBalance < sellFloor) {
// Profits can be disabled for possible simplified and rapid exit
emit ProfitsNotCollected();
return;
}
// sell reward token to FARM
// we can accept 1 as minimum because this is called only by a trusted role
address uliquidator = universalLiquidator();
IERC20(rewardToken).safeApprove(uliquidator, 0);
IERC20(rewardToken).safeApprove(uliquidator, rewardBalance);
ILiquidator(uliquidator).swapTokenOnMultipleDEXes(
rewardBalance,
1,
address(this), // target
liquidationDexes,
liquidationPath
);
uint256 farmAmount = IERC20(farm).balanceOf(address(this));
// Share profit + buyback
notifyProfitAndBuybackInRewardToken(farmAmount, distributionPool, 10000);
}
/*
* Stakes everything the strategy holds into the reward pool
*/
function investAllUnderlying() internal onlyNotPausedInvesting {
// this check is needed, because most of the SNX reward pools will revert if
// you try to stake(0).
if(IERC20(underlying).balanceOf(address(this)) > 0) {
IERC20(underlying).approve(address(rewardPool), IERC20(underlying).balanceOf(address(this)));
rewardPool.stake(IERC20(underlying).balanceOf(address(this)));
}
}
/*
* Withdraws all the asset to the vault
*/
function withdrawAllToVault() public restricted {
if (address(rewardPool) != address(0)) {
if (rewardPool.balanceOf(address(this)) > 0) {
rewardPool.exit();
}
}
_liquidateReward();
if (IERC20(underlying).balanceOf(address(this)) > 0) {
IERC20(underlying).safeTransfer(vault, IERC20(underlying).balanceOf(address(this)));
}
}
/*
* Withdraws all the asset to the vault
*/
function withdrawToVault(uint256 amount) public restricted {
// Typically there wouldn't be any amount here
// however, it is possible because of the emergencyExit
if(amount > IERC20(underlying).balanceOf(address(this))){
// While we have the check above, we still using SafeMath below
// for the peace of mind (in case something gets changed in between)
uint256 needToWithdraw = amount.sub(IERC20(underlying).balanceOf(address(this)));
rewardPool.withdraw(Math.min(rewardPool.balanceOf(address(this)), needToWithdraw));
}
IERC20(underlying).safeTransfer(vault, amount);
}
/*
* Note that we currently do not have a mechanism here to include the
* amount of reward that is accrued.
*/
function investedUnderlyingBalance() external view returns (uint256) {
if (address(rewardPool) == address(0)) {
return IERC20(underlying).balanceOf(address(this));
}
// Adding the amount locked in the reward pool and the amount that is somehow in this contract
// both are in the units of "underlying"
// The second part is needed because there is the emergency exit mechanism
// which would break the assumption that all the funds are always inside of the reward pool
return rewardPool.balanceOf(address(this)).add(IERC20(underlying).balanceOf(address(this)));
}
/*
* Governance or Controller can claim coins that are somehow transferred into the contract
* Note that they cannot come in take away coins that are used and defined in the strategy itself
* Those are protected by the "unsalvagableTokens". To check, see where those are being flagged.
*/
function salvage(address recipient, address token, uint256 amount) external onlyControllerOrGovernance {
// To make sure that governance cannot come in and take away the coins
require(!unsalvagableTokens[token], "token is defined as not salvagable");
IERC20(token).safeTransfer(recipient, amount);
}
/*
* Get the reward, sell it in exchange for underlying, invest what you got.
* It's not much, but it's honest work.
*
* Note that although `onlyNotPausedInvesting` is not added here,
* calling `investAllUnderlying()` affectively blocks the usage of `doHardWork`
* when the investing is being paused by governance.
*/
function doHardWork() external onlyNotPausedInvesting restricted {
rewardPool.getReward();
_liquidateReward();
investAllUnderlying();
}
/**
* Can completely disable claiming UNI rewards and selling. Good for emergency withdraw in the
* simplest possible way.
*/
function setSell(bool s) public onlyGovernance {
sell = s;
}
/**
* Sets the minimum amount of CRV needed to trigger a sale.
*/
function setSellFloor(uint256 floor) public onlyGovernance {
sellFloor = floor;
}
}
// File contracts/strategies/mirror-finance/MirrorMainnet_mNFLX_UST.sol
pragma solidity 0.5.16;
contract MirrorMainnet_mNFLX_UST is SNXReward2FarmStrategyUL {
address public ust = address(0xa47c8bf37f92aBed4A126BDA807A7b7498661acD);
address public mnflx_ust = address(0xC99A74145682C4b4A6e9fa55d559eb49A6884F75);
address public mnflx = address(0xC8d674114bac90148d11D3C1d33C61835a0F9DCD);
address public mir = address(0x09a3EcAFa817268f77BE1283176B946C4ff2E608);
address public weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
address public mNFLXUSTRewardPool = address(0x29cF719d134c1C18daB61C2F4c0529C4895eCF44);
address public constant universalLiquidatorRegistry = address(0x7882172921E99d590E097cD600554339fBDBc480);
address public constant farm = address(0xa0246c9032bC3A600820415aE600c6388619A14D);
constructor(
address _storage,
address _vault,
address _distributionPool
)
SNXReward2FarmStrategyUL(_storage, mnflx_ust, _vault, mNFLXUSTRewardPool, mir, universalLiquidatorRegistry, farm, _distributionPool)
public {
require(IVault(_vault).underlying() == mnflx_ust, "Underlying mismatch");
liquidationPath = [mir, farm];
liquidationDexes.push(bytes32(uint256(keccak256("uni"))));
allowedRewardClaimable = true;
}
} | should only be called by controller | interface IStrategy {
function unsalvagableTokens(address tokens) external view returns (bool);
function governance() external view returns (address);
function controller() external view returns (address);
function underlying() external view returns (address);
function vault() external view returns (address);
function withdrawAllToVault() external;
function withdrawToVault(uint256 amount) external;
function salvage(address recipient, address token, uint256 amount) external;
function doHardWork() external;
function depositArbCheck() external view returns(bool);
}
| 2,344,108 |
/**
*Submitted for verification at Etherscan.io on 2022-01-13
*/
// Sources flattened with hardhat v2.8.2 https://hardhat.org
// File deps/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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
);
}
// File deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.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 SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File deps/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol
pragma solidity ^0.6.2;
/**
* @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 in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage
) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) =
target.call{value: weiValue}(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File deps/@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.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 SafeERC20Upgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
function safeTransfer(
IERC20Upgradeable token,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transfer.selector, to, value)
);
}
function safeTransferFrom(
IERC20Upgradeable token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transferFrom.selector, from, to, value)
);
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, value)
);
}
function safeIncreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
uint256 newAllowance =
token.allowance(address(this), spender).add(value);
_callOptionalReturn(
token,
abi.encodeWithSelector(
token.approve.selector,
spender,
newAllowance
)
);
}
function safeDecreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
uint256 newAllowance =
token.allowance(address(this), spender).sub(
value,
"SafeERC20: decreased allowance below zero"
);
_callOptionalReturn(
token,
abi.encodeWithSelector(
token.approve.selector,
spender,
newAllowance
)
);
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data)
private
{
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata =
address(token).functionCall(
data,
"SafeERC20: low-level call failed"
);
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(
abi.decode(returndata, (bool)),
"SafeERC20: ERC20 operation did not succeed"
);
}
}
}
// File deps/@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol
pragma solidity ^0.6.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.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value)
private
view
returns (bool)
{
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index)
private
view
returns (bytes32)
{
require(
set._values.length > index,
"EnumerableSet: index out of bounds"
);
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value)
internal
returns (bool)
{
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index)
internal
view
returns (address)
{
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index)
internal
view
returns (uint256)
{
return uint256(_at(set._inner, index));
}
}
// File interfaces/uniswap/IUniswapRouterV2.sol
pragma solidity >=0.5.0 <0.8.0;
interface IUniswapRouterV2 {
function factory() external view 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 getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}
// File interfaces/badger/IBadgerGeyser.sol
pragma solidity >=0.5.0 <0.8.0;
interface IBadgerGeyser {
function stake(address) external returns (uint256);
function signalTokenLock(
address token,
uint256 amount,
uint256 durationSec,
uint256 startTime
) external;
function modifyTokenLock(
address token,
uint256 index,
uint256 amount,
uint256 durationSec,
uint256 startTime
) external;
}
// File interfaces/uniswap/IUniswapPair.sol
pragma solidity ^0.6.0;
interface IUniswapPair {
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves()
external
view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
}
// File interfaces/badger/IController.sol
pragma solidity >=0.5.0 <0.8.0;
interface IController {
function withdraw(address, uint256) external;
function strategies(address) external view returns (address);
function balanceOf(address) external view returns (uint256);
function earn(address, uint256) external;
function want(address) external view returns (address);
function rewards() external view returns (address);
function vaults(address) external view returns (address);
}
// File interfaces/badger/ISettV4.sol
pragma solidity >=0.5.0 <0.8.0;
interface ISettV4 {
function token() external view returns (address);
function decimals() external view returns (uint256);
function keeper() external view returns (address);
function governance() external view returns (address);
function deposit(uint256) external;
function setController(address) external;
function depositFor(address, uint256) external;
function depositAll() external;
function withdraw(uint256) external;
function withdrawAll() external;
function earn() external;
function balanceOf(address account) external view returns (uint256);
function totalSupply() external view returns (uint256);
function balance() external view returns (uint256);
function claimInsurance() external; // NOTE: Only yDelegatedVault implements this
function getPricePerFullShare() external view returns (uint256);
}
// File interfaces/convex/IBooster.sol
pragma solidity >=0.6.0;
pragma experimental ABIEncoderV2;
interface IBooster {
struct PoolInfo {
address lptoken;
address token;
address gauge;
address crvRewards;
address stash;
bool shutdown;
}
function poolInfo(uint256 _pid) external view returns (PoolInfo memory);
function deposit(
uint256 _pid,
uint256 _amount,
bool _stake
) external returns (bool);
function earmarkRewards(uint256 _pid) external returns (bool);
function depositAll(uint256 _pid, bool _stake) external returns (bool);
function withdraw(uint256 _pid, uint256 _amount) external returns (bool);
function withdrawAll(uint256 _pid) external returns (bool);
}
// File interfaces/convex/CrvDepositor.sol
pragma solidity >=0.6.0;
interface CrvDepositor {
//deposit crv for cvxCrv
//can locking immediately or defer locking to someone else by paying a fee.
//while users can choose to lock or defer, this is mostly in place so that
//the cvx reward contract isnt costly to claim rewards
function deposit(uint256 _amount, bool _lock) external;
}
// File interfaces/convex/IBaseRewardsPool.sol
pragma solidity ^0.6.0;
interface IBaseRewardsPool {
//balance
function balanceOf(address _account) external view returns (uint256);
//withdraw to a convex tokenized deposit
function withdraw(uint256 _amount, bool _claim) external returns (bool);
//withdraw directly to curve LP token
function withdrawAndUnwrap(uint256 _amount, bool _claim)
external
returns (bool);
//claim rewards
function getReward() external returns (bool);
//stake a convex tokenized deposit
function stake(uint256 _amount) external returns (bool);
//stake a convex tokenized deposit for another address(transfering ownership)
function stakeFor(address _account, uint256 _amount)
external
returns (bool);
function getReward(address _account, bool _claimExtras)
external
returns (bool);
function rewards(address _account) external view returns (uint256);
function earned(address _account) external view returns (uint256);
function stakingToken() external view returns (address);
function periodFinish() external view returns (uint256);
}
// File interfaces/convex/ICvxRewardsPool.sol
pragma solidity ^0.6.0;
interface ICvxRewardsPool {
//balance
function balanceOf(address _account) external view returns (uint256);
//withdraw to a convex tokenized deposit
function withdraw(uint256 _amount, bool _claim) external;
//withdraw directly to curve LP token
function withdrawAndUnwrap(uint256 _amount, bool _claim)
external
returns (bool);
//claim rewards
function getReward(bool _stake) external;
//stake a convex tokenized deposit
function stake(uint256 _amount) external;
//stake a convex tokenized deposit for another address(transfering ownership)
function stakeFor(address _account, uint256 _amount)
external
returns (bool);
function rewards(address _account) external view returns (uint256);
function earned(address _account) external view returns (uint256);
}
// File deps/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol
pragma solidity >=0.4.24 <0.7.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;
}
}
// File deps/@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.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 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;
}
// File deps/@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract 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 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;
}
// File interfaces/uniswap/IUniswapV2Factory.sol
pragma solidity >=0.5.0 <0.8.0;
interface IUniswapV2Factory {
event PairCreated(
address indexed token0,
address indexed token1,
address pair,
uint256
);
function getPair(address tokenA, address tokenB)
external
view
returns (address pair);
function allPairs(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function createPair(address tokenA, address tokenB)
external
returns (address pair);
}
// File interfaces/badger/IStrategy.sol
pragma solidity >=0.5.0 <0.8.0;
interface IStrategy {
function want() external view returns (address);
function deposit() external;
// NOTE: must exclude any tokens used in the yield
// Controller role - withdraw should return to Controller
function withdrawOther(address) external returns (uint256 balance);
// Controller | Vault role - withdraw should always return to Vault
function withdraw(uint256) external;
// Controller | Vault role - withdraw should always return to Vault
function withdrawAll() external returns (uint256);
function balanceOf() external view returns (uint256);
function getName() external pure returns (string memory);
function setStrategist(address _strategist) external;
function setWithdrawalFee(uint256 _withdrawalFee) external;
function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist)
external;
function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance)
external;
function setGovernance(address _governance) external;
function setController(address _controller) external;
function tend() external;
function harvest() external;
}
// File deps/SettAccessControl.sol
pragma solidity ^0.6.11;
/*
Common base for permissioned roles throughout Sett ecosystem
*/
contract SettAccessControl is Initializable {
address public governance;
address public strategist;
address public keeper;
// ===== MODIFIERS =====
function _onlyGovernance() internal view {
require(msg.sender == governance, "onlyGovernance");
}
function _onlyGovernanceOrStrategist() internal view {
require(
msg.sender == strategist || msg.sender == governance,
"onlyGovernanceOrStrategist"
);
}
function _onlyAuthorizedActors() internal view {
require(
msg.sender == keeper || msg.sender == governance,
"onlyAuthorizedActors"
);
}
// ===== PERMISSIONED ACTIONS =====
/// @notice Change strategist address
/// @notice Can only be changed by governance itself
function setStrategist(address _strategist) external {
_onlyGovernance();
strategist = _strategist;
}
/// @notice Change keeper address
/// @notice Can only be changed by governance itself
function setKeeper(address _keeper) external {
_onlyGovernance();
keeper = _keeper;
}
/// @notice Change governance address
/// @notice Can only be changed by governance itself
function setGovernance(address _governance) public {
_onlyGovernance();
governance = _governance;
}
uint256[50] private __gap;
}
// File deps/@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol
pragma solidity ^0.6.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
/**
* @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);
}
}
// File deps/BaseStrategy.sol
pragma solidity ^0.6.11;
/*
===== Badger Base Strategy =====
Common base class for all Sett strategies
Changelog
V1.1
- Verify amount unrolled from strategy positions on withdraw() is within a threshold relative to the requested amount as a sanity check
- Add version number which is displayed with baseStrategyVersion(). If a strategy does not implement this function, it can be assumed to be 1.0
V1.2
- Remove idle want handling from base withdraw() function. This should be handled as the strategy sees fit in _withdrawSome()
*/
abstract contract BaseStrategy is PausableUpgradeable, SettAccessControl {
using SafeERC20Upgradeable for IERC20Upgradeable;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
event Withdraw(uint256 amount);
event WithdrawAll(uint256 balance);
event WithdrawOther(address token, uint256 amount);
event SetStrategist(address strategist);
event SetGovernance(address governance);
event SetController(address controller);
event SetWithdrawalFee(uint256 withdrawalFee);
event SetPerformanceFeeStrategist(uint256 performanceFeeStrategist);
event SetPerformanceFeeGovernance(uint256 performanceFeeGovernance);
event Harvest(uint256 harvested, uint256 indexed blockNumber);
event Tend(uint256 tended);
address public want; // Want: Curve.fi renBTC/wBTC (crvRenWBTC) LP token
uint256 public performanceFeeGovernance;
uint256 public performanceFeeStrategist;
uint256 public withdrawalFee;
uint256 public constant MAX_FEE = 10000;
address public controller;
address public guardian;
uint256 public withdrawalMaxDeviationThreshold;
function __BaseStrategy_init(
address _governance,
address _strategist,
address _controller,
address _keeper,
address _guardian
) public initializer whenNotPaused {
__Pausable_init();
governance = _governance;
strategist = _strategist;
keeper = _keeper;
controller = _controller;
guardian = _guardian;
withdrawalMaxDeviationThreshold = 50;
}
// ===== Modifiers =====
function _onlyController() internal view {
require(msg.sender == controller, "onlyController");
}
function _onlyAuthorizedActorsOrController() internal view {
require(
msg.sender == keeper ||
msg.sender == governance ||
msg.sender == controller,
"onlyAuthorizedActorsOrController"
);
}
function _onlyAuthorizedPausers() internal view {
require(
msg.sender == guardian || msg.sender == governance,
"onlyPausers"
);
}
/// ===== View Functions =====
function baseStrategyVersion() public view returns (string memory) {
return "1.2";
}
/// @notice Get the balance of want held idle in the Strategy
function balanceOfWant() public view returns (uint256) {
return IERC20Upgradeable(want).balanceOf(address(this));
}
/// @notice Get the total balance of want realized in the strategy, whether idle or active in Strategy positions.
function balanceOf() public view virtual returns (uint256) {
return balanceOfWant().add(balanceOfPool());
}
function isTendable() public view virtual returns (bool) {
return false;
}
function isProtectedToken(address token) public view returns (bool) {
address[] memory protectedTokens = getProtectedTokens();
for (uint256 i = 0; i < protectedTokens.length; i++) {
if (token == protectedTokens[i]) {
return true;
}
}
return false;
}
/// ===== Permissioned Actions: Governance =====
function setGuardian(address _guardian) external {
_onlyGovernance();
guardian = _guardian;
}
function setWithdrawalFee(uint256 _withdrawalFee) external {
_onlyGovernance();
require(_withdrawalFee <= MAX_FEE, "excessive-fee");
withdrawalFee = _withdrawalFee;
}
function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist)
external
{
_onlyGovernance();
require(_performanceFeeStrategist <= MAX_FEE, "excessive-fee");
performanceFeeStrategist = _performanceFeeStrategist;
}
function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance)
external
{
_onlyGovernance();
require(_performanceFeeGovernance <= MAX_FEE, "excessive-fee");
performanceFeeGovernance = _performanceFeeGovernance;
}
function setController(address _controller) external {
_onlyGovernance();
controller = _controller;
}
function setWithdrawalMaxDeviationThreshold(uint256 _threshold) external {
_onlyGovernance();
require(_threshold <= MAX_FEE, "excessive-threshold");
withdrawalMaxDeviationThreshold = _threshold;
}
function deposit() public virtual whenNotPaused {
_onlyAuthorizedActorsOrController();
uint256 _want = IERC20Upgradeable(want).balanceOf(address(this));
if (_want > 0) {
_deposit(_want);
}
_postDeposit();
}
// ===== Permissioned Actions: Controller =====
/// @notice Controller-only function to Withdraw partial funds, normally used with a vault withdrawal
function withdrawAll()
external
virtual
whenNotPaused
returns (uint256 balance)
{
_onlyController();
_withdrawAll();
_transferToVault(IERC20Upgradeable(want).balanceOf(address(this)));
}
/// @notice Withdraw partial funds from the strategy, unrolling from strategy positions as necessary
/// @notice Processes withdrawal fee if present
/// @dev If it fails to recover sufficient funds (defined by withdrawalMaxDeviationThreshold), the withdrawal should fail so that this unexpected behavior can be investigated
function withdraw(uint256 _amount) external virtual whenNotPaused {
_onlyController();
// Withdraw from strategy positions, typically taking from any idle want first.
_withdrawSome(_amount);
uint256 _postWithdraw =
IERC20Upgradeable(want).balanceOf(address(this));
// Sanity check: Ensure we were able to retrieve sufficent want from strategy positions
// If we end up with less than the amount requested, make sure it does not deviate beyond a maximum threshold
if (_postWithdraw < _amount) {
uint256 diff = _diff(_amount, _postWithdraw);
// Require that difference between expected and actual values is less than the deviation threshold percentage
require(
diff <=
_amount.mul(withdrawalMaxDeviationThreshold).div(MAX_FEE),
"withdraw-exceed-max-deviation-threshold"
);
}
// Return the amount actually withdrawn if less than amount requested
uint256 _toWithdraw = MathUpgradeable.min(_postWithdraw, _amount);
// Process withdrawal fee
uint256 _fee = _processWithdrawalFee(_toWithdraw);
// Transfer remaining to Vault to handle withdrawal
_transferToVault(_toWithdraw.sub(_fee));
}
// NOTE: must exclude any tokens used in the yield
// Controller role - withdraw should return to Controller
function withdrawOther(address _asset)
external
virtual
whenNotPaused
returns (uint256 balance)
{
_onlyController();
_onlyNotProtectedTokens(_asset);
balance = IERC20Upgradeable(_asset).balanceOf(address(this));
IERC20Upgradeable(_asset).safeTransfer(controller, balance);
}
/// ===== Permissioned Actions: Authoized Contract Pausers =====
function pause() external {
_onlyAuthorizedPausers();
_pause();
}
function unpause() external {
_onlyGovernance();
_unpause();
}
/// ===== Internal Helper Functions =====
/// @notice If withdrawal fee is active, take the appropriate amount from the given value and transfer to rewards recipient
/// @return The withdrawal fee that was taken
function _processWithdrawalFee(uint256 _amount) internal returns (uint256) {
if (withdrawalFee == 0) {
return 0;
}
uint256 fee = _amount.mul(withdrawalFee).div(MAX_FEE);
IERC20Upgradeable(want).safeTransfer(
IController(controller).rewards(),
fee
);
return fee;
}
/// @dev Helper function to process an arbitrary fee
/// @dev If the fee is active, transfers a given portion in basis points of the specified value to the recipient
/// @return The fee that was taken
function _processFee(
address token,
uint256 amount,
uint256 feeBps,
address recipient
) internal returns (uint256) {
if (feeBps == 0) {
return 0;
}
uint256 fee = amount.mul(feeBps).div(MAX_FEE);
IERC20Upgradeable(token).safeTransfer(recipient, fee);
return fee;
}
function _transferToVault(uint256 _amount) internal {
address _vault = IController(controller).vaults(address(want));
require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20Upgradeable(want).safeTransfer(_vault, _amount);
}
/// @notice Utility function to diff two numbers, expects higher value in first position
function _diff(uint256 a, uint256 b) internal pure returns (uint256) {
require(a >= b, "diff/expected-higher-number-in-first-position");
return a.sub(b);
}
// ===== Abstract Functions: To be implemented by specific Strategies =====
/// @dev Internal deposit logic to be implemented by Stratgies
function _deposit(uint256 _want) internal virtual;
function _postDeposit() internal virtual {
//no-op by default
}
/// @notice Specify tokens used in yield process, should not be available to withdraw via withdrawOther()
function _onlyNotProtectedTokens(address _asset) internal virtual;
function getProtectedTokens()
public
view
virtual
returns (address[] memory)
{
return new address[](0);
}
/// @dev Internal logic for strategy migration. Should exit positions as efficiently as possible
function _withdrawAll() internal virtual;
/// @dev Internal logic for partial withdrawals. Should exit positions as efficiently as possible.
/// @dev The withdraw() function shell automatically uses idle want in the strategy before attempting to withdraw more using this
function _withdrawSome(uint256 _amount) internal virtual returns (uint256);
/// @dev Realize returns from positions
/// @dev Returns can be reinvested into positions, or distributed in another fashion
/// @dev Performance fees should also be implemented in this function
/// @dev Override function stub is removed as each strategy can have it's own return signature for STATICCALL
// function harvest() external virtual;
/// @dev User-friendly name for this strategy for purposes of convenient reading
function getName() external pure virtual returns (string memory);
/// @dev Balance of want currently held in strategy positions
function balanceOfPool() public view virtual returns (uint256);
uint256[49] private __gap;
}
// File deps/BaseStrategySwapper.sol
pragma solidity ^0.6.11;
/*
Expands swapping functionality over base strategy
- ETH in and ETH out Variants
- Sushiswap support in addition to Uniswap
*/
abstract contract BaseStrategyMultiSwapper is BaseStrategy {
using SafeERC20Upgradeable for IERC20Upgradeable;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
address public constant uniswap =
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // Uniswap Dex
address public constant sushiswap =
0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; // Sushiswap router
/// @notice Swap specified balance of given token on Uniswap with given path
function _swap_uniswap(
address startToken,
uint256 balance,
address[] memory path
) internal {
_safeApproveHelper(startToken, uniswap, balance);
IUniswapRouterV2(uniswap).swapExactTokensForTokens(
balance,
0,
path,
address(this),
now
);
}
/// @dev Reset approval and approve exact amount
function _safeApproveHelper(
address token,
address recipient,
uint256 amount
) internal {
IERC20Upgradeable(token).safeApprove(recipient, 0);
IERC20Upgradeable(token).safeApprove(recipient, amount);
}
/// @notice Swap specified balance of given token on Uniswap with given path
function _swap_sushiswap(
address startToken,
uint256 balance,
address[] memory path
) internal {
_safeApproveHelper(startToken, sushiswap, balance);
IUniswapRouterV2(sushiswap).swapExactTokensForTokens(
balance,
0,
path,
address(this),
now
);
}
function _swapEthIn_uniswap(uint256 balance, address[] memory path)
internal
{
IUniswapRouterV2(uniswap).swapExactETHForTokens{value: balance}(
0,
path,
address(this),
now
);
}
function _swapEthIn_sushiswap(uint256 balance, address[] memory path)
internal
{
IUniswapRouterV2(sushiswap).swapExactETHForTokens{value: balance}(
0,
path,
address(this),
now
);
}
function _swapEthOut_uniswap(
address startToken,
uint256 balance,
address[] memory path
) internal {
_safeApproveHelper(startToken, uniswap, balance);
IUniswapRouterV2(uniswap).swapExactTokensForETH(
balance,
0,
path,
address(this),
now
);
}
function _swapEthOut_sushiswap(
address startToken,
uint256 balance,
address[] memory path
) internal {
_safeApproveHelper(startToken, sushiswap, balance);
IUniswapRouterV2(sushiswap).swapExactTokensForETH(
balance,
0,
path,
address(this),
now
);
}
function _get_uni_pair(address token0, address token1)
internal
view
returns (address)
{
address factory = IUniswapRouterV2(uniswap).factory();
return IUniswapV2Factory(factory).getPair(token0, token1);
}
function _get_sushi_pair(address token0, address token1)
internal
view
returns (address)
{
address factory = IUniswapRouterV2(sushiswap).factory();
return IUniswapV2Factory(factory).getPair(token0, token1);
}
/// @notice Swap specified balance of given token on Uniswap with given path
function _swap(
address startToken,
uint256 balance,
address[] memory path
) internal {
_safeApproveHelper(startToken, uniswap, balance);
IUniswapRouterV2(uniswap).swapExactTokensForTokens(
balance,
0,
path,
address(this),
now
);
}
function _swapEthIn(uint256 balance, address[] memory path) internal {
IUniswapRouterV2(uniswap).swapExactETHForTokens{value: balance}(
0,
path,
address(this),
now
);
}
function _swapEthOut(
address startToken,
uint256 balance,
address[] memory path
) internal {
_safeApproveHelper(startToken, uniswap, balance);
IUniswapRouterV2(uniswap).swapExactTokensForETH(
balance,
0,
path,
address(this),
now
);
}
/// @notice Add liquidity to uniswap for specified token pair, utilizing the maximum balance possible
function _add_max_liquidity_uniswap(address token0, address token1)
internal
virtual
{
uint256 _token0Balance =
IERC20Upgradeable(token0).balanceOf(address(this));
uint256 _token1Balance =
IERC20Upgradeable(token1).balanceOf(address(this));
_safeApproveHelper(token0, uniswap, _token0Balance);
_safeApproveHelper(token1, uniswap, _token1Balance);
IUniswapRouterV2(uniswap).addLiquidity(
token0,
token1,
_token0Balance,
_token1Balance,
0,
0,
address(this),
block.timestamp
);
}
/// @notice Add liquidity to uniswap for specified token pair, utilizing the maximum balance possible
function _add_max_liquidity_sushiswap(address token0, address token1)
internal
{
uint256 _token0Balance =
IERC20Upgradeable(token0).balanceOf(address(this));
uint256 _token1Balance =
IERC20Upgradeable(token1).balanceOf(address(this));
_safeApproveHelper(token0, sushiswap, _token0Balance);
_safeApproveHelper(token1, sushiswap, _token1Balance);
IUniswapRouterV2(sushiswap).addLiquidity(
token0,
token1,
_token0Balance,
_token1Balance,
0,
0,
address(this),
block.timestamp
);
}
function _add_max_liquidity_eth_sushiswap(address token0) internal {
uint256 _token0Balance =
IERC20Upgradeable(token0).balanceOf(address(this));
uint256 _ethBalance = address(this).balance;
_safeApproveHelper(token0, sushiswap, _token0Balance);
IUniswapRouterV2(sushiswap).addLiquidityETH{
value: address(this).balance
}(token0, _token0Balance, 0, 0, address(this), block.timestamp);
}
uint256[50] private __gap;
}
// File interfaces/curve/ICurveFi.sol
pragma solidity >=0.5.0 <0.8.0;
interface ICurveFi {
function get_virtual_price() external view returns (uint256 out);
function add_liquidity(
// renbtc/tbtc pool
uint256[2] calldata amounts,
uint256 min_mint_amount
) external;
function add_liquidity(
// sBTC pool
uint256[3] calldata amounts,
uint256 min_mint_amount
) external;
function add_liquidity(
// bUSD pool
uint256[4] calldata amounts,
uint256 min_mint_amount
) external;
function get_dy(
int128 i,
int128 j,
uint256 dx
) external returns (uint256 out);
function get_dy_underlying(
int128 i,
int128 j,
uint256 dx
) external returns (uint256 out);
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external;
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy,
uint256 deadline
) external;
function exchange_underlying(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external;
function exchange_underlying(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy,
uint256 deadline
) external;
function remove_liquidity(
uint256 _amount,
uint256 deadline,
uint256[2] calldata min_amounts
) external;
function remove_liquidity_imbalance(
uint256[2] calldata amounts,
uint256 deadline
) external;
function remove_liquidity_imbalance(
uint256[3] calldata amounts,
uint256 max_burn_amount
) external;
function remove_liquidity(uint256 _amount, uint256[3] calldata amounts)
external;
function remove_liquidity_imbalance(
uint256[4] calldata amounts,
uint256 max_burn_amount
) external;
function remove_liquidity(uint256 _amount, uint256[4] calldata amounts)
external;
function remove_liquidity_one_coin(
uint256 _token_amount,
int128 i,
uint256 _min_amount
) external;
function commit_new_parameters(
int128 amplification,
int128 new_fee,
int128 new_admin_fee
) external;
function apply_new_parameters() external;
function revert_new_parameters() external;
function commit_transfer_ownership(address _owner) external;
function apply_transfer_ownership() external;
function revert_transfer_ownership() external;
function withdraw_admin_fees() external;
function coins(int128 arg0) external returns (address out);
function underlying_coins(int128 arg0) external returns (address out);
function balances(int128 arg0) external returns (uint256 out);
function A() external returns (int128 out);
function fee() external returns (int128 out);
function admin_fee() external returns (int128 out);
function owner() external returns (address out);
function admin_actions_deadline() external returns (uint256 out);
function transfer_ownership_deadline() external returns (uint256 out);
function future_A() external returns (int128 out);
function future_fee() external returns (int128 out);
function future_admin_fee() external returns (int128 out);
function future_owner() external returns (address out);
function calc_withdraw_one_coin(uint256 _token_amount, int128 _i)
external
view
returns (uint256 out);
}
// File interfaces/curve/ICurveExchange.sol
pragma solidity >=0.6.0;
interface ICurveExchange {
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external;
function get_dy(
int128,
int128 j,
uint256 dx
) external view returns (uint256);
function calc_token_amount(uint256[2] calldata amounts, bool deposit)
external
view
returns (uint256 amount);
function add_liquidity(uint256[2] calldata amounts, uint256 min_mint_amount)
external;
function remove_liquidity(uint256 _amount, uint256[2] calldata min_amounts)
external;
function remove_liquidity_imbalance(
uint256[2] calldata amounts,
uint256 max_burn_amount
) external;
function remove_liquidity_one_coin(
uint256 _token_amounts,
int128 i,
uint256 min_amount
) external;
}
interface ICurveRegistryAddressProvider {
function get_address(uint256 id) external returns (address);
}
interface ICurveRegistryExchange {
function get_best_rate(
address from,
address to,
uint256 amount
) external view returns (address, uint256);
function exchange(
address pool,
address from,
address to,
uint256 amount,
uint256 expected,
address receiver
) external payable returns (uint256);
}
// File interfaces/curve/ICurveRegistry.sol
pragma solidity >=0.5.0 <0.8.0;
interface ICurveRegistry {
function find_pool_for_coins(
address _from,
address _to,
uint256 _index
) external returns (address);
function get_coin_indices(
address _pool,
address _from,
address _to
)
external
returns (
int128,
int128,
bool
);
}
// File deps/libraries/BaseSwapper.sol
pragma solidity ^0.6.11;
/*
Expands swapping functionality over base strategy
- ETH in and ETH out Variants
- Sushiswap support in addition to Uniswap
*/
contract BaseSwapper {
using SafeERC20Upgradeable for IERC20Upgradeable;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
/// @dev Reset approval and approve exact amount
function _safeApproveHelper(
address token,
address recipient,
uint256 amount
) internal {
IERC20Upgradeable(token).safeApprove(recipient, 0);
IERC20Upgradeable(token).safeApprove(recipient, amount);
}
}
// File deps/libraries/CurveSwapper.sol
pragma solidity ^0.6.11;
/*
Expands swapping functionality over base strategy
- ETH in and ETH out Variants
- Sushiswap support in addition to Uniswap
*/
contract CurveSwapper is BaseSwapper {
using SafeERC20Upgradeable for IERC20Upgradeable;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
address public constant addressProvider =
0x0000000022D53366457F9d5E68Ec105046FC4383;
uint256 public constant registryId = 0;
uint256 public constant metaPoolFactoryId = 3;
function _exchange(
address _from,
address _to,
uint256 _dx,
uint256 _min_dy,
uint256 _index,
bool _isFactoryPool
) internal {
address poolRegistry =
ICurveRegistryAddressProvider(addressProvider).get_address(
_isFactoryPool ? metaPoolFactoryId : registryId
);
address poolAddress =
ICurveRegistry(poolRegistry).find_pool_for_coins(
_from,
_to,
_index
);
if (poolAddress != address(0)) {
_safeApproveHelper(_from, poolAddress, _dx);
(int128 i, int128 j, ) =
ICurveRegistry(poolRegistry).get_coin_indices(
poolAddress,
_from,
_to
);
ICurveFi(poolAddress).exchange(i, j, _dx, _min_dy);
}
}
function _add_liquidity_single_coin(
address swap,
address pool,
address inputToken,
uint256 inputAmount,
uint256 inputPosition,
uint256 numPoolElements,
uint256 min_mint_amount
) internal {
_safeApproveHelper(inputToken, swap, inputAmount);
if (numPoolElements == 2) {
uint256[2] memory convertedAmounts;
convertedAmounts[inputPosition] = inputAmount;
ICurveFi(swap).add_liquidity(convertedAmounts, min_mint_amount);
} else if (numPoolElements == 3) {
uint256[3] memory convertedAmounts;
convertedAmounts[inputPosition] = inputAmount;
ICurveFi(swap).add_liquidity(convertedAmounts, min_mint_amount);
} else if (numPoolElements == 4) {
uint256[4] memory convertedAmounts;
convertedAmounts[inputPosition] = inputAmount;
ICurveFi(swap).add_liquidity(convertedAmounts, min_mint_amount);
} else {
revert("Bad numPoolElements");
}
}
function _add_liquidity(
address pool,
uint256[2] memory amounts,
uint256 min_mint_amount
) internal {
ICurveFi(pool).add_liquidity(amounts, min_mint_amount);
}
function _add_liquidity(
address pool,
uint256[3] memory amounts,
uint256 min_mint_amount
) internal {
ICurveFi(pool).add_liquidity(amounts, min_mint_amount);
}
function _add_liquidity(
address pool,
uint256[4] memory amounts,
uint256 min_mint_amount
) internal {
ICurveFi(pool).add_liquidity(amounts, min_mint_amount);
}
function _remove_liquidity_one_coin(
address swap,
uint256 _token_amount,
int128 i,
uint256 _min_amount
) internal {
ICurveFi(swap).remove_liquidity_one_coin(_token_amount, i, _min_amount);
}
}
// File deps/@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is
Initializable,
ContextUpgradeable
{
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using AddressUpgradeable for address;
struct RoleData {
EnumerableSetUpgradeable.AddressSet members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(
bytes32 indexed role,
bytes32 indexed previousAdminRole,
bytes32 indexed newAdminRole
);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(
bytes32 indexed role,
address indexed account,
address indexed sender
);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(
bytes32 indexed role,
address indexed account,
address indexed sender
);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index)
public
view
returns (address)
{
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(
hasRole(_roles[role].adminRole, _msgSender()),
"AccessControl: sender must be an admin to grant"
);
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(
hasRole(_roles[role].adminRole, _msgSender()),
"AccessControl: sender must be an admin to revoke"
);
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(
account == _msgSender(),
"AccessControl: can only renounce roles for self"
);
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// File deps/libraries/UniswapSwapper.sol
pragma solidity ^0.6.11;
/*
Expands swapping functionality over base strategy
- ETH in and ETH out Variants
- Sushiswap support in addition to Uniswap
*/
contract UniswapSwapper is BaseSwapper {
using SafeERC20Upgradeable for IERC20Upgradeable;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
address internal constant uniswap =
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // Uniswap router
address internal constant sushiswap =
0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; // Sushiswap router
function _swapExactTokensForTokens(
address router,
address startToken,
uint256 balance,
address[] memory path
) internal {
_safeApproveHelper(startToken, router, balance);
IUniswapRouterV2(router).swapExactTokensForTokens(
balance,
0,
path,
address(this),
now
);
}
function _swapExactETHForTokens(
address router,
uint256 balance,
address[] memory path
) internal {
IUniswapRouterV2(uniswap).swapExactETHForTokens{value: balance}(
0,
path,
address(this),
now
);
}
function _swapExactTokensForETH(
address router,
address startToken,
uint256 balance,
address[] memory path
) internal {
_safeApproveHelper(startToken, router, balance);
IUniswapRouterV2(router).swapExactTokensForETH(
balance,
0,
path,
address(this),
now
);
}
function _getPair(
address router,
address token0,
address token1
) internal view returns (address) {
address factory = IUniswapRouterV2(router).factory();
return IUniswapV2Factory(factory).getPair(token0, token1);
}
/// @notice Add liquidity to uniswap for specified token pair, utilizing the maximum balance possible
function _addMaxLiquidity(
address router,
address token0,
address token1
) internal {
uint256 _token0Balance =
IERC20Upgradeable(token0).balanceOf(address(this));
uint256 _token1Balance =
IERC20Upgradeable(token1).balanceOf(address(this));
_safeApproveHelper(token0, router, _token0Balance);
_safeApproveHelper(token1, router, _token1Balance);
IUniswapRouterV2(router).addLiquidity(
token0,
token1,
_token0Balance,
_token1Balance,
0,
0,
address(this),
block.timestamp
);
}
function _addMaxLiquidityEth(address router, address token0) internal {
uint256 _token0Balance =
IERC20Upgradeable(token0).balanceOf(address(this));
uint256 _ethBalance = address(this).balance;
_safeApproveHelper(token0, router, _token0Balance);
IUniswapRouterV2(router).addLiquidityETH{value: address(this).balance}(
token0,
_token0Balance,
0,
0,
address(this),
block.timestamp
);
}
}
// File deps/libraries/TokenSwapPathRegistry.sol
pragma solidity ^0.6.11;
/*
Expands swapping functionality over base strategy
- ETH in and ETH out Variants
- Sushiswap support in addition to Uniswap
*/
contract TokenSwapPathRegistry {
mapping(address => mapping(address => address[])) public tokenSwapPaths;
event TokenSwapPathSet(address tokenIn, address tokenOut, address[] path);
function getTokenSwapPath(address tokenIn, address tokenOut)
public
view
returns (address[] memory)
{
return tokenSwapPaths[tokenIn][tokenOut];
}
function _setTokenSwapPath(
address tokenIn,
address tokenOut,
address[] memory path
) internal {
tokenSwapPaths[tokenIn][tokenOut] = path;
emit TokenSwapPathSet(tokenIn, tokenOut, path);
}
}
// File contracts/StrategyConvexStables.sol
pragma solidity ^0.6.11;
/*
=== Deposit ===
Deposit & Stake underlying asset into appropriate convex vault (deposit + stake is atomic)
=== Tend ===
1. Harvest gains from positions
2. Convert CRV -> cvxCRV
3. Stake all cvxCRV
4. Stake all CVX
=== Harvest ===
1. Withdraw accrued rewards from staking positions (claim unclaimed positions as well)
2. Convert 3CRV -> CRV via USDC
3. Swap CRV -> cvxCRV
4. Process fees on cvxCRV harvested + swapped
5. Deposit remaining cvxCRV into helper vault and distribute
6. Process fees on CVX, swap CVX for bveCVX and distribute
*/
contract StrategyConvexStables is
BaseStrategy,
CurveSwapper,
UniswapSwapper,
TokenSwapPathRegistry
{
using SafeERC20Upgradeable for IERC20Upgradeable;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
// ===== Token Registry =====
address public constant wbtc = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599;
address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant crv = 0xD533a949740bb3306d119CC777fa900bA034cd52;
address public constant cvx = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B;
address public constant cvxCrv = 0x62B9c7356A2Dc64a1969e19C23e4f579F9810Aa7;
address public constant usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address public constant threeCrv =
0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490;
IERC20Upgradeable public constant wbtcToken =
IERC20Upgradeable(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599);
IERC20Upgradeable public constant crvToken =
IERC20Upgradeable(0xD533a949740bb3306d119CC777fa900bA034cd52);
IERC20Upgradeable public constant cvxToken =
IERC20Upgradeable(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B);
IERC20Upgradeable public constant cvxCrvToken =
IERC20Upgradeable(0x62B9c7356A2Dc64a1969e19C23e4f579F9810Aa7);
IERC20Upgradeable public constant usdcToken =
IERC20Upgradeable(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
IERC20Upgradeable public constant threeCrvToken =
IERC20Upgradeable(0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490);
IERC20Upgradeable public constant bveCVX =
IERC20Upgradeable(0xfd05D3C7fe2924020620A8bE4961bBaA747e6305);
// ===== Convex Registry =====
CrvDepositor public constant crvDepositor =
CrvDepositor(0x8014595F2AB54cD7c604B00E9fb932176fDc86Ae); // Convert CRV -> cvxCRV
IBooster public constant booster =
IBooster(0xF403C135812408BFbE8713b5A23a04b3D48AAE31);
IBaseRewardsPool public baseRewardsPool;
IBaseRewardsPool public constant cvxCrvRewardsPool =
IBaseRewardsPool(0x3Fe65692bfCD0e6CF84cB1E7d24108E434A7587e);
ICvxRewardsPool public constant cvxRewardsPool =
ICvxRewardsPool(0xCF50b810E57Ac33B91dCF525C6ddd9881B139332);
address public constant threeCrvSwap =
0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7;
uint256 public constant MAX_UINT_256 = uint256(-1);
uint256 public pid;
address public badgerTree;
ISettV4 public cvxCrvHelperVault;
/**
=== Harvest Config ===
- stableSwapSlippageTolerance: Sets the slippage tolerance for the CRV -> cvxCRV swap and the CVX -> bveCVX swap
- minThreeCrvHarvest: Minimum amount of 3Crv that must be harvestd (or previously harvested) for it to be processed
*/
uint256 public stableSwapSlippageTolerance;
uint256 public constant crvCvxCrvPoolIndex = 2;
// Minimum 3Crv harvested to perform a profitable swap on it
uint256 public minThreeCrvHarvest;
event TreeDistribution(
address indexed token,
uint256 amount,
uint256 indexed blockNumber,
uint256 timestamp
);
event PerformanceFeeGovernance(
address indexed destination,
address indexed token,
uint256 amount,
uint256 indexed blockNumber,
uint256 timestamp
);
event PerformanceFeeStrategist(
address indexed destination,
address indexed token,
uint256 amount,
uint256 indexed blockNumber,
uint256 timestamp
);
event WithdrawState(
uint256 toWithdraw,
uint256 preWant,
uint256 postWant,
uint256 withdrawn
);
struct TendData {
uint256 crvTended;
uint256 cvxTended;
uint256 cvxCrvTended;
}
event TendState(uint256 crvTended, uint256 cvxTended, uint256 cvxCrvTended);
function initialize(
address _governance,
address _strategist,
address _controller,
address _keeper,
address _guardian,
address[3] memory _wantConfig,
uint256 _pid,
uint256[3] memory _feeConfig
) public initializer whenNotPaused {
__BaseStrategy_init(
_governance,
_strategist,
_controller,
_keeper,
_guardian
);
want = _wantConfig[0];
badgerTree = _wantConfig[1];
cvxCrvHelperVault = ISettV4(_wantConfig[2]);
pid = _pid; // Core staking pool ID
IBooster.PoolInfo memory poolInfo = booster.poolInfo(pid);
baseRewardsPool = IBaseRewardsPool(poolInfo.crvRewards);
performanceFeeGovernance = _feeConfig[0];
performanceFeeStrategist = _feeConfig[1];
withdrawalFee = _feeConfig[2];
// Approvals: Staking Pools
IERC20Upgradeable(want).approve(address(booster), MAX_UINT_256);
cvxToken.approve(address(cvxRewardsPool), MAX_UINT_256);
cvxCrvToken.approve(address(cvxCrvRewardsPool), MAX_UINT_256);
// Approvals: CRV -> cvxCRV converter
crvToken.approve(address(crvDepositor), MAX_UINT_256);
// Set Swap Paths
address[] memory path = new address[](3);
path[0] = usdc;
path[1] = weth;
path[2] = crv;
_setTokenSwapPath(usdc, crv, path);
_initializeApprovals();
// Set default values
stableSwapSlippageTolerance = 500;
minThreeCrvHarvest = 1000e18;
}
/// ===== Permissioned Functions =====
function setPid(uint256 _pid) external {
_onlyGovernance();
pid = _pid; // LP token pool ID
}
function initializeApprovals() external {
_onlyGovernance();
_initializeApprovals();
}
function setstableSwapSlippageTolerance(uint256 _sl) external {
_onlyGovernance();
stableSwapSlippageTolerance = _sl;
}
function setMinThreeCrvHarvest(uint256 _minThreeCrvHarvest) external {
_onlyGovernance();
minThreeCrvHarvest = _minThreeCrvHarvest;
}
function _initializeApprovals() internal {
cvxCrvToken.approve(address(cvxCrvHelperVault), MAX_UINT_256);
}
/// ===== View Functions =====
function version() external pure returns (string memory) {
return "1.0";
}
function getName() external pure override returns (string memory) {
return "StrategyConvexStables";
}
function balanceOfPool() public view override returns (uint256) {
return baseRewardsPool.balanceOf(address(this));
}
function getProtectedTokens()
public
view
override
returns (address[] memory)
{
address[] memory protectedTokens = new address[](4);
protectedTokens[0] = want;
protectedTokens[1] = crv;
protectedTokens[2] = cvx;
protectedTokens[3] = cvxCrv;
return protectedTokens;
}
function isTendable() public view override returns (bool) {
return true;
}
/// ===== Internal Core Implementations =====
function _onlyNotProtectedTokens(address _asset) internal override {
require(address(want) != _asset, "want");
require(address(crv) != _asset, "crv");
require(address(cvx) != _asset, "cvx");
require(address(cvxCrv) != _asset, "cvxCrv");
}
/// @dev Deposit Badger into the staking contract
function _deposit(uint256 _want) internal override {
// Deposit all want in core staking pool
booster.deposit(pid, _want, true);
}
/// @dev Unroll from all strategy positions, and transfer non-core tokens to controller rewards
function _withdrawAll() internal override {
baseRewardsPool.withdrawAndUnwrap(balanceOfPool(), false);
// Note: All want is automatically withdrawn outside this "inner hook" in base strategy function
}
/// @dev Withdraw want from staking rewards, using earnings first
function _withdrawSome(uint256 _amount)
internal
override
returns (uint256)
{
// Get idle want in the strategy
uint256 _preWant = IERC20Upgradeable(want).balanceOf(address(this));
// If we lack sufficient idle want, withdraw the difference from the strategy position
if (_preWant < _amount) {
uint256 _toWithdraw = _amount.sub(_preWant);
baseRewardsPool.withdrawAndUnwrap(_toWithdraw, false);
}
// Confirm how much want we actually end up with
uint256 _postWant = IERC20Upgradeable(want).balanceOf(address(this));
// Return the actual amount withdrawn if less than requested
uint256 _withdrawn = MathUpgradeable.min(_postWant, _amount);
emit WithdrawState(_amount, _preWant, _postWant, _withdrawn);
return _withdrawn;
}
function _tendGainsFromPositions() internal {
// Harvest CRV, CVX, cvxCRV, 3CRV, and extra rewards tokens from staking positions
// Note: Always claim extras
baseRewardsPool.getReward(address(this), true);
if (cvxCrvRewardsPool.earned(address(this)) > 0) {
cvxCrvRewardsPool.getReward(address(this), true);
}
if (cvxRewardsPool.earned(address(this)) > 0) {
cvxRewardsPool.getReward(false);
}
}
/// @notice The more frequent the tend, the higher returns will be
function tend() external whenNotPaused returns (TendData memory) {
_onlyAuthorizedActors();
TendData memory tendData;
// 1. Harvest gains from positions
_tendGainsFromPositions();
// Track harvested coins, before conversion
tendData.crvTended = crvToken.balanceOf(address(this));
// 2. Convert CRV -> cvxCRV
if (tendData.crvTended > 0) {
uint256 minCvxCrvOut =
tendData
.crvTended
.mul(MAX_FEE.sub(stableSwapSlippageTolerance))
.div(MAX_FEE);
_exchange(
crv,
cvxCrv,
tendData.crvTended,
minCvxCrvOut,
crvCvxCrvPoolIndex,
true
);
}
// Track harvested + converted coins
tendData.cvxCrvTended = cvxCrvToken.balanceOf(address(this));
tendData.cvxTended = cvxToken.balanceOf(address(this));
// 3. Stake all cvxCRV
if (tendData.cvxCrvTended > 0) {
cvxCrvRewardsPool.stake(tendData.cvxCrvTended);
}
// 4. Stake all CVX
if (tendData.cvxTended > 0) {
cvxRewardsPool.stake(cvxToken.balanceOf(address(this)));
}
emit Tend(0);
emit TendState(
tendData.crvTended,
tendData.cvxTended,
tendData.cvxCrvTended
);
return tendData;
}
// No-op until we optimize harvesting strategy. Auto-compouding is key.
function harvest() external whenNotPaused returns (uint256) {
_onlyAuthorizedActors();
uint256 totalWantBefore = balanceOf();
// 1. Withdraw accrued rewards from staking positions (claim unclaimed positions as well)
baseRewardsPool.getReward(address(this), true);
uint256 cvxCrvRewardsPoolBalance =
cvxCrvRewardsPool.balanceOf(address(this));
if (cvxCrvRewardsPoolBalance > 0) {
cvxCrvRewardsPool.withdraw(cvxCrvRewardsPoolBalance, true);
}
uint256 cvxRewardsPoolBalance = cvxRewardsPool.balanceOf(address(this));
if (cvxRewardsPoolBalance > 0) {
cvxRewardsPool.withdraw(cvxRewardsPoolBalance, true);
}
// 2. Convert 3CRV -> CRV via USDC
uint256 threeCrvBalance = threeCrvToken.balanceOf(address(this));
if (threeCrvBalance > minThreeCrvHarvest) {
_remove_liquidity_one_coin(threeCrvSwap, threeCrvBalance, 1, 0);
uint256 usdcBalance = usdcToken.balanceOf(address(this));
if (usdcBalance > 0) {
_swapExactTokensForTokens(
sushiswap,
usdc,
usdcBalance,
getTokenSwapPath(usdc, crv)
);
}
}
// 3. Swap CRV -> cvxCRV
uint256 crvBalance = crvToken.balanceOf(address(this));
if (crvBalance > 0) {
uint256 minCvxCrvOut =
crvBalance.mul(MAX_FEE.sub(stableSwapSlippageTolerance)).div(
MAX_FEE
);
_exchange(
crv,
cvxCrv,
crvBalance,
minCvxCrvOut,
crvCvxCrvPoolIndex,
true
);
}
// 4. Process fees on cvxCRV harvested + swapped
uint256 cvxCrvBalance = cvxCrvToken.balanceOf(address(this));
if (cvxCrvBalance > 0) {
// Process performance fees on cvxCrv
if (performanceFeeGovernance > 0) {
uint256 cvxCrvToGovernance =
cvxCrvBalance.mul(performanceFeeGovernance).div(MAX_FEE);
cvxCrvToken.safeTransfer(
IController(controller).rewards(),
cvxCrvToGovernance
);
emit PerformanceFeeGovernance(
IController(controller).rewards(),
cvxCrv,
cvxCrvToGovernance,
block.number,
block.timestamp
);
}
if (performanceFeeStrategist > 0) {
uint256 cvxCrvToStrategist =
cvxCrvBalance.mul(performanceFeeStrategist).div(MAX_FEE);
crvToken.safeTransfer(strategist, cvxCrvToStrategist);
emit PerformanceFeeStrategist(
strategist,
cvxCrv,
cvxCrvToStrategist,
block.number,
block.timestamp
);
}
// 5. Deposit remaining cvxCRV into helper vault and distribute
uint256 cvxCrvToTree = cvxCrvToken.balanceOf(address(this));
// TODO: [Optimization] Allow contract to circumvent blockLock to dedup deposit operations
uint256 treeHelperVaultBefore =
cvxCrvHelperVault.balanceOf(badgerTree);
// Deposit remaining to tree
cvxCrvHelperVault.depositFor(badgerTree, cvxCrvToTree);
uint256 treeHelperVaultAfter =
cvxCrvHelperVault.balanceOf(badgerTree);
uint256 treeVaultPositionGained =
treeHelperVaultAfter.sub(treeHelperVaultBefore);
emit TreeDistribution(
address(cvxCrvHelperVault),
treeVaultPositionGained,
block.number,
block.timestamp
);
}
// 6. Process fees on CVX, swap CVX for bveCVX and distribute
uint256 cvxBalance = cvxToken.balanceOf(address(this));
if (cvxBalance > 0) {
// Process performance fees on CVX
if (performanceFeeGovernance > 0) {
uint256 cvxToGovernance =
cvxBalance.mul(performanceFeeGovernance).div(MAX_FEE);
cvxToken.safeTransfer(
IController(controller).rewards(),
cvxToGovernance
);
emit PerformanceFeeGovernance(
IController(controller).rewards(),
cvx,
cvxToGovernance,
block.number,
block.timestamp
);
}
if (performanceFeeStrategist > 0) {
uint256 cvxToStrategist =
cvxBalance.mul(performanceFeeStrategist).div(MAX_FEE);
cvxToken.safeTransfer(strategist, cvxToStrategist);
emit PerformanceFeeStrategist(
strategist,
cvx,
cvxToStrategist,
block.number,
block.timestamp
);
}
// Exchange remaining CVX for bveCVX
uint256 cvxToDistribute = cvxToken.balanceOf(address(this));
uint256 minbveCVXOut =
cvxToDistribute
.mul(MAX_FEE.sub(stableSwapSlippageTolerance))
.div(MAX_FEE);
// Get the bveCVX here
_exchange(
address(cvxToken),
address(bveCVX),
cvxToDistribute,
minbveCVXOut,
0,
true
);
uint256 treeHelperVaultBefore = bveCVX.balanceOf(badgerTree);
// Deposit remaining to tree.
uint256 bveCvxToTree = bveCVX.balanceOf(address(this));
bveCVX.safeTransfer(badgerTree, bveCvxToTree);
uint256 treeHelperVaultAfter = bveCVX.balanceOf(badgerTree);
uint256 treeVaultPositionGained =
treeHelperVaultAfter.sub(treeHelperVaultBefore);
emit TreeDistribution(
address(bveCVX),
treeVaultPositionGained,
block.number,
block.timestamp
);
}
uint256 totalWantAfter = balanceOf();
require(totalWantAfter >= totalWantBefore, "want-decreased");
// Expected to be 0 since there is no auto compounding
uint256 wantGained = totalWantAfter - totalWantBefore;
emit Harvest(wantGained, block.number);
return wantGained;
}
} | No-op until we optimize harvesting strategy. Auto-compouding is key. 1. Withdraw accrued rewards from staking positions (claim unclaimed positions as well) Process performance fees on cvxCrv Process performance fees on CVX | function harvest() external whenNotPaused returns (uint256) {
_onlyAuthorizedActors();
uint256 totalWantBefore = balanceOf();
baseRewardsPool.getReward(address(this), true);
uint256 cvxCrvRewardsPoolBalance =
cvxCrvRewardsPool.balanceOf(address(this));
if (cvxCrvRewardsPoolBalance > 0) {
cvxCrvRewardsPool.withdraw(cvxCrvRewardsPoolBalance, true);
}
uint256 cvxRewardsPoolBalance = cvxRewardsPool.balanceOf(address(this));
if (cvxRewardsPoolBalance > 0) {
cvxRewardsPool.withdraw(cvxRewardsPoolBalance, true);
}
if (threeCrvBalance > minThreeCrvHarvest) {
_remove_liquidity_one_coin(threeCrvSwap, threeCrvBalance, 1, 0);
uint256 usdcBalance = usdcToken.balanceOf(address(this));
if (usdcBalance > 0) {
_swapExactTokensForTokens(
sushiswap,
usdc,
usdcBalance,
getTokenSwapPath(usdc, crv)
);
}
}
if (crvBalance > 0) {
uint256 minCvxCrvOut =
crvBalance.mul(MAX_FEE.sub(stableSwapSlippageTolerance)).div(
MAX_FEE
);
_exchange(
crv,
cvxCrv,
crvBalance,
minCvxCrvOut,
crvCvxCrvPoolIndex,
true
);
}
if (cvxCrvBalance > 0) {
if (performanceFeeGovernance > 0) {
uint256 cvxCrvToGovernance =
cvxCrvBalance.mul(performanceFeeGovernance).div(MAX_FEE);
cvxCrvToken.safeTransfer(
IController(controller).rewards(),
cvxCrvToGovernance
);
emit PerformanceFeeGovernance(
IController(controller).rewards(),
cvxCrv,
cvxCrvToGovernance,
block.number,
block.timestamp
);
}
if (performanceFeeStrategist > 0) {
uint256 cvxCrvToStrategist =
cvxCrvBalance.mul(performanceFeeStrategist).div(MAX_FEE);
crvToken.safeTransfer(strategist, cvxCrvToStrategist);
emit PerformanceFeeStrategist(
strategist,
cvxCrv,
cvxCrvToStrategist,
block.number,
block.timestamp
);
}
uint256 treeHelperVaultBefore =
cvxCrvHelperVault.balanceOf(badgerTree);
uint256 treeHelperVaultAfter =
cvxCrvHelperVault.balanceOf(badgerTree);
uint256 treeVaultPositionGained =
treeHelperVaultAfter.sub(treeHelperVaultBefore);
emit TreeDistribution(
address(cvxCrvHelperVault),
treeVaultPositionGained,
block.number,
block.timestamp
);
}
if (cvxBalance > 0) {
if (performanceFeeGovernance > 0) {
uint256 cvxToGovernance =
cvxBalance.mul(performanceFeeGovernance).div(MAX_FEE);
cvxToken.safeTransfer(
IController(controller).rewards(),
cvxToGovernance
);
emit PerformanceFeeGovernance(
IController(controller).rewards(),
cvx,
cvxToGovernance,
block.number,
block.timestamp
);
}
if (performanceFeeStrategist > 0) {
uint256 cvxToStrategist =
cvxBalance.mul(performanceFeeStrategist).div(MAX_FEE);
cvxToken.safeTransfer(strategist, cvxToStrategist);
emit PerformanceFeeStrategist(
strategist,
cvx,
cvxToStrategist,
block.number,
block.timestamp
);
}
uint256 minbveCVXOut =
cvxToDistribute
.mul(MAX_FEE.sub(stableSwapSlippageTolerance))
.div(MAX_FEE);
address(cvxToken),
address(bveCVX),
cvxToDistribute,
minbveCVXOut,
0,
true
);
uint256 treeHelperVaultBefore = bveCVX.balanceOf(badgerTree);
bveCVX.safeTransfer(badgerTree, bveCvxToTree);
uint256 treeHelperVaultAfter = bveCVX.balanceOf(badgerTree);
uint256 treeVaultPositionGained =
treeHelperVaultAfter.sub(treeHelperVaultBefore);
emit TreeDistribution(
address(bveCVX),
treeVaultPositionGained,
block.number,
block.timestamp
);
}
uint256 totalWantAfter = balanceOf();
require(totalWantAfter >= totalWantBefore, "want-decreased");
emit Harvest(wantGained, block.number);
return wantGained;
}
| 10,587,320 |
pragma solidity 0.4.24;
/**
* CryptoCanvas Terms of Use
*
* 1. Intro
*
* CryptoCanvas is a set of collectible artworks (“Canvas”) created by the CryptoCanvas community with proof of ownership stored on the Ethereum blockchain.
*
* This agreement does a few things. First, it passes copyright ownership of a Canvas from the Canvas Authors to the first Canvas Owner. The first Canvas Owner is then obligated to pass on the copyright ownership along with the Canvas to the next owner, and so on forever, such that each owner of a Canvas is also the copyright owner. Second, it requires each Canvas Owner to allow certain uses of their Canvas image. Third, it limits the rights of Canvas owners to sue The Mindhouse and the prior owners of the Canvas.
*
* Canvases of CryptoCanvas are not an investment. They are experimental digital art.
*
* PLEASE READ THESE TERMS CAREFULLY BEFORE USING THE APP, THE SMART CONTRACTS, OR THE SITE. BY USING THE APP, THE SMART CONTRACTS, THE SITE, OR ANY PART OF THEM YOU ARE CONFIRMING THAT YOU UNDERSTAND AND AGREE TO BE BOUND BY ALL OF THESE TERMS. IF YOU ARE ACCEPTING THESE TERMS ON BEHALF OF A COMPANY OR OTHER LEGAL ENTITY, YOU REPRESENT THAT YOU HAVE THE LEGAL AUTHORITY TO ACCEPT THESE TERMS ON THAT ENTITY’S BEHALF, IN WHICH CASE “YOU” WILL MEAN THAT ENTITY. IF YOU DO NOT HAVE SUCH AUTHORITY, OR IF YOU DO NOT ACCEPT ALL OF THESE TERMS, THEN WE ARE UNWILLING TO MAKE THE APP, THE SMART CONTRACTS, OR THE SITE AVAILABLE TO YOU. IF YOU DO NOT AGREE TO THESE TERMS, YOU MAY NOT ACCESS OR USE THE APP, THE SMART CONTRACTS, OR THE SITE.
*
* 2. Definitions
*
* “Smart Contract” refers to this smart contract.
*
* “Canvas” means a collectible artwork created by the CryptoCanvas community with information about the color and author of each pixel of the Canvas, and proof of ownership stored in the Smart Contract. The Canvas is considered finished when all the pixels of the Canvas have their color set. Specifically, the Canvas is considered finished when its “state” field in the Smart Contract equals to STATE_INITIAL_BIDDING or STATE_OWNED constant.
*
* “Canvas Author” means the person who painted at least one final pixel of the finished Canvas by sending a transaction to the Smart Contract. Specifically, Canvas Author means the person with the private key for at least one address in the “painter” field of the “pixels” field of the applicable Canvas in the Smart Contract.
*
* “Canvas Owner” means the person that can cryptographically prove ownership of the applicable Canvas. Specifically, Canvas Owner means the person with the private key for the address in the “owner” field of the applicable Canvas in the Smart Contract. The person is the Canvas Owner only after the Initial Bidding phase is finished, that is when the field “state” of the applicable Canvas equals to the STATE_OWNED constant.
*
* “Initial Bidding” means the state of the Canvas when each of its pixels has been set by Canvas Authors but it does not have the Canvas Owner yet. In this phase any user can claim the ownership of the Canvas by sending a transaction to the Smart Contract (a “Bid”). Other users have 48 hours from the time of making the first Bid on the Canvas to submit their own Bids. After that time, the user who sent the highest Bid becomes the sole Canvas Owner of the applicable Canvas. Users who placed Bids with lower amounts are able to withdraw their Bid amount from their Account Balance.
*
* “Account Balance” means the value stored in the Smart Contract assigned to an address. The Account Balance can be withdrawn by the person with the private key for the applicable address by sending a transaction to the Smart Contract. Account Balance consists of Rewards for painting, Bids from Initial Bidding which have been overbid, cancelled offers to buy a Canvas and profits from selling a Canvas.
*
* “The Mindhouse”, “we” or “us” is the group of developers who created and published the CryptoCanvas Smart Contract.
*
* “The App” means collectively the Smart Contract and the website created by The Mindhouse to interact with the Smart Contract.
*
* 3. Intellectual Property
*
* A. First Assignment
* The Canvas Authors of the applicable Canvas hereby assign all copyright ownership in the Canvas to the Canvas Owner. In exchange for this copyright ownership, the Canvas Owner agrees to the terms below.
*
* B. Later Assignments
* When the Canvas Owner transfers the Canvas to a new owner, the Canvas Owner hereby agrees to assign all copyright ownership in the Canvas to the new owner of the Canvas. In exchange for these rights, the new owner shall agree to become the Canvas Owner, and shall agree to be subject to this Terms of Use.
*
* C. No Other Assignments.
* The Canvas Owner shall not assign or license the copyright except as set forth in the “Later Assignments” section above.
*
* D. Third Party Permissions.
* The Canvas Owner agrees to allow CryptoCanvas fans to make non-commercial Use of images of the Canvas to discuss CryptoCanvas, digital collectibles and related matters. “Use” means to reproduce, display, transmit, and distribute images of the Canvas. This permission excludes the right to print the Canvas onto physical copies (including, for example, shirts and posters).
*
* 4. Fees and Payment
*
* A. If you choose to paint, make a bid or trade any Canvas of CryptoCanvas any financial transactions that you engage in will be conducted solely through the Ethereum network via MetaMask. We will have no insight into or control over these payments or transactions, nor do we have the ability to reverse any transactions. With that in mind, we will have no liability to you or to any third party for any claims or damages that may arise as a result of any transactions that you engage in via the App, or using the Smart Contracts, or any other transactions that you conduct via the Ethereum network or MetaMask.
*
* B. Ethereum requires the payment of a transaction fee (a “Gas Fee”) for every transaction that occurs on the Ethereum network. The Gas Fee funds the network of computers that run the decentralized Ethereum network. This means that you will need to pay a Gas Fee for each transaction that occurs via the App.
*
* C. In addition to the Gas Fee, each time you sell a Canvas to another user of the App, you authorize us to collect a fee of 10% of the total value of that transaction. That fee consists of:
1) 3.9% of the total value of that transaction (a “Commission”). You acknowledge and agree that the Commission will be transferred to us through the Ethereum network as a part of the payment.
2) 6.1% of the total value of that transaction (a “Reward”). You acknowledge and agree that the Reward will be transferred evenly to all painters of the sold canvas through the Ethereum network as a part of the payment.
*
* D. If you are the Canvas Author you are eligible to receive a reward for painting a Canvas (a “Reward”). A Reward is distributed in these scenarios:
1) After the Initial Bidding phase is completed. You acknowledge and agree that the Reward for the Canvas Author will be calculated by dividing the value of the winning Bid, decreased by our commission of 3.9% of the total value of the Bid, by the total number of pixels of the Canvas and multiplied by the number of pixels of the Canvas that have been painted by applicable Canvas Author.
2) Each time the Canvas is sold. You acknowledge and agree that the Reward for the Canvas Author will be calculated by dividing 6.1% of the total transaction value by the total number of pixels of the Canvas and multiplied by the number of pixels of the Canvas that have been painted by the applicable Canvas Author.
You acknowledge and agree that in order to withdraw the Reward you first need to add the Reward to your Account Balance by sending a transaction to the Smart Contract.
*
* 5. Disclaimers
*
* A. YOU EXPRESSLY UNDERSTAND AND AGREE THAT YOUR ACCESS TO AND USE OF THE APP IS AT YOUR SOLE RISK, AND THAT THE APP IS PROVIDED "AS IS" AND "AS AVAILABLE" WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR IMPLIED. TO THE FULLEST EXTENT PERMISSIBLE PURSUANT TO APPLICABLE LAW, WE, OUR SUBSIDIARIES, AFFILIATES, AND LICENSORS MAKE NO EXPRESS WARRANTIES AND HEREBY DISCLAIM ALL IMPLIED WARRANTIES REGARDING THE APP AND ANY PART OF IT (INCLUDING, WITHOUT LIMITATION, THE SITE, ANY SMART CONTRACT, OR ANY EXTERNAL WEBSITES), INCLUDING THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, CORRECTNESS, ACCURACY, OR RELIABILITY. WITHOUT LIMITING THE GENERALITY OF THE FOREGOING, WE, OUR SUBSIDIARIES, AFFILIATES, AND LICENSORS DO NOT REPRESENT OR WARRANT TO YOU THAT: (I) YOUR ACCESS TO OR USE OF THE APP WILL MEET YOUR REQUIREMENTS, (II) YOUR ACCESS TO OR USE OF THE APP WILL BE UNINTERRUPTED, TIMELY, SECURE OR FREE FROM ERROR, (III) USAGE DATA PROVIDED THROUGH THE APP WILL BE ACCURATE, (III) THE APP OR ANY CONTENT, SERVICES, OR FEATURES MADE AVAILABLE ON OR THROUGH THE APP ARE FREE OF VIRUSES OR OTHER HARMFUL COMPONENTS, OR (IV) THAT ANY DATA THAT YOU DISCLOSE WHEN YOU USE THE APP WILL BE SECURE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES IN CONTRACTS WITH CONSUMERS, SO SOME OR ALL OF THE ABOVE EXCLUSIONS MAY NOT APPLY TO YOU.
*
* B. YOU ACCEPT THE INHERENT SECURITY RISKS OF PROVIDING INFORMATION AND DEALING ONLINE OVER THE INTERNET, AND AGREE THAT WE HAVE NO LIABILITY OR RESPONSIBILITY FOR ANY BREACH OF SECURITY UNLESS IT IS DUE TO OUR GROSS NEGLIGENCE.
*
* C. WE WILL NOT BE RESPONSIBLE OR LIABLE TO YOU FOR ANY LOSSES YOU INCUR AS THE RESULT OF YOUR USE OF THE ETHEREUM NETWORK OR THE METAMASK ELECTRONIC WALLET, INCLUDING BUT NOT LIMITED TO ANY LOSSES, DAMAGES OR CLAIMS ARISING FROM: (A) USER ERROR, SUCH AS FORGOTTEN PASSWORDS OR INCORRECTLY CONSTRUED SMART CONTRACTS OR OTHER TRANSACTIONS; (B) SERVER FAILURE OR DATA LOSS; (C) CORRUPTED WALLET FILES; (D) UNAUTHORIZED ACCESS OR ACTIVITIES BY THIRD PARTIES, INCLUDING BUT NOT LIMITED TO THE USE OF VIRUSES, PHISHING, BRUTEFORCING OR OTHER MEANS OF ATTACK AGAINST THE APP, ETHEREUM NETWORK, OR THE METAMASK ELECTRONIC WALLET.
*
* D. THE CANVASES OF CRYPTOCANVAS ARE INTANGIBLE DIGITAL ASSETS THAT EXIST ONLY BY VIRTUE OF THE OWNERSHIP RECORD MAINTAINED IN THE ETHEREUM NETWORK. ALL SMART CONTRACTS ARE CONDUCTED AND OCCUR ON THE DECENTRALIZED LEDGER WITHIN THE ETHEREUM PLATFORM. WE HAVE NO CONTROL OVER AND MAKE NO GUARANTEES OR PROMISES WITH RESPECT TO SMART CONTRACTS.
*
* E. THE MINDHOUSE IS NOT RESPONSIBLE FOR LOSSES DUE TO BLOCKCHAINS OR ANY OTHER FEATURES OF THE ETHEREUM NETWORK OR THE METAMASK ELECTRONIC WALLET, INCLUDING BUT NOT LIMITED TO LATE REPORT BY DEVELOPERS OR REPRESENTATIVES (OR NO REPORT AT ALL) OF ANY ISSUES WITH THE BLOCKCHAIN SUPPORTING THE ETHEREUM NETWORK, INCLUDING FORKS, TECHNICAL NODE ISSUES, OR ANY OTHER ISSUES HAVING FUND LOSSES AS A RESULT.
*
* 6. Limitation of Liability
* YOU UNDERSTAND AND AGREE THAT WE, OUR SUBSIDIARIES, AFFILIATES, AND LICENSORS WILL NOT BE LIABLE TO YOU OR TO ANY THIRD PARTY FOR ANY CONSEQUENTIAL, INCIDENTAL, INDIRECT, EXEMPLARY, SPECIAL, PUNITIVE, OR ENHANCED DAMAGES, OR FOR ANY LOSS OF ACTUAL OR ANTICIPATED PROFITS (REGARDLESS OF HOW THESE ARE CLASSIFIED AS DAMAGES), WHETHER ARISING OUT OF BREACH OF CONTRACT, TORT (INCLUDING NEGLIGENCE), OR OTHERWISE, REGARDLESS OF WHETHER SUCH DAMAGE WAS FORESEEABLE AND WHETHER EITHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*/
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @dev Contract that is aware of time. Useful for tests - like this
* we can mock time.
*/
contract TimeAware is Ownable {
/**
* @dev Returns current time.
*/
function getTime() public view returns (uint) {
return now;
}
}
/**
* @dev Contract that holds pending withdrawals. Responsible for withdrawals.
*/
contract Withdrawable {
mapping(address => uint) private pendingWithdrawals;
event Withdrawal(address indexed receiver, uint amount);
event BalanceChanged(address indexed _address, uint oldBalance, uint newBalance);
/**
* Returns amount of wei that given address is able to withdraw.
*/
function getPendingWithdrawal(address _address) public view returns (uint) {
return pendingWithdrawals[_address];
}
/**
* Add pending withdrawal for an address.
*/
function addPendingWithdrawal(address _address, uint _amount) internal {
require(_address != 0x0);
uint oldBalance = pendingWithdrawals[_address];
pendingWithdrawals[_address] += _amount;
emit BalanceChanged(_address, oldBalance, oldBalance + _amount);
}
/**
* Withdraws all pending withdrawals.
*/
function withdraw() external {
uint amount = getPendingWithdrawal(msg.sender);
require(amount > 0);
pendingWithdrawals[msg.sender] = 0;
msg.sender.transfer(amount);
emit Withdrawal(msg.sender, amount);
emit BalanceChanged(msg.sender, amount, 0);
}
}
/**
* @dev This contract takes care of painting on canvases, returning artworks and creating ones.
*/
contract CanvasFactory is TimeAware, Withdrawable {
//@dev It means canvas is not finished yet, and bidding is not possible.
uint8 public constant STATE_NOT_FINISHED = 0;
//@dev there is ongoing bidding and anybody can bid. If there canvas can have
// assigned owner, but it can change if someone will over-bid him.
uint8 public constant STATE_INITIAL_BIDDING = 1;
//@dev canvas has been sold, and has the owner
uint8 public constant STATE_OWNED = 2;
uint8 public constant WIDTH = 48;
uint8 public constant HEIGHT = 48;
uint32 public constant PIXEL_COUNT = 2304; //WIDTH * HEIGHT doesn't work for some reason
uint32 public constant MAX_CANVAS_COUNT = 1000;
uint8 public constant MAX_ACTIVE_CANVAS = 12;
uint8 public constant MAX_CANVAS_NAME_LENGTH = 24;
Canvas[] canvases;
uint32 public activeCanvasCount = 0;
event PixelPainted(uint32 indexed canvasId, uint32 index, uint8 color, address indexed painter);
event CanvasFinished(uint32 indexed canvasId);
event CanvasCreated(uint indexed canvasId, address indexed bookedFor);
event CanvasNameSet(uint indexed canvasId, string name);
modifier notFinished(uint32 _canvasId) {
require(!isCanvasFinished(_canvasId));
_;
}
modifier finished(uint32 _canvasId) {
require(isCanvasFinished(_canvasId));
_;
}
modifier validPixelIndex(uint32 _pixelIndex) {
require(_pixelIndex < PIXEL_COUNT);
_;
}
/**
* @notice Creates new canvas. There can't be more canvases then MAX_CANVAS_COUNT.
* There can't be more unfinished canvases than MAX_ACTIVE_CANVAS.
*/
function createCanvas() external returns (uint canvasId) {
return _createCanvasInternal(0x0);
}
/**
* @notice Similar to createCanvas(). Books it for given address. If address is 0x0 everybody will
* be allowed to paint on a canvas.
*/
function createAndBookCanvas(address _bookFor) external onlyOwner returns (uint canvasId) {
return _createCanvasInternal(_bookFor);
}
/**
* @notice Changes canvas.bookFor variable. Only for the owner of the contract.
*/
function bookCanvasFor(uint32 _canvasId, address _bookFor) external onlyOwner {
Canvas storage _canvas = _getCanvas(_canvasId);
_canvas.bookedFor = _bookFor;
}
/**
* @notice Sets pixel. Given canvas can't be yet finished.
*/
function setPixel(uint32 _canvasId, uint32 _index, uint8 _color) external {
Canvas storage _canvas = _getCanvas(_canvasId);
_setPixelInternal(_canvas, _canvasId, _index, _color);
_finishCanvasIfNeeded(_canvas, _canvasId);
}
/**
* Set many pixels with one tx. Be careful though - sending a lot of pixels
* to set may cause out of gas error.
*
* Throws when none of the pixels has been set.
*
*/
function setPixels(uint32 _canvasId, uint32[] _indexes, uint8[] _colors) external {
require(_indexes.length == _colors.length);
Canvas storage _canvas = _getCanvas(_canvasId);
bool anySet = false;
for (uint32 i = 0; i < _indexes.length; i++) {
Pixel storage _pixel = _canvas.pixels[_indexes[i]];
if (_pixel.painter == 0x0) {
//only allow when pixel is not set
_setPixelInternal(_canvas, _canvasId, _indexes[i], _colors[i]);
anySet = true;
}
}
if (!anySet) {
//If didn't set any pixels - revert to show that transaction failed
revert();
}
_finishCanvasIfNeeded(_canvas, _canvasId);
}
/**
* @notice Returns full bitmap for given canvas.
*/
function getCanvasBitmap(uint32 _canvasId) external view returns (uint8[]) {
Canvas storage canvas = _getCanvas(_canvasId);
uint8[] memory result = new uint8[](PIXEL_COUNT);
for (uint32 i = 0; i < PIXEL_COUNT; i++) {
result[i] = canvas.pixels[i].color;
}
return result;
}
/**
* @notice Returns how many pixels has been already set.
*/
function getCanvasPaintedPixelsCount(uint32 _canvasId) public view returns (uint32) {
return _getCanvas(_canvasId).paintedPixelsCount;
}
function getPixelCount() external pure returns (uint) {
return PIXEL_COUNT;
}
/**
* @notice Returns amount of created canvases.
*/
function getCanvasCount() public view returns (uint) {
return canvases.length;
}
/**
* @notice Returns true if the canvas has been already finished.
*/
function isCanvasFinished(uint32 _canvasId) public view returns (bool) {
return _isCanvasFinished(_getCanvas(_canvasId));
}
/**
* @notice Returns the author of given pixel.
*/
function getPixelAuthor(uint32 _canvasId, uint32 _pixelIndex) public view validPixelIndex(_pixelIndex) returns (address) {
return _getCanvas(_canvasId).pixels[_pixelIndex].painter;
}
/**
* @notice Returns number of pixels set by given address.
*/
function getPaintedPixelsCountByAddress(address _address, uint32 _canvasId) public view returns (uint32) {
Canvas storage canvas = _getCanvas(_canvasId);
return canvas.addressToCount[_address];
}
function _isCanvasFinished(Canvas canvas) internal pure returns (bool) {
return canvas.paintedPixelsCount == PIXEL_COUNT;
}
function _getCanvas(uint32 _canvasId) internal view returns (Canvas storage) {
require(_canvasId < canvases.length);
return canvases[_canvasId];
}
function _createCanvasInternal(address _bookedFor) private returns (uint canvasId) {
require(canvases.length < MAX_CANVAS_COUNT);
require(activeCanvasCount < MAX_ACTIVE_CANVAS);
uint id = canvases.push(Canvas(STATE_NOT_FINISHED, 0x0, _bookedFor, "", 0, 0, false)) - 1;
emit CanvasCreated(id, _bookedFor);
activeCanvasCount++;
_onCanvasCreated(id);
return id;
}
function _onCanvasCreated(uint /* _canvasId */) internal {}
/**
* Sets the pixel.
*/
function _setPixelInternal(Canvas storage _canvas, uint32 _canvasId, uint32 _index, uint8 _color)
private
notFinished(_canvasId)
validPixelIndex(_index) {
require(_color > 0);
require(_canvas.bookedFor == 0x0 || _canvas.bookedFor == msg.sender);
if (_canvas.pixels[_index].painter != 0x0) {
//it means this pixel has been already set!
revert();
}
_canvas.paintedPixelsCount++;
_canvas.addressToCount[msg.sender]++;
_canvas.pixels[_index] = Pixel(_color, msg.sender);
emit PixelPainted(_canvasId, _index, _color, msg.sender);
}
/**
* Marks canvas as finished if all the pixels has been already set.
* Starts initial bidding session.
*/
function _finishCanvasIfNeeded(Canvas storage _canvas, uint32 _canvasId) private {
if (_isCanvasFinished(_canvas)) {
activeCanvasCount--;
_canvas.state = STATE_INITIAL_BIDDING;
emit CanvasFinished(_canvasId);
}
}
struct Pixel {
uint8 color;
address painter;
}
struct Canvas {
/**
* Map of all pixels.
*/
mapping(uint32 => Pixel) pixels;
uint8 state;
/**
* Owner of canvas. Canvas doesn't have an owner until initial bidding ends.
*/
address owner;
/**
* Booked by this address. It means that only that address can draw on the canvas.
* 0x0 if everybody can paint on the canvas.
*/
address bookedFor;
string name;
/**
* Numbers of pixels set. Canvas will be considered finished when all pixels will be set.
* Technically it means that setPixelsCount == PIXEL_COUNT
*/
uint32 paintedPixelsCount;
mapping(address => uint32) addressToCount;
/**
* Initial bidding finish time.
*/
uint initialBiddingFinishTime;
/**
* If commission from initial bidding has been paid.
*/
bool isCommissionPaid;
/**
* @dev if address has been paid a reward for drawing.
*/
mapping(address => bool) isAddressPaid;
}
}
/**
* @notice Useful methods to manage canvas' state.
*/
contract CanvasState is CanvasFactory {
modifier stateBidding(uint32 _canvasId) {
require(getCanvasState(_canvasId) == STATE_INITIAL_BIDDING);
_;
}
modifier stateOwned(uint32 _canvasId) {
require(getCanvasState(_canvasId) == STATE_OWNED);
_;
}
/**
* Ensures that canvas's saved state is STATE_OWNED.
*
* Because initial bidding is based on current time, we had to find a way to
* trigger saving new canvas state. Every transaction (not a call) that
* requires state owned should use it modifier as a last one.
*
* Thank's to that, we can make sure, that canvas state gets updated.
*/
modifier forceOwned(uint32 _canvasId) {
Canvas storage canvas = _getCanvas(_canvasId);
if (canvas.state != STATE_OWNED) {
canvas.state = STATE_OWNED;
}
_;
}
/**
* @notice Returns current canvas state.
*/
function getCanvasState(uint32 _canvasId) public view returns (uint8) {
Canvas storage canvas = _getCanvas(_canvasId);
if (canvas.state != STATE_INITIAL_BIDDING) {
//if state is set to owned, or not finished
//it means it doesn't depend on current time -
//we don't have to double check
return canvas.state;
}
//state initial bidding - as that state depends on
//current time, we have to double check if initial bidding
//hasn't finish yet
uint finishTime = canvas.initialBiddingFinishTime;
if (finishTime == 0 || finishTime > getTime()) {
return STATE_INITIAL_BIDDING;
} else {
return STATE_OWNED;
}
}
/**
* @notice Returns all canvas' id for a given state.
*/
function getCanvasByState(uint8 _state) external view returns (uint32[]) {
uint size;
if (_state == STATE_NOT_FINISHED) {
size = activeCanvasCount;
} else {
size = getCanvasCount() - activeCanvasCount;
}
uint32[] memory result = new uint32[](size);
uint currentIndex = 0;
for (uint32 i = 0; i < canvases.length; i++) {
if (getCanvasState(i) == _state) {
result[currentIndex] = i;
currentIndex++;
}
}
return _slice(result, 0, currentIndex);
}
/**
* Sets canvas name. Only for the owner of the canvas. Name can be an empty
* string which is the same as lack of the name.
*/
function setCanvasName(uint32 _canvasId, string _name) external
stateOwned(_canvasId)
forceOwned(_canvasId)
{
bytes memory _strBytes = bytes(_name);
require(_strBytes.length <= MAX_CANVAS_NAME_LENGTH);
Canvas storage _canvas = _getCanvas(_canvasId);
require(msg.sender == _canvas.owner);
_canvas.name = _name;
emit CanvasNameSet(_canvasId, _name);
}
/**
* @dev Slices array from start (inclusive) to end (exclusive).
* Doesn't modify input array.
*/
function _slice(uint32[] memory _array, uint _start, uint _end) internal pure returns (uint32[]) {
require(_start <= _end);
if (_start == 0 && _end == _array.length) {
return _array;
}
uint size = _end - _start;
uint32[] memory sliced = new uint32[](size);
for (uint i = 0; i < size; i++) {
sliced[i] = _array[i + _start];
}
return sliced;
}
}
/**
* @notice Keeps track of all rewards and commissions.
* Commission - fee that we charge for using CryptoCanvas.
* Reward - painters cut.
*/
contract RewardableCanvas is CanvasState {
/**
* As it's hard to operate on floating numbers, each fee will be calculated like this:
* PRICE * COMMISSION / COMMISSION_DIVIDER. It's impossible to keep float number here.
*
* ufixed COMMISSION = 0.039; may seem useful, but it's not possible to multiply ufixed * uint.
*/
uint public constant COMMISSION = 39;
uint public constant TRADE_REWARD = 61;
uint public constant PERCENT_DIVIDER = 1000;
event RewardAddedToWithdrawals(uint32 indexed canvasId, address indexed toAddress, uint amount);
event CommissionAddedToWithdrawals(uint32 indexed canvasId, uint amount);
event FeesUpdated(uint32 indexed canvasId, uint totalCommissions, uint totalReward);
mapping(uint => FeeHistory) private canvasToFeeHistory;
/**
* @notice Adds all unpaid commission to the owner's pending withdrawals.
* Ethers to withdraw has to be greater that 0, otherwise transaction
* will be rejected.
* Can be called only by the owner.
*/
function addCommissionToPendingWithdrawals(uint32 _canvasId)
public
onlyOwner
stateOwned(_canvasId)
forceOwned(_canvasId) {
FeeHistory storage _history = _getFeeHistory(_canvasId);
uint _toWithdraw = calculateCommissionToWithdraw(_canvasId);
uint _lastIndex = _history.commissionCumulative.length - 1;
require(_toWithdraw > 0);
_history.paidCommissionIndex = _lastIndex;
addPendingWithdrawal(owner, _toWithdraw);
emit CommissionAddedToWithdrawals(_canvasId, _toWithdraw);
}
/**
* @notice Adds all unpaid rewards of the caller to his pending withdrawals.
* Ethers to withdraw has to be greater that 0, otherwise transaction
* will be rejected.
*/
function addRewardToPendingWithdrawals(uint32 _canvasId)
public
stateOwned(_canvasId)
forceOwned(_canvasId) {
FeeHistory storage _history = _getFeeHistory(_canvasId);
uint _toWithdraw;
(_toWithdraw,) = calculateRewardToWithdraw(_canvasId, msg.sender);
uint _lastIndex = _history.rewardsCumulative.length - 1;
require(_toWithdraw > 0);
_history.addressToPaidRewardIndex[msg.sender] = _lastIndex;
addPendingWithdrawal(msg.sender, _toWithdraw);
emit RewardAddedToWithdrawals(_canvasId, msg.sender, _toWithdraw);
}
/**
* @notice Calculates how much of commission there is to be paid.
*/
function calculateCommissionToWithdraw(uint32 _canvasId)
public
view
stateOwned(_canvasId)
returns (uint)
{
FeeHistory storage _history = _getFeeHistory(_canvasId);
uint _lastIndex = _history.commissionCumulative.length - 1;
uint _lastPaidIndex = _history.paidCommissionIndex;
if (_lastIndex < 0) {
//means that FeeHistory hasn't been created yet
return 0;
}
uint _commissionSum = _history.commissionCumulative[_lastIndex];
uint _lastWithdrawn = _history.commissionCumulative[_lastPaidIndex];
uint _toWithdraw = _commissionSum - _lastWithdrawn;
require(_toWithdraw <= _commissionSum);
return _toWithdraw;
}
/**
* @notice Calculates unpaid rewards of a given address. Returns amount to withdraw
* and amount of pixels owned.
*/
function calculateRewardToWithdraw(uint32 _canvasId, address _address)
public
view
stateOwned(_canvasId)
returns (
uint reward,
uint pixelsOwned
)
{
FeeHistory storage _history = _getFeeHistory(_canvasId);
uint _lastIndex = _history.rewardsCumulative.length - 1;
uint _lastPaidIndex = _history.addressToPaidRewardIndex[_address];
uint _pixelsOwned = getPaintedPixelsCountByAddress(_address, _canvasId);
if (_lastIndex < 0) {
//means that FeeHistory hasn't been created yet
return (0, _pixelsOwned);
}
uint _rewardsSum = _history.rewardsCumulative[_lastIndex];
uint _lastWithdrawn = _history.rewardsCumulative[_lastPaidIndex];
// Our data structure guarantees that _commissionSum is greater or equal to _lastWithdrawn
uint _toWithdraw = ((_rewardsSum - _lastWithdrawn) / PIXEL_COUNT) * _pixelsOwned;
return (_toWithdraw, _pixelsOwned);
}
/**
* @notice Returns total amount of commission charged for a given canvas.
* It is not a commission to be withdrawn!
*/
function getTotalCommission(uint32 _canvasId) external view returns (uint) {
require(_canvasId < canvases.length);
FeeHistory storage _history = canvasToFeeHistory[_canvasId];
uint _lastIndex = _history.commissionCumulative.length - 1;
if (_lastIndex < 0) {
//means that FeeHistory hasn't been created yet
return 0;
}
return _history.commissionCumulative[_lastIndex];
}
/**
* @notice Returns total amount of commission that has been already
* paid (added to pending withdrawals).
*/
function getCommissionWithdrawn(uint32 _canvasId) external view returns (uint) {
require(_canvasId < canvases.length);
FeeHistory storage _history = canvasToFeeHistory[_canvasId];
uint _index = _history.paidCommissionIndex;
return _history.commissionCumulative[_index];
}
/**
* @notice Returns all rewards charged for the given canvas.
*/
function getTotalRewards(uint32 _canvasId) external view returns (uint) {
require(_canvasId < canvases.length);
FeeHistory storage _history = canvasToFeeHistory[_canvasId];
uint _lastIndex = _history.rewardsCumulative.length - 1;
if (_lastIndex < 0) {
//means that FeeHistory hasn't been created yet
return 0;
}
return _history.rewardsCumulative[_lastIndex];
}
/**
* @notice Returns total amount of rewards that has been already
* paid (added to pending withdrawals) by a given address.
*/
function getRewardsWithdrawn(uint32 _canvasId, address _address) external view returns (uint) {
require(_canvasId < canvases.length);
FeeHistory storage _history = canvasToFeeHistory[_canvasId];
uint _index = _history.addressToPaidRewardIndex[_address];
uint _pixelsOwned = getPaintedPixelsCountByAddress(_address, _canvasId);
if (_history.rewardsCumulative.length == 0 || _index == 0) {
return 0;
}
return (_history.rewardsCumulative[_index] / PIXEL_COUNT) * _pixelsOwned;
}
/**
* @notice Calculates how the initial bidding money will be split.
*
* @return Commission and sum of all painter rewards.
*/
function splitBid(uint _amount) public pure returns (
uint commission,
uint paintersRewards
){
uint _rewardPerPixel = ((_amount - _calculatePercent(_amount, COMMISSION))) / PIXEL_COUNT;
// Rewards is divisible by PIXEL_COUNT
uint _rewards = _rewardPerPixel * PIXEL_COUNT;
return (_amount - _rewards, _rewards);
}
/**
* @notice Calculates how the money from selling canvas will be split.
*
* @return Commission, sum of painters' rewards and a seller's profit.
*/
function splitTrade(uint _amount) public pure returns (
uint commission,
uint paintersRewards,
uint sellerProfit
){
uint _commission = _calculatePercent(_amount, COMMISSION);
// We make sure that painters reward is divisible by PIXEL_COUNT.
// It is important to split reward across all the painters equally.
uint _rewardPerPixel = _calculatePercent(_amount, TRADE_REWARD) / PIXEL_COUNT;
uint _paintersReward = _rewardPerPixel * PIXEL_COUNT;
uint _sellerProfit = _amount - _commission - _paintersReward;
//check for the underflow
require(_sellerProfit < _amount);
return (_commission, _paintersReward, _sellerProfit);
}
/**
* @notice Adds a bid to fee history. Doesn't perform any checks if the bid is valid!
* @return Returns how the bid was split. Same value as _splitBid function.
*/
function _registerBid(uint32 _canvasId, uint _amount) internal stateBidding(_canvasId) returns (
uint commission,
uint paintersRewards
){
uint _commission;
uint _rewards;
(_commission, _rewards) = splitBid(_amount);
FeeHistory storage _history = _getFeeHistory(_canvasId);
// We have to save the difference between new bid and a previous one.
// Because we save data as cumulative sum, it's enough to save
// only the new value.
_history.commissionCumulative.push(_commission);
_history.rewardsCumulative.push(_rewards);
return (_commission, _rewards);
}
/**
* @notice Adds a bid to fee history. Doesn't perform any checks if the bid is valid!
* @return Returns how the trade ethers were split. Same value as splitTrade function.
*/
function _registerTrade(uint32 _canvasId, uint _amount)
internal
stateOwned(_canvasId)
forceOwned(_canvasId)
returns (
uint commission,
uint paintersRewards,
uint sellerProfit
){
uint _commission;
uint _rewards;
uint _sellerProfit;
(_commission, _rewards, _sellerProfit) = splitTrade(_amount);
FeeHistory storage _history = _getFeeHistory(_canvasId);
_pushCumulative(_history.commissionCumulative, _commission);
_pushCumulative(_history.rewardsCumulative, _rewards);
return (_commission, _rewards, _sellerProfit);
}
function _onCanvasCreated(uint _canvasId) internal {
//we create a fee entrance on the moment canvas is created
canvasToFeeHistory[_canvasId] = FeeHistory(new uint[](1), new uint[](1), 0);
}
/**
* @notice Gets a fee history of a canvas.
*/
function _getFeeHistory(uint32 _canvasId) private view returns (FeeHistory storage) {
require(_canvasId < canvases.length);
//fee history entry is created in onCanvasCreated() method.
FeeHistory storage _history = canvasToFeeHistory[_canvasId];
return _history;
}
function _pushCumulative(uint[] storage _array, uint _value) private returns (uint) {
uint _lastValue = _array[_array.length - 1];
uint _newValue = _lastValue + _value;
//overflow protection
require(_newValue >= _lastValue);
return _array.push(_newValue);
}
/**
* @param _percent - percent value mapped to scale [0-1000]
*/
function _calculatePercent(uint _amount, uint _percent) private pure returns (uint) {
return (_amount * _percent) / PERCENT_DIVIDER;
}
struct FeeHistory {
/**
* @notice Cumulative sum of all charged commissions.
*/
uint[] commissionCumulative;
/**
* @notice Cumulative sum of all charged rewards.
*/
uint[] rewardsCumulative;
/**
* Index of last paid commission (from commissionCumulative array)
*/
uint paidCommissionIndex;
/**
* Mapping showing what rewards has been already paid.
*/
mapping(address => uint) addressToPaidRewardIndex;
}
}
/**
* @dev This contract takes care of initial bidding.
*/
contract BiddableCanvas is RewardableCanvas {
uint public constant BIDDING_DURATION = 48 hours;
mapping(uint32 => Bid) bids;
mapping(address => uint32) addressToCount;
uint public minimumBidAmount = 0.1 ether;
event BidPosted(uint32 indexed canvasId, address indexed bidder, uint amount, uint finishTime);
/**
* Places bid for canvas that is in the state STATE_INITIAL_BIDDING.
* If somebody is outbid his pending withdrawals will be to topped up.
*/
function makeBid(uint32 _canvasId) external payable stateBidding(_canvasId) {
Canvas storage canvas = _getCanvas(_canvasId);
Bid storage oldBid = bids[_canvasId];
if (msg.value < minimumBidAmount || msg.value <= oldBid.amount) {
revert();
}
if (oldBid.bidder != 0x0 && oldBid.amount > 0) {
//return old bidder his money
addPendingWithdrawal(oldBid.bidder, oldBid.amount);
}
uint finishTime = canvas.initialBiddingFinishTime;
if (finishTime == 0) {
canvas.initialBiddingFinishTime = getTime() + BIDDING_DURATION;
}
bids[_canvasId] = Bid(msg.sender, msg.value);
if (canvas.owner != 0x0) {
addressToCount[canvas.owner]--;
}
canvas.owner = msg.sender;
addressToCount[msg.sender]++;
_registerBid(_canvasId, msg.value);
emit BidPosted(_canvasId, msg.sender, msg.value, canvas.initialBiddingFinishTime);
}
/**
* @notice Returns last bid for canvas. If the initial bidding has been
* already finished that will be winning offer.
*/
function getLastBidForCanvas(uint32 _canvasId) external view returns (
uint32 canvasId,
address bidder,
uint amount,
uint finishTime
) {
Bid storage bid = bids[_canvasId];
Canvas storage canvas = _getCanvas(_canvasId);
return (_canvasId, bid.bidder, bid.amount, canvas.initialBiddingFinishTime);
}
/**
* @notice Returns number of canvases owned by the given address.
*/
function balanceOf(address _owner) external view returns (uint) {
return addressToCount[_owner];
}
/**
* @notice Only for the owner of the contract. Sets minimum bid amount.
*/
function setMinimumBidAmount(uint _amount) external onlyOwner {
minimumBidAmount = _amount;
}
struct Bid {
address bidder;
uint amount;
}
}
/**
* @dev This contract takes trading our artworks. Trading can happen
* if artwork has been initially bought.
*/
contract CanvasMarket is BiddableCanvas {
mapping(uint32 => SellOffer) canvasForSale;
mapping(uint32 => BuyOffer) buyOffers;
event CanvasOfferedForSale(uint32 indexed canvasId, uint minPrice, address indexed from, address indexed to);
event SellOfferCancelled(uint32 indexed canvasId, uint minPrice, address indexed from, address indexed to);
event CanvasSold(uint32 indexed canvasId, uint amount, address indexed from, address indexed to);
event BuyOfferMade(uint32 indexed canvasId, address indexed buyer, uint amount);
event BuyOfferCancelled(uint32 indexed canvasId, address indexed buyer, uint amount);
struct SellOffer {
bool isForSale;
address seller;
uint minPrice;
address onlySellTo; // specify to sell only to a specific address
}
struct BuyOffer {
bool hasOffer;
address buyer;
uint amount;
}
/**
* @notice Buy artwork. Artwork has to be put on sale. If buyer has bid before for
* that artwork, that bid will be canceled.
*/
function acceptSellOffer(uint32 _canvasId)
external
payable
stateOwned(_canvasId)
forceOwned(_canvasId) {
Canvas storage canvas = _getCanvas(_canvasId);
SellOffer memory sellOffer = canvasForSale[_canvasId];
require(msg.sender != canvas.owner);
//don't sell for the owner
require(sellOffer.isForSale);
require(msg.value >= sellOffer.minPrice);
require(sellOffer.seller == canvas.owner);
//seller is no longer owner
require(sellOffer.onlySellTo == 0x0 || sellOffer.onlySellTo == msg.sender);
//protect from selling to unintended address
uint toTransfer;
(, ,toTransfer) = _registerTrade(_canvasId, msg.value);
addPendingWithdrawal(sellOffer.seller, toTransfer);
addressToCount[canvas.owner]--;
addressToCount[msg.sender]++;
canvas.owner = msg.sender;
_cancelSellOfferInternal(_canvasId, false);
emit CanvasSold(_canvasId, msg.value, sellOffer.seller, msg.sender);
//If the buyer have placed buy offer, refund it
BuyOffer memory offer = buyOffers[_canvasId];
if (offer.buyer == msg.sender) {
buyOffers[_canvasId] = BuyOffer(false, 0x0, 0);
if (offer.amount > 0) {
//refund offer
addPendingWithdrawal(offer.buyer, offer.amount);
}
}
}
/**
* @notice Offer canvas for sale for a minimal price.
* Anybody can buy it for an amount grater or equal to min price.
*/
function offerCanvasForSale(uint32 _canvasId, uint _minPrice) external {
_offerCanvasForSaleInternal(_canvasId, _minPrice, 0x0);
}
/**
* @notice Offer canvas for sale to a given address. Only that address
* is allowed to buy canvas for an amount grater or equal
* to minimal price.
*/
function offerCanvasForSaleToAddress(uint32 _canvasId, uint _minPrice, address _receiver) external {
_offerCanvasForSaleInternal(_canvasId, _minPrice, _receiver);
}
/**
* @notice Cancels previously made sell offer. Caller has to be an owner
* of the canvas. Function will fail if there is no sell offer
* for the canvas.
*/
function cancelSellOffer(uint32 _canvasId) external {
_cancelSellOfferInternal(_canvasId, true);
}
/**
* @notice Places buy offer for the canvas. It cannot be called by the owner of the canvas.
* New offer has to be bigger than existing offer. Returns ethers to the previous
* bidder, if any.
*/
function makeBuyOffer(uint32 _canvasId) external payable stateOwned(_canvasId) forceOwned(_canvasId) {
Canvas storage canvas = _getCanvas(_canvasId);
BuyOffer storage existing = buyOffers[_canvasId];
require(canvas.owner != msg.sender);
require(canvas.owner != 0x0);
require(msg.value > existing.amount);
if (existing.amount > 0) {
//refund previous buy offer.
addPendingWithdrawal(existing.buyer, existing.amount);
}
buyOffers[_canvasId] = BuyOffer(true, msg.sender, msg.value);
emit BuyOfferMade(_canvasId, msg.sender, msg.value);
}
/**
* @notice Cancels previously made buy offer. Caller has to be an author
* of the offer.
*/
function cancelBuyOffer(uint32 _canvasId) external stateOwned(_canvasId) forceOwned(_canvasId) {
BuyOffer memory offer = buyOffers[_canvasId];
require(offer.buyer == msg.sender);
buyOffers[_canvasId] = BuyOffer(false, 0x0, 0);
if (offer.amount > 0) {
//refund offer
addPendingWithdrawal(offer.buyer, offer.amount);
}
emit BuyOfferCancelled(_canvasId, offer.buyer, offer.amount);
}
/**
* @notice Accepts buy offer for the canvas. Caller has to be the owner
* of the canvas. You can specify minimal price, which is the
* protection against accidental calls.
*/
function acceptBuyOffer(uint32 _canvasId, uint _minPrice) external stateOwned(_canvasId) forceOwned(_canvasId) {
Canvas storage canvas = _getCanvas(_canvasId);
require(canvas.owner == msg.sender);
BuyOffer memory offer = buyOffers[_canvasId];
require(offer.hasOffer);
require(offer.amount > 0);
require(offer.buyer != 0x0);
require(offer.amount >= _minPrice);
uint toTransfer;
(, ,toTransfer) = _registerTrade(_canvasId, offer.amount);
addressToCount[canvas.owner]--;
addressToCount[offer.buyer]++;
canvas.owner = offer.buyer;
addPendingWithdrawal(msg.sender, toTransfer);
buyOffers[_canvasId] = BuyOffer(false, 0x0, 0);
canvasForSale[_canvasId] = SellOffer(false, 0x0, 0, 0x0);
emit CanvasSold(_canvasId, offer.amount, msg.sender, offer.buyer);
}
/**
* @notice Returns current buy offer for the canvas.
*/
function getCurrentBuyOffer(uint32 _canvasId)
external
view
returns (bool hasOffer, address buyer, uint amount) {
BuyOffer storage offer = buyOffers[_canvasId];
return (offer.hasOffer, offer.buyer, offer.amount);
}
/**
* @notice Returns current sell offer for the canvas.
*/
function getCurrentSellOffer(uint32 _canvasId)
external
view
returns (bool isForSale, address seller, uint minPrice, address onlySellTo) {
SellOffer storage offer = canvasForSale[_canvasId];
return (offer.isForSale, offer.seller, offer.minPrice, offer.onlySellTo);
}
function _offerCanvasForSaleInternal(uint32 _canvasId, uint _minPrice, address _receiver)
private
stateOwned(_canvasId)
forceOwned(_canvasId) {
Canvas storage canvas = _getCanvas(_canvasId);
require(canvas.owner == msg.sender);
require(_receiver != canvas.owner);
canvasForSale[_canvasId] = SellOffer(true, msg.sender, _minPrice, _receiver);
emit CanvasOfferedForSale(_canvasId, _minPrice, msg.sender, _receiver);
}
function _cancelSellOfferInternal(uint32 _canvasId, bool emitEvent)
private
stateOwned(_canvasId)
forceOwned(_canvasId) {
Canvas storage canvas = _getCanvas(_canvasId);
SellOffer memory oldOffer = canvasForSale[_canvasId];
require(canvas.owner == msg.sender);
require(oldOffer.isForSale);
//don't allow to cancel if there is no offer
canvasForSale[_canvasId] = SellOffer(false, msg.sender, 0, 0x0);
if (emitEvent) {
emit SellOfferCancelled(_canvasId, oldOffer.minPrice, oldOffer.seller, oldOffer.onlySellTo);
}
}
}
contract CryptoArt is CanvasMarket {
function getCanvasInfo(uint32 _canvasId) external view returns (
uint32 id,
string name,
uint32 paintedPixels,
uint8 canvasState,
uint initialBiddingFinishTime,
address owner,
address bookedFor
) {
Canvas storage canvas = _getCanvas(_canvasId);
return (_canvasId, canvas.name, canvas.paintedPixelsCount, getCanvasState(_canvasId),
canvas.initialBiddingFinishTime, canvas.owner, canvas.bookedFor);
}
function getCanvasByOwner(address _owner) external view returns (uint32[]) {
uint32[] memory result = new uint32[](canvases.length);
uint currentIndex = 0;
for (uint32 i = 0; i < canvases.length; i++) {
if (getCanvasState(i) == STATE_OWNED) {
Canvas storage canvas = _getCanvas(i);
if (canvas.owner == _owner) {
result[currentIndex] = i;
currentIndex++;
}
}
}
return _slice(result, 0, currentIndex);
}
/**
* @notice Returns array of canvas's ids. Returned canvases have sell offer.
* If includePrivateOffers is true, includes offers that are targeted
* only to one specified address.
*/
function getCanvasesWithSellOffer(bool includePrivateOffers) external view returns (uint32[]) {
uint32[] memory result = new uint32[](canvases.length);
uint currentIndex = 0;
for (uint32 i = 0; i < canvases.length; i++) {
SellOffer storage offer = canvasForSale[i];
if (offer.isForSale && (includePrivateOffers || offer.onlySellTo == 0x0)) {
result[currentIndex] = i;
currentIndex++;
}
}
return _slice(result, 0, currentIndex);
}
/**
* @notice Returns array of all the owners of all of pixels. If some pixel hasn't
* been painted yet, 0x0 address will be returned.
*/
function getCanvasPainters(uint32 _canvasId) external view returns (address[]) {
Canvas storage canvas = _getCanvas(_canvasId);
address[] memory result = new address[](PIXEL_COUNT);
for (uint32 i = 0; i < PIXEL_COUNT; i++) {
result[i] = canvas.pixels[i].painter;
}
return result;
}
} | Adds a bid to fee history. Doesn't perform any checks if the bid is valid! return Returns how the bid was split. Same value as _splitBid function./ We have to save the difference between new bid and a previous one. Because we save data as cumulative sum, it's enough to save only the new value. | function _registerBid(uint32 _canvasId, uint _amount) internal stateBidding(_canvasId) returns (
uint commission,
uint paintersRewards
){
uint _commission;
uint _rewards;
(_commission, _rewards) = splitBid(_amount);
FeeHistory storage _history = _getFeeHistory(_canvasId);
_history.commissionCumulative.push(_commission);
_history.rewardsCumulative.push(_rewards);
return (_commission, _rewards);
}
| 5,907,395 |
./partial_match/56/0x098cA7D558F5E47c2EF267033f877b71ff3bf7Dc/sources/AnimalFactory.sol | The structure defining a single animal | {
struct AnimalProperties
{
uint id;
string name;
string desc;
string attributes;
bool upForSale;
uint priceForSale;
bool upForMating;
bool eggPhase;
uint priceForMating;
bool isBornByMating;
uint parentId1;
uint parentId2;
uint birthdate;
uint assetsId;
uint generationId;
uint cuteVotes;
uint gameVotes;
}
using SafeMath for uint256;
uint public priceForBuyingAssets = 0.25 ether;
uint public priceForSaleAdvertisement = 0.025 ether;
uint public priceForSuccessfulSale = 0.05 ether;
uint public ownerPerThousandShareForBuying = 5;
uint[] eggPhaseAnimalIds;
uint[] animalIdsWithPendingAssetss;
ERC721Interface public token;
uint uniqueAnimalId=0;
mapping(uint=>AnimalProperties) animalAgainstId;
mapping(uint=>uint[]) childrenIdAgainstAnimalId;
uint[] upForMatingList;
uint[] upForSaleList;
address[] memberAddresses;
AnimalProperties animalObject;
uint public totalAnimalsMax = 10000;
uint256 public totalFreeAnimalsMax=1500;
uint public freeAnimalsLimit = 1;
bool public isContractPaused;
bool public isMintingPaused;
bool public isMatingPaused;
uint256 public weiPerAnimal = 0.15 ether;
uint public priceForMateAdvertisement = 0.025 ether;
uint public ownerPerThousandShareForMating = 2;
uint256 public weiRaised;
uint256 public totalAnimalsCreated=0;
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;
isMintingPaused = false;
isMatingPaused = true;
priceForMateAdvertisement = 0.025 ether;
priceForSaleAdvertisement = 0.025 ether;
priceForBuyingAssets = 0.25 ether;
token = ERC721Interface(_tokenAddress);
}
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 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 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 assetsid, uint generationid )
{
return(
animalAgainstId[aid].upForSale,
animalAgainstId[aid].upForMating,
animalAgainstId[aid].eggPhase,
animalAgainstId[aid].isBornByMating,
animalAgainstId[aid].birthdate,
animalAgainstId[aid].assetsId,
animalAgainstId[aid].generationId
);
}
function getOwnerByAnimalId(uint aid) public constant
returns (address)
{
return token.ownerOf(aid);
}
function getAllAnimalsByAddress(address ad) public constant returns (uint[] listAnimals)
{
require (!isContractPaused);
return token.getAnimalIdAgainstAddress(ad);
}
function claimFreeAnimalFromAnimalFactory( string animalName, string animalDesc) public
{
require(msg.sender != 0x0);
require (!isContractPaused);
uint gId=0;
if (msg.sender!=owner)
{
require(token.getTotalTokensAgainstAddress(msg.sender)<freeAnimalsLimit);
gId=1;
}
if (totalAnimalsCreated >= totalFreeAnimalsMax) throw;
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
attributes:"",
upForSale: false,
eggPhase: false,
priceForSale:0,
upForMating: false,
priceForMating:0,
isBornByMating: false,
parentId1:0,
parentId2:0,
birthdate:now,
assetsId:0,
generationId:gId,
cuteVotes:0,
gameVotes:0
});
token.sendToken(msg.sender, uniqueAnimalId,animalName);
totalAnimalsCreated++;
}
function claimFreeAnimalFromAnimalFactory( string animalName, string animalDesc) public
{
require(msg.sender != 0x0);
require (!isContractPaused);
uint gId=0;
if (msg.sender!=owner)
{
require(token.getTotalTokensAgainstAddress(msg.sender)<freeAnimalsLimit);
gId=1;
}
if (totalAnimalsCreated >= totalFreeAnimalsMax) throw;
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
attributes:"",
upForSale: false,
eggPhase: false,
priceForSale:0,
upForMating: false,
priceForMating:0,
isBornByMating: false,
parentId1:0,
parentId2:0,
birthdate:now,
assetsId:0,
generationId:gId,
cuteVotes:0,
gameVotes:0
});
token.sendToken(msg.sender, uniqueAnimalId,animalName);
totalAnimalsCreated++;
}
uniqueAnimalId++;
function claimFreeAnimalFromAnimalFactory( string animalName, string animalDesc) public
{
require(msg.sender != 0x0);
require (!isContractPaused);
uint gId=0;
if (msg.sender!=owner)
{
require(token.getTotalTokensAgainstAddress(msg.sender)<freeAnimalsLimit);
gId=1;
}
if (totalAnimalsCreated >= totalFreeAnimalsMax) throw;
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
attributes:"",
upForSale: false,
eggPhase: false,
priceForSale:0,
upForMating: false,
priceForMating:0,
isBornByMating: false,
parentId1:0,
parentId2:0,
birthdate:now,
assetsId:0,
generationId:gId,
cuteVotes:0,
gameVotes:0
});
token.sendToken(msg.sender, uniqueAnimalId,animalName);
totalAnimalsCreated++;
}
animalAgainstId[uniqueAnimalId]=animalObject;
function MintAnimalsFromAnimalFactory(string animalName, string animalDesc) public payable
{
require (!isContractPaused);
require (!isMintingPaused);
require(validPurchase());
require(msg.sender != 0x0);
if (msg.sender!=owner)
{
require(msg.value>=weiPerAnimal);
}
require(msg.value>=weiPerAnimal);
if (totalAnimalsCreated >= totalAnimalsMax) throw;
uint gId=0;
{
gId=1;
}
uint256 weiAmount = msg.value;
uniqueAnimalId++;
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
attributes:"",
upForSale: false,
priceForSale:0,
upForMating: false,
eggPhase: false,
priceForMating:0,
isBornByMating:false,
parentId1:0,
parentId2:0,
birthdate:now,
assetsId:0,
generationId:gId,
cuteVotes:0,
gameVotes:0
});
emit AnimalsPurchased(msg.sender, owner, weiAmount, tokens);
totalAnimalsCreated++;
}
function MintAnimalsFromAnimalFactory(string animalName, string animalDesc) public payable
{
require (!isContractPaused);
require (!isMintingPaused);
require(validPurchase());
require(msg.sender != 0x0);
if (msg.sender!=owner)
{
require(msg.value>=weiPerAnimal);
}
require(msg.value>=weiPerAnimal);
if (totalAnimalsCreated >= totalAnimalsMax) throw;
uint gId=0;
{
gId=1;
}
uint256 weiAmount = msg.value;
uniqueAnimalId++;
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
attributes:"",
upForSale: false,
priceForSale:0,
upForMating: false,
eggPhase: false,
priceForMating:0,
isBornByMating:false,
parentId1:0,
parentId2:0,
birthdate:now,
assetsId:0,
generationId:gId,
cuteVotes:0,
gameVotes:0
});
emit AnimalsPurchased(msg.sender, owner, weiAmount, tokens);
totalAnimalsCreated++;
}
if (msg.sender!=owner)
function MintAnimalsFromAnimalFactory(string animalName, string animalDesc) public payable
{
require (!isContractPaused);
require (!isMintingPaused);
require(validPurchase());
require(msg.sender != 0x0);
if (msg.sender!=owner)
{
require(msg.value>=weiPerAnimal);
}
require(msg.value>=weiPerAnimal);
if (totalAnimalsCreated >= totalAnimalsMax) throw;
uint gId=0;
{
gId=1;
}
uint256 weiAmount = msg.value;
uniqueAnimalId++;
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
attributes:"",
upForSale: false,
priceForSale:0,
upForMating: false,
eggPhase: false,
priceForMating:0,
isBornByMating:false,
parentId1:0,
parentId2:0,
birthdate:now,
assetsId:0,
generationId:gId,
cuteVotes:0,
gameVotes:0
});
emit AnimalsPurchased(msg.sender, owner, weiAmount, tokens);
totalAnimalsCreated++;
}
uint256 tokens = weiAmount.div(weiPerAnimal);
weiRaised = weiRaised.add(weiAmount);
function MintAnimalsFromAnimalFactory(string animalName, string animalDesc) public payable
{
require (!isContractPaused);
require (!isMintingPaused);
require(validPurchase());
require(msg.sender != 0x0);
if (msg.sender!=owner)
{
require(msg.value>=weiPerAnimal);
}
require(msg.value>=weiPerAnimal);
if (totalAnimalsCreated >= totalAnimalsMax) throw;
uint gId=0;
{
gId=1;
}
uint256 weiAmount = msg.value;
uniqueAnimalId++;
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
attributes:"",
upForSale: false,
priceForSale:0,
upForMating: false,
eggPhase: false,
priceForMating:0,
isBornByMating:false,
parentId1:0,
parentId2:0,
birthdate:now,
assetsId:0,
generationId:gId,
cuteVotes:0,
gameVotes:0
});
emit AnimalsPurchased(msg.sender, owner, weiAmount, tokens);
totalAnimalsCreated++;
}
token.sendToken(msg.sender, uniqueAnimalId,animalName);
animalAgainstId[uniqueAnimalId]=animalObject;
owner.transfer(msg.value);
function buyAnimalsFromUser(uint animalId) public payable
{
require (!isContractPaused);
require(msg.sender != 0x0);
address prevOwner=token.ownerOf(animalId);
require(prevOwner!=msg.sender);
uint price=animalAgainstId[animalId].priceForSale;
uint convertedpricetoEther = msg.value;
uint OwnerPercentage=animalAgainstId[animalId].priceForSale.mul(ownerPerThousandShareForBuying);
OwnerPercentage=OwnerPercentage.div(1000);
uint priceMinusOwnerPercentage = animalAgainstId[animalId].priceForSale.sub(OwnerPercentage);
require(convertedpricetoEther>=price);
token.safeTransferFrom(prevOwner,msg.sender,animalId);
animalAgainstId[animalId].upForSale=false;
animalAgainstId[animalId].priceForSale=0;
for (uint j=0;j<upForSaleList.length;j++)
{
if (upForSaleList[j] == animalId)
delete upForSaleList[j];
}
}
function buyAnimalsFromUser(uint animalId) public payable
{
require (!isContractPaused);
require(msg.sender != 0x0);
address prevOwner=token.ownerOf(animalId);
require(prevOwner!=msg.sender);
uint price=animalAgainstId[animalId].priceForSale;
uint convertedpricetoEther = msg.value;
uint OwnerPercentage=animalAgainstId[animalId].priceForSale.mul(ownerPerThousandShareForBuying);
OwnerPercentage=OwnerPercentage.div(1000);
uint priceMinusOwnerPercentage = animalAgainstId[animalId].priceForSale.sub(OwnerPercentage);
require(convertedpricetoEther>=price);
token.safeTransferFrom(prevOwner,msg.sender,animalId);
animalAgainstId[animalId].upForSale=false;
animalAgainstId[animalId].priceForSale=0;
for (uint j=0;j<upForSaleList.length;j++)
{
if (upForSaleList[j] == animalId)
delete upForSaleList[j];
}
}
prevOwner.transfer(priceMinusOwnerPercentage);
owner.transfer(OwnerPercentage);
function mateAnimal(uint parent1Id, uint parent2Id, string animalName,string animalDesc) public payable
{
require (!isContractPaused);
require(!isMatingPaused);
require(msg.sender != 0x0);
require (token.ownerOf(parent2Id) == msg.sender);
require(token.ownerOf(parent2Id)!=token.ownerOf(parent1Id));
require(animalAgainstId[parent1Id].upForMating==true);
uint convertedpricetoEther = msg.value;
uint price=animalAgainstId[parent1Id].priceForMating;
uint OwnerPercentage=animalAgainstId[parent1Id].priceForMating.mul(ownerPerThousandShareForMating);
OwnerPercentage=OwnerPercentage.div(1000);
uint priceMinusOwnerPercentage = animalAgainstId[parent1Id].priceForMating.sub(OwnerPercentage);
require(convertedpricetoEther>=price);
uint generationnum = 1;
if(animalAgainstId[parent1Id].generationId >= animalAgainstId[parent2Id].generationId)
{
generationnum = animalAgainstId[parent1Id].generationId+1;
}
else{
generationnum = animalAgainstId[parent2Id].generationId+1;
}
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
attributes:"",
upForSale: false,
priceForSale:0,
upForMating: false,
eggPhase: true,
priceForMating:0,
isBornByMating:true,
parentId1: parent1Id,
parentId2: parent2Id,
birthdate:now,
assetsId:0,
generationId:generationnum,
cuteVotes:0,
gameVotes:0
});
childrenIdAgainstAnimalId[parent2Id].push(uniqueAnimalId);
{
if (upForMatingList[i]==parent1Id)
delete upForMatingList[i];
}
animalAgainstId[parent1Id].priceForMating = 0;
}
function mateAnimal(uint parent1Id, uint parent2Id, string animalName,string animalDesc) public payable
{
require (!isContractPaused);
require(!isMatingPaused);
require(msg.sender != 0x0);
require (token.ownerOf(parent2Id) == msg.sender);
require(token.ownerOf(parent2Id)!=token.ownerOf(parent1Id));
require(animalAgainstId[parent1Id].upForMating==true);
uint convertedpricetoEther = msg.value;
uint price=animalAgainstId[parent1Id].priceForMating;
uint OwnerPercentage=animalAgainstId[parent1Id].priceForMating.mul(ownerPerThousandShareForMating);
OwnerPercentage=OwnerPercentage.div(1000);
uint priceMinusOwnerPercentage = animalAgainstId[parent1Id].priceForMating.sub(OwnerPercentage);
require(convertedpricetoEther>=price);
uint generationnum = 1;
if(animalAgainstId[parent1Id].generationId >= animalAgainstId[parent2Id].generationId)
{
generationnum = animalAgainstId[parent1Id].generationId+1;
}
else{
generationnum = animalAgainstId[parent2Id].generationId+1;
}
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
attributes:"",
upForSale: false,
priceForSale:0,
upForMating: false,
eggPhase: true,
priceForMating:0,
isBornByMating:true,
parentId1: parent1Id,
parentId2: parent2Id,
birthdate:now,
assetsId:0,
generationId:generationnum,
cuteVotes:0,
gameVotes:0
});
childrenIdAgainstAnimalId[parent2Id].push(uniqueAnimalId);
{
if (upForMatingList[i]==parent1Id)
delete upForMatingList[i];
}
animalAgainstId[parent1Id].priceForMating = 0;
}
function mateAnimal(uint parent1Id, uint parent2Id, string animalName,string animalDesc) public payable
{
require (!isContractPaused);
require(!isMatingPaused);
require(msg.sender != 0x0);
require (token.ownerOf(parent2Id) == msg.sender);
require(token.ownerOf(parent2Id)!=token.ownerOf(parent1Id));
require(animalAgainstId[parent1Id].upForMating==true);
uint convertedpricetoEther = msg.value;
uint price=animalAgainstId[parent1Id].priceForMating;
uint OwnerPercentage=animalAgainstId[parent1Id].priceForMating.mul(ownerPerThousandShareForMating);
OwnerPercentage=OwnerPercentage.div(1000);
uint priceMinusOwnerPercentage = animalAgainstId[parent1Id].priceForMating.sub(OwnerPercentage);
require(convertedpricetoEther>=price);
uint generationnum = 1;
if(animalAgainstId[parent1Id].generationId >= animalAgainstId[parent2Id].generationId)
{
generationnum = animalAgainstId[parent1Id].generationId+1;
}
else{
generationnum = animalAgainstId[parent2Id].generationId+1;
}
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
attributes:"",
upForSale: false,
priceForSale:0,
upForMating: false,
eggPhase: true,
priceForMating:0,
isBornByMating:true,
parentId1: parent1Id,
parentId2: parent2Id,
birthdate:now,
assetsId:0,
generationId:generationnum,
cuteVotes:0,
gameVotes:0
});
childrenIdAgainstAnimalId[parent2Id].push(uniqueAnimalId);
{
if (upForMatingList[i]==parent1Id)
delete upForMatingList[i];
}
animalAgainstId[parent1Id].priceForMating = 0;
}
uniqueAnimalId++;
function mateAnimal(uint parent1Id, uint parent2Id, string animalName,string animalDesc) public payable
{
require (!isContractPaused);
require(!isMatingPaused);
require(msg.sender != 0x0);
require (token.ownerOf(parent2Id) == msg.sender);
require(token.ownerOf(parent2Id)!=token.ownerOf(parent1Id));
require(animalAgainstId[parent1Id].upForMating==true);
uint convertedpricetoEther = msg.value;
uint price=animalAgainstId[parent1Id].priceForMating;
uint OwnerPercentage=animalAgainstId[parent1Id].priceForMating.mul(ownerPerThousandShareForMating);
OwnerPercentage=OwnerPercentage.div(1000);
uint priceMinusOwnerPercentage = animalAgainstId[parent1Id].priceForMating.sub(OwnerPercentage);
require(convertedpricetoEther>=price);
uint generationnum = 1;
if(animalAgainstId[parent1Id].generationId >= animalAgainstId[parent2Id].generationId)
{
generationnum = animalAgainstId[parent1Id].generationId+1;
}
else{
generationnum = animalAgainstId[parent2Id].generationId+1;
}
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
attributes:"",
upForSale: false,
priceForSale:0,
upForMating: false,
eggPhase: true,
priceForMating:0,
isBornByMating:true,
parentId1: parent1Id,
parentId2: parent2Id,
birthdate:now,
assetsId:0,
generationId:generationnum,
cuteVotes:0,
gameVotes:0
});
childrenIdAgainstAnimalId[parent2Id].push(uniqueAnimalId);
{
if (upForMatingList[i]==parent1Id)
delete upForMatingList[i];
}
animalAgainstId[parent1Id].priceForMating = 0;
}
token.sendToken(msg.sender,uniqueAnimalId,animalName);
animalAgainstId[uniqueAnimalId]=animalObject;
eggPhaseAnimalIds.push(uniqueAnimalId);
childrenIdAgainstAnimalId[parent1Id].push(uniqueAnimalId);
for (uint i=0;i<upForMatingList.length;i++)
function mateAnimal(uint parent1Id, uint parent2Id, string animalName,string animalDesc) public payable
{
require (!isContractPaused);
require(!isMatingPaused);
require(msg.sender != 0x0);
require (token.ownerOf(parent2Id) == msg.sender);
require(token.ownerOf(parent2Id)!=token.ownerOf(parent1Id));
require(animalAgainstId[parent1Id].upForMating==true);
uint convertedpricetoEther = msg.value;
uint price=animalAgainstId[parent1Id].priceForMating;
uint OwnerPercentage=animalAgainstId[parent1Id].priceForMating.mul(ownerPerThousandShareForMating);
OwnerPercentage=OwnerPercentage.div(1000);
uint priceMinusOwnerPercentage = animalAgainstId[parent1Id].priceForMating.sub(OwnerPercentage);
require(convertedpricetoEther>=price);
uint generationnum = 1;
if(animalAgainstId[parent1Id].generationId >= animalAgainstId[parent2Id].generationId)
{
generationnum = animalAgainstId[parent1Id].generationId+1;
}
else{
generationnum = animalAgainstId[parent2Id].generationId+1;
}
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
attributes:"",
upForSale: false,
priceForSale:0,
upForMating: false,
eggPhase: true,
priceForMating:0,
isBornByMating:true,
parentId1: parent1Id,
parentId2: parent2Id,
birthdate:now,
assetsId:0,
generationId:generationnum,
cuteVotes:0,
gameVotes:0
});
childrenIdAgainstAnimalId[parent2Id].push(uniqueAnimalId);
{
if (upForMatingList[i]==parent1Id)
delete upForMatingList[i];
}
animalAgainstId[parent1Id].priceForMating = 0;
}
animalAgainstId[parent1Id].upForMating = false;
token.ownerOf(parent1Id).transfer(priceMinusOwnerPercentage);
owner.transfer(OwnerPercentage);
function TransferAnimalToAnotherUser(uint animalId,address to) public
{
require (!isContractPaused);
require(msg.sender != 0x0);
require(token.ownerOf(animalId)==msg.sender);
require(animalAgainstId[animalId].upForSale == false);
require(animalAgainstId[animalId].upForMating == false);
token.safeTransferFrom(msg.sender, to, animalId);
}
function voteGame(uint animalId, uint gamepoints)
{
require(msg.sender != 0x0);
animalAgainstId[animalId].gameVotes.add(1);
}
function voteGameMinus(uint animalId, uint gamepoints)
{
require(msg.sender != 0x0);
animalAgainstId[animalId].gameVotes.sub(1);
}
function voteCuteness(uint animalId, uint vote)
{
require(msg.sender != 0x0);
animalAgainstId[animalId].cuteVotes.add(1);
}
function putSaleRequest(uint animalId, uint salePrice) public payable
{
require (!isContractPaused);
uint convertedpricetoEther = salePrice;
if (msg.sender!=owner)
{
require(msg.value>=priceForSaleAdvertisement);
}
animalAgainstId[animalId].priceForSale=convertedpricetoEther;
upForSaleList.push(animalId);
}
function putSaleRequest(uint animalId, uint salePrice) public payable
{
require (!isContractPaused);
uint convertedpricetoEther = salePrice;
if (msg.sender!=owner)
{
require(msg.value>=priceForSaleAdvertisement);
}
animalAgainstId[animalId].priceForSale=convertedpricetoEther;
upForSaleList.push(animalId);
}
require(token.ownerOf(animalId)==msg.sender);
require(animalAgainstId[animalId].eggPhase==false);
require(animalAgainstId[animalId].upForSale==false);
require(animalAgainstId[animalId].upForMating==false);
animalAgainstId[animalId].upForSale=true;
owner.transfer(msg.value);
function withdrawSaleRequest(uint animalId) public
{
require (!isContractPaused);
require(token.ownerOf(animalId)==msg.sender);
require(animalAgainstId[animalId].upForSale==true);
animalAgainstId[animalId].upForSale=false;
animalAgainstId[animalId].priceForSale=0;
for (uint i=0;i<upForSaleList.length;i++)
{
if (upForSaleList[i]==animalId)
delete upForSaleList[i];
}
}
function withdrawSaleRequest(uint animalId) public
{
require (!isContractPaused);
require(token.ownerOf(animalId)==msg.sender);
require(animalAgainstId[animalId].upForSale==true);
animalAgainstId[animalId].upForSale=false;
animalAgainstId[animalId].priceForSale=0;
for (uint i=0;i<upForSaleList.length;i++)
{
if (upForSaleList[i]==animalId)
delete upForSaleList[i];
}
}
function putMatingRequest(uint animalId, uint matePrice) public payable
{
require(!isContractPaused);
require(!isMatingPaused);
if (msg.sender!=owner)
{
require(msg.value>=priceForMateAdvertisement);
}
require(token.ownerOf(animalId)==msg.sender);
animalAgainstId[animalId].upForMating=true;
animalAgainstId[animalId].priceForMating=convertedpricetoEther;
upForMatingList.push(animalId);
}
function putMatingRequest(uint animalId, uint matePrice) public payable
{
require(!isContractPaused);
require(!isMatingPaused);
if (msg.sender!=owner)
{
require(msg.value>=priceForMateAdvertisement);
}
require(token.ownerOf(animalId)==msg.sender);
animalAgainstId[animalId].upForMating=true;
animalAgainstId[animalId].priceForMating=convertedpricetoEther;
upForMatingList.push(animalId);
}
uint convertedpricetoEther = matePrice;
require(animalAgainstId[animalId].eggPhase==false);
require(animalAgainstId[animalId].upForSale==false);
require(animalAgainstId[animalId].upForMating==false);
owner.transfer(msg.value);
function withdrawMatingRequest(uint animalId) public
{
require(!isContractPaused);
require(!isMatingPaused);
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];
}
}
function withdrawMatingRequest(uint animalId) public
{
require(!isContractPaused);
require(!isMatingPaused);
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];
}
}
function validPurchase() internal constant returns (bool)
{
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 showMyAnimalBalance() public view returns (uint256 tokenBalance)
{
tokenBalance = token.balanceOf(msg.sender);
}
function setPriceRate(uint256 newPrice) public onlyOwner returns (bool)
{
weiPerAnimal = newPrice;
}
function setMateAdvertisementRate(uint256 newPrice) public onlyOwner returns (bool)
{
priceForMateAdvertisement = newPrice;
}
function setSaleAdvertisementRate(uint256 newPrice) public onlyOwner returns (bool)
{
priceForSaleAdvertisement = newPrice;
}
function setBuyingAssetsRate(uint256 newPrice) public onlyOwner returns (bool)
{
priceForBuyingAssets = newPrice;
}
function changeMaxMintable(uint limit) public onlyOwner
{
totalAnimalsMax = limit;
}
function changeFreeMaxMintable(uint limit) public onlyOwner
{
totalFreeAnimalsMax = limit;
}
function getAllMatingAnimals() public constant returns (uint[])
{
return upForMatingList;
}
function getAllSaleAnimals() public constant returns (uint[])
{
return upForSaleList;
}
function changeFreeAnimalsLimit(uint limit) public onlyOwner
{
freeAnimalsLimit = limit;
}
function pauseMating(bool isPaused) public onlyOwner
{
isMatingPaused = isPaused;
isMintingPaused = true;
}
function pauseContract(bool isPaused) public onlyOwner
{
isContractPaused = isPaused;
}
function pauseMinting(bool isPaused) public onlyOwner
{
isMintingPaused = isPaused;
}
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 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 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 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 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 getChildrenAgainstAnimalId(uint id) public constant returns (uint[])
{
return childrenIdAgainstAnimalId[id];
}
function getEggPhaseList() public constant returns (uint[])
{
return eggPhaseAnimalIds;
}
function getAnimalIdsWithPendingAssets() public constant returns (uint[])
{
return animalIdsWithPendingAssetss;
}
function buyAssets(uint cId, uint aId) public payable
{
require(msg.value>=priceForBuyingAssets);
require(!isContractPaused);
require(token.ownerOf(aId)==msg.sender);
require(animalAgainstId[aId].assetsId==0);
animalAgainstId[aId].assetsId=cId;
animalIdsWithPendingAssetss.push(aId);
owner.transfer(msg.value);
}
function approvePendingAssets(uint animalId) public
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==msg.sender)
{
for (uint j=0;j<animalIdsWithPendingAssetss.length;j++)
{
if (animalIdsWithPendingAssetss[j]==animalId)
{
delete animalIdsWithPendingAssetss[j];
}
}
}
}
}
function approvePendingAssets(uint animalId) public
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==msg.sender)
{
for (uint j=0;j<animalIdsWithPendingAssetss.length;j++)
{
if (animalIdsWithPendingAssetss[j]==animalId)
{
delete animalIdsWithPendingAssetss[j];
}
}
}
}
}
function approvePendingAssets(uint animalId) public
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==msg.sender)
{
for (uint j=0;j<animalIdsWithPendingAssetss.length;j++)
{
if (animalIdsWithPendingAssetss[j]==animalId)
{
delete animalIdsWithPendingAssetss[j];
}
}
}
}
}
function approvePendingAssets(uint animalId) public
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==msg.sender)
{
for (uint j=0;j<animalIdsWithPendingAssetss.length;j++)
{
if (animalIdsWithPendingAssetss[j]==animalId)
{
delete animalIdsWithPendingAssetss[j];
}
}
}
}
}
function approvePendingAssets(uint animalId) public
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==msg.sender)
{
for (uint j=0;j<animalIdsWithPendingAssetss.length;j++)
{
if (animalIdsWithPendingAssetss[j]==animalId)
{
delete animalIdsWithPendingAssetss[j];
}
}
}
}
}
function addMember(address member) public onlyOwner
{
memberAddresses.push(member);
}
function listMembers() public constant returns (address[])
{
return memberAddresses;
}
function deleteMember(address member) public onlyOwner
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==member)
{
delete memberAddresses[i];
}
}
}
function deleteMember(address member) public onlyOwner
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==member)
{
delete memberAddresses[i];
}
}
}
function deleteMember(address member) public onlyOwner
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==member)
{
delete memberAddresses[i];
}
}
}
function updateAnimal(uint animalId, string name, string desc, string attributes) public
{
require(msg.sender==token.ownerOf(animalId));
animalAgainstId[animalId].name=name;
animalAgainstId[animalId].desc=desc;
animalAgainstId[animalId].attributes=attributes;
token.setAnimalMeta(animalId, name);
}
} | 11,260,549 |
/**
* Source Code first verified at https://etherscan.io
* WorldTrade asset Smart Contract v4.1
*/
pragma solidity ^0.4.16;
/*
* @title Standard Token Contract
*
* ERC20-compliant tokens => https://github.com/ethereum/EIPs/issues/20
* A token is a fungible virtual good that can be traded.
* ERC-20 Tokens comply to the standard described in the Ethereum ERC-20 proposal.
* Basic, standardized Token contract. Defines the functions to check token balances
* send tokens, send tokens on behalf of a 3rd party and the corresponding approval process.
*
*/
contract Token {
// **** BASE FUNCTIONALITY
// @notice For debugging purposes when using solidity online browser
function whoAmI() constant returns (address) {
return msg.sender;
}
// SC owners:
address owner;
function isOwner() returns (bool) {
if (msg.sender == owner) return true;
return false;
}
// **** EVENTS
// @notice A generic error log
event Error(string error);
// **** DATA
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public initialSupply; // Initial and total token supply
uint256 public totalSupply;
// bool allocated = false; // True after defining token parameters and initial mint
// Public variables of the token, all used for display
// HumanStandardToken is a specialisation of ERC20 defining these parameters
string public name;
string public symbol;
uint8 public decimals;
string public standard = 'H0.1';
// **** METHODS
// Get total amount of tokens, totalSupply is a public var actually
// function totalSupply() constant returns (uint256 totalSupply) {}
// Get the account balance of another account with address _owner
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
// Send _amount amount of tokens to address _to
function transfer(address _to, uint256 _amount) returns (bool success) {
if (balances[msg.sender] < _amount) {
Error('transfer: the amount to transfer is higher than your token balance');
return false;
}
balances[msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(msg.sender, _to, _amount);
return true;
}
// Send _amount amount of tokens from address _from to address _to
// The transferFrom method is used for a withdraw workflow, allowing contracts to send
// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
// fees in sub-currencies; the command should fail unless the _from account has
// deliberately authorized the sender of the message via some mechanism
function transferFrom(address _from, address _to, uint256 _amount) returns (bool success) {
if (balances[_from] < _amount) {
Error('transfer: the amount to transfer is higher than the token balance of the source');
return false;
}
if (allowed[_from][msg.sender] < _amount) {
Error('transfer: the amount to transfer is higher than the maximum token transfer allowed by the source');
return false;
}
balances[_from] -= _amount;
balances[_to] += _amount;
allowed[_from][msg.sender] -= _amount;
Transfer(_from, _to, _amount);
return true;
}
// Allow _spender to withdraw from your account, multiple times, up to the _amount amount.
// If this function is called again it overwrites the current allowance with _amount.
function approve(address _spender, uint256 _amount) returns (bool success) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
// Returns the amount which _spender is still allowed to withdraw from _owner
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
// Constructor: set up token properties and owner token balance
function Token() {
// This is the constructor, so owner should be equal to msg.sender, and this method should be called just once
owner = msg.sender;
// make sure owner address is configured
// if(owner == 0x0) throw;
// owner address can call this function
// if (msg.sender != owner ) throw;
// call this function just once
// if (allocated) throw;
initialSupply = 50000000 * 1000000; // 50M tokens, 6 decimals
totalSupply = initialSupply;
name = "WorldTrade";
symbol = "WTE";
decimals = 6;
balances[owner] = totalSupply;
Transfer(this, owner, totalSupply);
// allocated = true;
}
// **** EVENTS
// Triggered when tokens are transferred
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
// Triggered whenever approve(address _spender, uint256 _amount) is called
event Approval(address indexed _owner, address indexed _spender, uint256 _amount);
}
// Interface of issuer contract, just to cast the contract address and make it callable from the asset contract
contract IFIssuers {
// **** DATA
// **** FUNCTIONS
function isIssuer(address _issuer) constant returns (bool);
}
contract Asset is Token {
// **** DATA
/** Asset states
*
* - Released: Once issued the asset stays as released until sent for free to someone specified by issuer
* - ForSale: The asset belongs to a user and is open to be sold
* - Unfungible: The asset cannot be sold, remaining to the user it belongs to.
*/
enum assetStatus { Released, ForSale, Unfungible }
// https://ethereum.stackexchange.com/questions/1807/enums-in-solidity
struct asst {
uint256 assetId;
address assetOwner;
address issuer;
string content; // a JSON object containing the image data of the asset and its title
uint256 sellPrice; // in WorldTrade tokens, how many of them for this asset
assetStatus status; // behaviour (tradability) of the asset depends upon its status
}
mapping (uint256 => asst) assetsById;
uint256 lastAssetId; // Last assetId
address public SCIssuers; // Contract that defines who is an issuer and who is not
uint256 assetFeeIssuer; // Fee percentage for Issuer on every asset sale transaction
uint256 assetFeeWorldTrade; // Fee percentage for WorldTrade on every asset sale transaction
// **** METHODS
// Constructor
function Asset(address _SCIssuers) {
SCIssuers = _SCIssuers;
}
// Queries the asset, knowing the id
function getAssetById(uint256 assetId) constant returns (uint256 _assetId, address _assetOwner, address _issuer, string _content, uint256 _sellPrice, uint256 _status) {
return (assetsById[assetId].assetId, assetsById[assetId].assetOwner, assetsById[assetId].issuer, assetsById[assetId].content, assetsById[assetId].sellPrice, uint256(assetsById[assetId].status));
}
// Seller sends an owned asset to a buyer, providing its allowance matches token price and transfer the tokens from buyer
function sendAssetTo(uint256 assetId, address assetBuyer) returns (bool) {
// assetId must not be zero
if (assetId == 0) {
Error('sendAssetTo: assetId must not be zero');
return false;
}
// Check whether the asset belongs to the seller
if (assetsById[assetId].assetOwner != msg.sender) {
Error('sendAssetTo: the asset does not belong to you, the seller');
return false;
}
if (assetsById[assetId].sellPrice > 0) { // for non-null token paid transactions
// Check whether there is balance enough from the buyer to get its tokens
if (balances[assetBuyer] < assetsById[assetId].sellPrice) {
Error('sendAssetTo: there is not enough balance from the buyer to get its tokens');
return false;
}
// Check whether there is allowance enough from the buyer to get its tokens
if (allowance(assetBuyer, msg.sender) < assetsById[assetId].sellPrice) {
Error('sendAssetTo: there is not enough allowance from the buyer to get its tokens');
return false;
}
// Get the buyer tokens
if (!transferFrom(assetBuyer, msg.sender, assetsById[assetId].sellPrice)) {
Error('sendAssetTo: transferFrom failed'); // This shouldn't happen ever, but just in case...
return false;
}
}
// Set the asset status to Unfungible
assetsById[assetId].status = assetStatus.Unfungible;
// Transfer the asset to the buyer
assetsById[assetId].assetOwner = assetBuyer;
// Event log
SendAssetTo(assetId, assetBuyer);
return true;
}
// Buyer gets an asset providing it is in ForSale status, and pays the corresponding tokens to the seller/owner. amount must match assetPrice to have a deal.
function buyAsset(uint256 assetId, uint256 amount) returns (bool) {
// assetId must not be zero
if (assetId == 0) {
Error('buyAsset: assetId must not be zero');
return false;
}
// Check whether the asset is in ForSale status
if (assetsById[assetId].status != assetStatus.ForSale) {
Error('buyAsset: the asset is not for sale');
return false;
}
// Check whether the asset price is the same as amount
if (assetsById[assetId].sellPrice != amount) {
Error('buyAsset: the asset price does not match the specified amount');
return false;
}
if (assetsById[assetId].sellPrice > 0) { // for non-null token paid transactions
// Check whether there is balance enough from the buyer to pay the asset
if (balances[msg.sender] < assetsById[assetId].sellPrice) {
Error('buyAsset: there is not enough token balance to buy this asset');
return false;
}
// Calculate the seller income
uint256 sellerIncome = assetsById[assetId].sellPrice * (1000 - assetFeeIssuer - assetFeeWorldTrade) / 1000;
// Send the buyer's tokens to the seller
if (!transfer(assetsById[assetId].assetOwner, sellerIncome)) {
Error('buyAsset: seller token transfer failed'); // This shouldn't happen ever, but just in case...
return false;
}
// Send the issuer's fee
uint256 issuerIncome = assetsById[assetId].sellPrice * assetFeeIssuer / 1000;
if (!transfer(assetsById[assetId].issuer, issuerIncome)) {
Error('buyAsset: issuer token transfer failed'); // This shouldn't happen ever, but just in case...
return false;
}
// Send the WorldTrade's fee
uint256 WorldTradeIncome = assetsById[assetId].sellPrice * assetFeeWorldTrade / 1000;
if (!transfer(owner, WorldTradeIncome)) {
Error('buyAsset: WorldTrade token transfer failed'); // This shouldn't happen ever, but just in case...
return false;
}
}
// Set the asset status to Unfungible
assetsById[assetId].status = assetStatus.Unfungible;
// Transfer the asset to the buyer
assetsById[assetId].assetOwner = msg.sender;
// Event log
BuyAsset(assetId, amount);
return true;
}
// To limit issue functions just to authorized issuers
modifier onlyIssuer() {
if (!IFIssuers(SCIssuers).isIssuer(msg.sender)) {
Error('onlyIssuer function called by user that is not an authorized issuer');
} else {
_;
}
}
// To be called by issueAssetTo() and properly authorized issuers
function issueAsset(string content, uint256 sellPrice) onlyIssuer internal returns (uint256 nextAssetId) {
// Find out next asset Id
nextAssetId = lastAssetId + 1;
assetsById[nextAssetId].assetId = nextAssetId;
assetsById[nextAssetId].assetOwner = msg.sender;
assetsById[nextAssetId].issuer = msg.sender;
assetsById[nextAssetId].content = content;
assetsById[nextAssetId].sellPrice = sellPrice;
assetsById[nextAssetId].status = assetStatus.Released;
// Update lastAssetId
lastAssetId++;
// Event log
IssueAsset(nextAssetId, msg.sender, sellPrice);
return nextAssetId;
}
// Issuer sends a new free asset to a given user as a gift
function issueAssetTo(string content, address to) returns (bool) {
uint256 assetId = issueAsset(content, 0); // 0 tokens, as a gift
if (assetId == 0) {
Error('issueAssetTo: asset has not been properly issued');
return (false);
}
// The brand new asset is inmediatly sent to the recipient
return(sendAssetTo(assetId, to));
}
// Seller can block tradability of its assets
function setAssetUnfungible(uint256 assetId) returns (bool) {
// assetId must not be zero
if (assetId == 0) {
Error('setAssetUnfungible: assetId must not be zero');
return false;
}
// Check whether the asset belongs to the caller
if (assetsById[assetId].assetOwner != msg.sender) {
Error('setAssetUnfungible: only owners of the asset are allowed to update its status');
return false;
}
assetsById[assetId].status = assetStatus.Unfungible;
// Event log
SetAssetUnfungible(assetId, msg.sender);
return true;
}
// Seller updates the price of its assets and its status to ForSale
function setAssetPrice(uint256 assetId, uint256 sellPrice) returns (bool) {
// assetId must not be zero
if (assetId == 0) {
Error('setAssetPrice: assetId must not be zero');
return false;
}
// Check whether the asset belongs to the caller
if (assetsById[assetId].assetOwner != msg.sender) {
Error('setAssetPrice: only owners of the asset are allowed to set its price and update its status');
return false;
}
assetsById[assetId].sellPrice = sellPrice;
assetsById[assetId].status = assetStatus.ForSale;
// Event log
SetAssetPrice(assetId, msg.sender, sellPrice);
return true;
}
// Owner updates the fees for assets sale transactions
function setAssetSaleFees(uint256 feeIssuer, uint256 feeWorldTrade) returns (bool) {
// Check this is called by owner
if (!isOwner()) {
Error('setAssetSaleFees: only Owner is authorized to update asset sale fees.');
return false;
}
// Check new fees are consistent
if (feeIssuer + feeWorldTrade > 1000) {
Error('setAssetSaleFees: added fees exceed 100.0%. Not updated.');
return false;
}
assetFeeIssuer = feeIssuer;
assetFeeWorldTrade = feeWorldTrade;
// Event log
SetAssetSaleFees(feeIssuer, feeWorldTrade);
return true;
}
// **** EVENTS
// Triggered when a seller sends its asset to a buyer and receives the corresponding tokens
event SendAssetTo(uint256 assetId, address assetBuyer);
// Triggered when a buyer sends its tokens to a seller and receives the specified asset
event BuyAsset(uint256 assetId, uint256 amount);
// Triggered when the admin issues a new asset
event IssueAsset(uint256 nextAssetId, address assetOwner, uint256 sellPrice);
// Triggered when the user updates its asset status to Unfungible
event SetAssetUnfungible(uint256 assetId, address assetOwner);
// Triggered when the user updates its asset price and status to ForSale
event SetAssetPrice(uint256 assetId, address assetOwner, uint256 sellPrice);
// Triggered when the owner updates the asset sale fees
event SetAssetSaleFees(uint256 feeIssuer, uint256 feeWorldTrade);
} | Constructor: set up token properties and owner token balance This is the constructor, so owner should be equal to msg.sender, and this method should be called just once make sure owner address is configured if(owner == 0x0) throw; owner address can call this function if (msg.sender != owner ) throw; call this function just once if (allocated) throw; allocated = true; | function Token() {
owner = msg.sender;
totalSupply = initialSupply;
name = "WorldTrade";
symbol = "WTE";
decimals = 6;
balances[owner] = totalSupply;
Transfer(this, owner, totalSupply);
}
| 2,487,261 |
./partial_match/42/0xc5d5D4A6B145D9Ea18290E2E94cBa7c2b33289f5/sources/UniverseChart.sol | Utils function to change default company address _referrer The referrer address;/ | function register(address _referrer) external {
require(accounts[_referrer].referrer != address(0) || _referrer == accountIds[0],"Invalid referrer address");
require(accounts[msg.sender].referrer == address(0), "Account has been registered");
uint registerTime = block.timestamp;
uint256 _id = accounts[_referrer].id;
referrers[_id].push(referrer);
accounts[msg.sender] = account;
accountIds[lastId] = msg.sender;
emit Register(lastId++, msg.sender, _referrer, registerTime);
}
| 9,036,083 |
./full_match/80001/0x6b807cB56f7a8eBE896B93D0960bE3cA84F98aF0/sources/src/nft/BaseWormholeBridgedNft.sol | "constructor" of the proxy contract | function initialize(
string memory name,
string memory symbol,
uint256 dustAmountOnMint,
uint256 gasTokenAmountOnMint,
address royaltyReceiver,
uint96 royaltyFeeNumerator
) public initializer {
_dustAmountOnMint = dustAmountOnMint;
_gasTokenAmountOnMint = gasTokenAmountOnMint;
__UUPSUpgradeable_init();
__ERC721_init(name, symbol);
__ERC2981_init();
__Ownable_init();
_setDefaultRoyalty(royaltyReceiver, royaltyFeeNumerator);
}
| 845,764 |
./full_match/1/0x9f1040ff6adc3F484aF4C140B4da398Aa28D3A32/sources/contracts/Interfaces/IPCV.sol | --- Events -- --- Functions --- | interface IPCV {
event THUSDTokenAddressSet(address _thusdTokenAddress);
event BorrowerOperationsAddressSet(address _borrowerOperationsAddress);
event CollateralAddressSet(address _collateralAddress);
event BAMMAddressSet(address _bammAddress);
event RolesSet(address _council, address _treasury);
event BAMMDeposit(uint256 _thusdAmount);
event BAMMWithdraw(uint256 _numShares);
event THUSDWithdraw(address _recipient, uint256 _thusdAmount);
event CollateralWithdraw(address _recipient, uint256 _collateralAmount);
event PCVDebtPaid(uint256 _paidDebt);
event RecipientAdded(address _recipient);
event RecipientRemoved(address _recipient);
function debtToPay() external returns(uint256);
function payDebt(uint256 _thusdToBurn) external;
function setAddresses(
address _thusdTokenAddress,
address _borrowerOperations,
address payable _bammAddress,
address _collateralERC20
) external;
function initialize() external;
function depositToBAMM(uint256 _thusdAmount) external;
function withdrawFromBAMM(uint256 _numShares) external;
function withdrawTHUSD(address _recipient, uint256 _thusdAmount) external;
function withdrawCollateral(address _recipient, uint256 _collateralAmount) external;
function addRecipientToWhitelist(address _recipient) external;
function addRecipientsToWhitelist(address[] calldata _recipients) external;
function removeRecipientFromWhitelist(address _recipient) external;
function removeRecipientsFromWhitelist(address[] calldata _recipients) external;
function startChangingRoles(address _council, address _treasury) external;
function cancelChangingRoles() external;
function finalizeChangingRoles() external;
function collateralERC20() external view returns(IERC20);
function thusdToken() external view returns(ITHUSDToken);
}
| 2,929,105 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "hardhat/console.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
contract OutfitNFT is ERC721 {
address internal fancyDAO;
using Counters for Counters.Counter;
Counters.Counter private _outfitIdCounter;
string originalOutfitURI;
mapping (uint256 => string) SecretURIs;
mapping (uint256=>address) outfitOwnerBee; // maps outfitTokenID to the BeeContract. (User does not own outfits.)
mapping (uint256=>uint256) beeTokenID; // Maps outfitIds to BeeIds.
constructor(string memory tokenName, string memory symbol) ERC721(tokenName, symbol) {
_setBaseURI("ipfs://");
// fancyDAO = DAOAddress;
}
//TODO - register for ERC-1820
//TODO Should split it 50:50 with th creator. Register Outfit with as royalty receiver and split.
// function royaltyInfo(uint256 _tokenId, uint256 _price) external view returns (address receiver, uint256 amount){
// require (_tokenId>0, "TokenID out of range");
// return (fancyDAO, _price/10); //TODO need to forward price/5 to the creator.
// }
function mintToken(address owner, string memory metadataURI)
public
returns (uint256)
{
require( balanceOf(msg.sender) == 0, "Sorry, only one bee per person." );
_outfitIdCounter.increment();
uint256 id = _outfitIdCounter.current();
_safeMint(owner, id);
_setTokenURI(id, metadataURI);
originalOutfitURI = metadataURI;
return id;
}
//==================================
// SPECIAL FUNCIONALITY
//
// Returns True if the token exists, else false.
function tokenExists(uint256 _tokenId) public view returns (bool){
return _exists(_tokenId);
}
function isOwnedBy(uint256 _beeID) public view returns (bool){
return(beeTokenID[_beeID] != 0);
}
// Given an outfitId, return the the one with the bee attached.
function getTokenURI(uint _outfitId) public view returns (string memory) {
return "bafyreie2wx4due37g4bwv6askqtdntuhiim7elpcmagc7tjghjh5z5vpdm/metadata.json";
}
function setSecretTokenURI(string memory _secretURI, uint256 _oufitId) public {
SecretURIs[_oufitId] = _secretURI;
}
// Called by the DAO to ask outfit to attach to a bee. Must be called _before_ calling the bee
function attachToBee(uint256 _outfitID, address _beeContract, uint256 _beeID) public {
// FancyBeeInterface fancyBee = FancyBeeInterface(_beeContract);
require(msg.sender == fancyDAO, "Not fancyDAO");
require (!tokenExists(_outfitID), "Invalid outfit"); //check outfit exists.
require (outfitOwnerBee[_outfitID] != address(0), "Already taken"); //check the outfit is available, if the location is empty (0's), its available.
outfitOwnerBee[_outfitID] = _beeContract;
beeTokenID[_outfitID] = _beeID;
// _setTokenOWner(_contract, _beeID); //Will be done by the DAO.
}
// function _transfer(address _from, address _to, uint _tokenId) internal override {
// require(outfitOwnerBee[_tokenId] == address(0), "Transfer not allowed.");
// super._transfer(_from, _to, _tokenID);
// }
} | Returns True if the token exists, else false. | function tokenExists(uint256 _tokenId) public view returns (bool){
return _exists(_tokenId);
}
| 7,231,100 |
pragma solidity ^0.4.18;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
/// @title Auction Core
/// @dev Contains models, variables, and internal methods for the auction.
contract ClockAuctionBase {
// Represents an auction on an NFT
struct Auction {
// Current owner of NFT
address seller;
// Price (in wei) at beginning of auction
uint128 startingPrice;
// Price (in wei) at end of auction
uint128 endingPrice;
// Duration (in seconds) of auction
uint64 duration;
// Time when auction started
// NOTE: 0 if this auction has been concluded
uint64 startedAt;
}
// Reference to contract tracking NFT ownership
ERC721 public nonFungibleContract;
// Cut owner takes on each auction, measured in basis points (1/100 of a percent).
// Values 0-10,000 map to 0%-100%
uint256 public ownerCut;
// Map from token ID to their corresponding auction.
mapping (uint256 => Auction) tokenIdToAuction;
event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration);
event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
event AuctionCancelled(uint256 tokenId);
/// @dev DON'T give me your money.
function() external {}
// Modifiers to check that inputs can be safely stored with a certain
// number of bits. We use constants and multiple modifiers to save gas.
modifier canBeStoredWith64Bits(uint256 _value) {
require(_value <= 18446744073709551615);
_;
}
modifier canBeStoredWith128Bits(uint256 _value) {
require(_value < 340282366920938463463374607431768211455);
_;
}
/// @dev Returns true if the claimant owns the token.
/// @param _claimant - Address claiming to own the token.
/// @param _tokenId - ID of token whose ownership to verify.
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return (nonFungibleContract.ownerOf(_tokenId) == _claimant);
}
/// @dev Escrows the NFT, assigning ownership to this contract.
/// Throws if the escrow fails.
/// @param _owner - Current owner address of token to escrow.
/// @param _tokenId - ID of token whose approval to verify.
function _escrow(address _owner, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transferFrom(_owner, this, _tokenId);
}
/// @dev Transfers an NFT owned by this contract to another address.
/// Returns true if the transfer succeeds.
/// @param _receiver - Address to transfer NFT to.
/// @param _tokenId - ID of token to transfer.
function _transfer(address _receiver, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transfer(_receiver, _tokenId);
}
/// @dev Adds an auction to the list of open auctions. Also fires the
/// AuctionCreated event.
/// @param _tokenId The ID of the token to be put on auction.
/// @param _auction Auction to add.
function _addAuction(uint256 _tokenId, Auction _auction) internal {
// Require that all auctions have a duration of
// at least one minute. (Keeps our math from getting hairy!)
require(_auction.duration >= 1 minutes);
tokenIdToAuction[_tokenId] = _auction;
AuctionCreated(
uint256(_tokenId),
uint256(_auction.startingPrice),
uint256(_auction.endingPrice),
uint256(_auction.duration)
);
}
/// @dev Cancels an auction unconditionally.
function _cancelAuction(uint256 _tokenId, address _seller) internal {
_removeAuction(_tokenId);
_transfer(_seller, _tokenId);
AuctionCancelled(_tokenId);
}
/// @dev Computes the price and transfers winnings.
/// Does NOT transfer ownership of token.
function _bid(uint256 _tokenId, uint256 _bidAmount)
internal
returns (uint256)
{
// Get a reference to the auction struct
Auction storage auction = tokenIdToAuction[_tokenId];
// Explicitly check that this auction is currently live.
// (Because of how Ethereum mappings work, we can't just count
// on the lookup above failing. An invalid _tokenId will just
// return an auction object that is all zeros.)
require(_isOnAuction(auction));
// Check that the incoming bid is higher than the current
// price
uint256 price = _currentPrice(auction);
require(_bidAmount >= price);
// Grab a reference to the seller before the auction struct
// gets deleted.
address seller = auction.seller;
// The bid is good! Remove the auction before sending the fees
// to the sender so we can't have a reentrancy attack.
_removeAuction(_tokenId);
// Transfer proceeds to seller (if there are any!)
if (price > 0) {
// Calculate the auctioneer's cut.
// (NOTE: _computeCut() is guaranteed to return a
// value <= price, so this subtraction can't go negative.)
uint256 auctioneerCut = _computeCut(price);
uint256 sellerProceeds = price - auctioneerCut;
// NOTE: Doing a transfer() in the middle of a complex
// method like this is generally discouraged because of
// reentrancy attacks and DoS attacks if the seller is
// a contract with an invalid fallback function. We explicitly
// guard against reentrancy attacks by removing the auction
// before calling transfer(), and the only thing the seller
// can DoS is the sale of their own asset! (And if it's an
// accident, they can call cancelAuction(). )
seller.transfer(sellerProceeds);
}
// Tell the world!
AuctionSuccessful(_tokenId, price, msg.sender);
return price;
}
/// @dev Removes an auction from the list of open auctions.
/// @param _tokenId - ID of NFT on auction.
function _removeAuction(uint256 _tokenId) internal {
delete tokenIdToAuction[_tokenId];
}
/// @dev Returns true if the NFT is on auction.
/// @param _auction - Auction to check.
function _isOnAuction(Auction storage _auction) internal view returns (bool) {
return (_auction.startedAt > 0);
}
/// @dev Returns current price of an NFT on auction. Broken into two
/// functions (this one, that computes the duration from the auction
/// structure, and the other that does the price computation) so we
/// can easily test that the price computation works correctly.
function _currentPrice(Auction storage _auction)
internal
view
returns (uint256)
{
uint256 secondsPassed = 0;
// A bit of insurance against negative values (or wraparound).
// Probably not necessary (since Ethereum guarnatees that the
// now variable doesn't ever go backwards).
if (now > _auction.startedAt) {
secondsPassed = now - _auction.startedAt;
}
return _computeCurrentPrice(
_auction.startingPrice,
_auction.endingPrice,
_auction.duration,
secondsPassed
);
}
/// @dev Computes the current price of an auction. Factored out
/// from _currentPrice so we can run extensive unit tests.
/// When testing, make this function public and turn on
/// `Current price computation` test suite.
function _computeCurrentPrice(
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
uint256 _secondsPassed
)
internal
pure
returns (uint256)
{
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our public functions carefully cap the maximum values for
// time (at 64-bits) and currency (at 128-bits). _duration is
// also known to be non-zero (see the require() statement in
// _addAuction())
if (_secondsPassed >= _duration) {
// We've reached the end of the dynamic pricing portion
// of the auction, just return the end price.
return _endingPrice;
} else {
// Starting price can be higher than ending price (and often is!), so
// this delta can be negative.
int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice);
// This multiplication can't overflow, _secondsPassed will easily fit within
// 64-bits, and totalPriceChange will easily fit within 128-bits, their product
// will always fit within 256-bits.
int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration);
// currentPriceChange can be negative, but if so, will have a magnitude
// less that _startingPrice. Thus, this result will always end up positive.
int256 currentPrice = int256(_startingPrice) + currentPriceChange;
return uint256(currentPrice);
}
}
/// @dev Computes owner's cut of a sale.
/// @param _price - Sale price of NFT.
function _computeCut(uint256 _price) internal view returns (uint256) {
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our entry functions carefully cap the maximum values for
// currency (at 128-bits), and ownerCut <= 10000 (see the require()
// statement in the ClockAuction constructor). The result of this
// function is always guaranteed to be <= _price.
return _price * ownerCut / 10000;
}
}
/// @title Clock auction for non-fungible tokens.
contract ClockAuction is Pausable, ClockAuctionBase {
/// @dev Constructor creates a reference to the NFT ownership contract
/// and verifies the owner cut is in the valid range.
/// @param _nftAddress - address of a deployed contract implementing
/// the Nonfungible Interface.
/// @param _cut - percent cut the owner takes on each auction, must be
/// between 0-10,000.
function ClockAuction(address _nftAddress, uint256 _cut) public {
require(_cut <= 10000);
ownerCut = _cut;
ERC721 candidateContract = ERC721(_nftAddress);
require(candidateContract.implementsERC721());
nonFungibleContract = candidateContract;
}
/// @dev Remove all Ether from the contract, which is the owner's cuts
/// as well as any Ether sent directly to the contract address.
/// Always transfers to the NFT contract, but can be called either by
/// the owner or the NFT contract.
function withdrawBalance() external {
address nftAddress = address(nonFungibleContract);
require(
msg.sender == owner ||
msg.sender == nftAddress
);
nftAddress.transfer(this.balance);
}
/// @dev Creates and begins a new auction.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
/// @param _endingPrice - Price of item (in wei) at end of auction.
/// @param _duration - Length of time to move between starting
/// price and ending price (in seconds).
/// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
public
whenNotPaused
canBeStoredWith128Bits(_startingPrice)
canBeStoredWith128Bits(_endingPrice)
canBeStoredWith64Bits(_duration)
{
require(_owns(msg.sender, _tokenId));
_escrow(msg.sender, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/// @dev Bids on an open auction, completing the auction and transferring
/// ownership of the NFT if enough Ether is supplied.
/// @param _tokenId - ID of token to bid on.
function bid(uint256 _tokenId)
public
payable
whenNotPaused
{
// _bid will throw if the bid or funds transfer fails
_bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
}
/// @dev Cancels an auction that hasn't been won yet.
/// Returns the NFT to original owner.
/// @notice This is a state-modifying function that can
/// be called while the contract is paused.
/// @param _tokenId - ID of token on auction
function cancelAuction(uint256 _tokenId)
public
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
address seller = auction.seller;
require(msg.sender == seller);
_cancelAuction(_tokenId, seller);
}
/// @dev Cancels an auction when the contract is paused.
/// Only the owner may do this, and NFTs are returned to
/// the seller. This should only be used in emergencies.
/// @param _tokenId - ID of the NFT on auction to cancel.
function cancelAuctionWhenPaused(uint256 _tokenId)
whenPaused
onlyOwner
public
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
_cancelAuction(_tokenId, auction.seller);
}
/// @dev Returns auction info for an NFT on auction.
/// @param _tokenId - ID of NFT on auction.
function getAuction(uint256 _tokenId)
public
view
returns
(
address seller,
uint256 startingPrice,
uint256 endingPrice,
uint256 duration,
uint256 startedAt
) {
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return (
auction.seller,
auction.startingPrice,
auction.endingPrice,
auction.duration,
auction.startedAt
);
}
/// @dev Returns the current price of an auction.
/// @param _tokenId - ID of the token price we are checking.
function getCurrentPrice(uint256 _tokenId)
public
view
returns (uint256)
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return _currentPrice(auction);
}
}
/// @title Clock auction modified for sale of fighters
contract SaleClockAuction is ClockAuction {
// @dev Sanity check that allows us to ensure that we are pointing to the
// right auction in our setSaleAuctionAddress() call.
bool public isSaleClockAuction = true;
// Tracks last 4 sale price of gen0 fighter sales
uint256 public gen0SaleCount;
uint256[4] public lastGen0SalePrices;
// Delegate constructor
function SaleClockAuction(address _nftAddr, uint256 _cut) public
ClockAuction(_nftAddr, _cut) {}
/// @dev Creates and begins a new auction.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
/// @param _endingPrice - Price of item (in wei) at end of auction.
/// @param _duration - Length of auction (in seconds).
/// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
public
canBeStoredWith128Bits(_startingPrice)
canBeStoredWith128Bits(_endingPrice)
canBeStoredWith64Bits(_duration)
{
require(msg.sender == address(nonFungibleContract));
_escrow(_seller, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/// @dev Updates lastSalePrice if seller is the nft contract
/// Otherwise, works the same as default bid method.
function bid(uint256 _tokenId)
public
payable
{
// _bid verifies token ID size
address seller = tokenIdToAuction[_tokenId].seller;
uint256 price = _bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
// If not a gen0 auction, exit
if (seller == address(nonFungibleContract)) {
// Track gen0 sale prices
lastGen0SalePrices[gen0SaleCount % 4] = price;
gen0SaleCount++;
}
}
function averageGen0SalePrice() public view returns (uint256) {
uint256 sum = 0;
for (uint256 i = 0; i < 4; i++) {
sum += lastGen0SalePrices[i];
}
return sum / 4;
}
}
/// @title A facet of FighterCore that manages special access privileges.
contract FighterAccessControl {
/// @dev Emited when contract is upgraded
event ContractUpgrade(address newContract);
address public ceoAddress;
address public cfoAddress;
address public cooAddress;
// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
modifier onlyCLevel() {
require(
msg.sender == cooAddress ||
msg.sender == ceoAddress ||
msg.sender == cfoAddress
);
_;
}
function setCEO(address _newCEO) public onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
function setCFO(address _newCFO) public onlyCEO {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
function setCOO(address _newCOO) public onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
function withdrawBalance() external onlyCFO {
cfoAddress.transfer(this.balance);
}
/*** Pausable functionality adapted from OpenZeppelin ***/
/// @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused {
require(paused);
_;
}
function pause() public onlyCLevel whenNotPaused {
paused = true;
}
function unpause() public onlyCEO whenPaused {
// can't unpause if contract was upgraded
paused = false;
}
}
/// @title Base contract for CryptoFighters. Holds all common structs, events and base variables.
contract FighterBase is FighterAccessControl {
/*** EVENTS ***/
event FighterCreated(address indexed owner, uint256 fighterId, uint256 genes);
/// @dev Transfer event as defined in current draft of ERC721. Emitted every time a fighter
/// ownership is assigned, including newly created fighters.
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/*** DATA TYPES ***/
/// @dev The main Fighter struct. Every fighter in CryptoFighters is represented by a copy
/// of this structure.
struct Fighter {
// The Fighter's genetic code is packed into these 256-bits.
// A fighter's genes never change.
uint256 genes;
// The minimum timestamp after which this fighter can win a prize fighter again
uint64 prizeCooldownEndTime;
// The minimum timestamp after which this fighter can engage in battle again
uint64 battleCooldownEndTime;
// battle experience
uint32 experience;
// Set to the index that represents the current cooldown duration for this Fighter.
// Incremented by one for each successful prize won in battle
uint16 prizeCooldownIndex;
uint16 battlesFought;
uint16 battlesWon;
// The "generation number" of this fighter. Fighters minted by the CF contract
// for sale are called "gen0" and have a generation number of 0.
uint16 generation;
uint8 dexterity;
uint8 strength;
uint8 vitality;
uint8 luck;
}
/*** STORAGE ***/
/// @dev An array containing the Fighter struct for all Fighters in existence. The ID
/// of each fighter is actually an index into this array. Note that ID 0 is a negafighter.
/// Fighter ID 0 is invalid.
Fighter[] fighters;
/// @dev A mapping from fighter IDs to the address that owns them. All fighters have
/// some valid owner address, even gen0 fighters are created with a non-zero owner.
mapping (uint256 => address) public fighterIndexToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) ownershipTokenCount;
/// @dev A mapping from FighterIDs to an address that has been approved to call
/// transferFrom(). A zero value means no approval is outstanding.
mapping (uint256 => address) public fighterIndexToApproved;
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// since the number of fighters is capped to 2^32
// there is no way to overflow this
ownershipTokenCount[_to]++;
fighterIndexToOwner[_tokenId] = _to;
if (_from != address(0)) {
ownershipTokenCount[_from]--;
delete fighterIndexToApproved[_tokenId];
}
Transfer(_from, _to, _tokenId);
}
// Will generate both a FighterCreated event
function _createFighter(
uint16 _generation,
uint256 _genes,
uint8 _dexterity,
uint8 _strength,
uint8 _vitality,
uint8 _luck,
address _owner
)
internal
returns (uint)
{
Fighter memory _fighter = Fighter({
genes: _genes,
prizeCooldownEndTime: 0,
battleCooldownEndTime: 0,
prizeCooldownIndex: 0,
battlesFought: 0,
battlesWon: 0,
experience: 0,
generation: _generation,
dexterity: _dexterity,
strength: _strength,
vitality: _vitality,
luck: _luck
});
uint256 newFighterId = fighters.push(_fighter) - 1;
require(newFighterId <= 4294967295);
FighterCreated(_owner, newFighterId, _fighter.genes);
_transfer(0, _owner, newFighterId);
return newFighterId;
}
}
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
contract ERC721 {
function implementsERC721() public pure returns (bool);
function totalSupply() public view returns (uint256 total);
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 transferFrom(address _from, address _to, uint256 _tokenId) public;
function transfer(address _to, uint256 _tokenId) public;
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId);
// function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl);
}
/// @title The facet of the CryptoFighters core contract that manages ownership, ERC-721 (draft) compliant.
contract FighterOwnership is FighterBase, ERC721 {
string public name = "CryptoFighters";
string public symbol = "CF";
function implementsERC721() public pure returns (bool)
{
return true;
}
/// @dev Checks if a given address is the current owner of a particular Fighter.
/// @param _claimant the address we are validating against.
/// @param _tokenId fighter id, only valid when > 0
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return fighterIndexToOwner[_tokenId] == _claimant;
}
/// @dev Checks if a given address currently has transferApproval for a particular Fighter.
/// @param _claimant the address we are confirming fighter is approved for.
/// @param _tokenId fighter id, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return fighterIndexToApproved[_tokenId] == _claimant;
}
/// @dev Marks an address as being approved for transferFrom(), overwriting any previous
/// approval. Setting _approved to address(0) clears all transfer approval.
/// NOTE: _approve() does NOT send the Approval event.
function _approve(uint256 _tokenId, address _approved) internal {
fighterIndexToApproved[_tokenId] = _approved;
}
/// @dev Transfers a fighter owned by this contract to the specified address.
/// Used to rescue lost fighters. (There is no "proper" flow where this contract
/// should be the owner of any Fighter. This function exists for us to reassign
/// the ownership of Fighters that users may have accidentally sent to our address.)
/// @param _fighterId - ID of fighter
/// @param _recipient - Address to send the fighter to
function rescueLostFighter(uint256 _fighterId, address _recipient) public onlyCOO whenNotPaused {
require(_owns(this, _fighterId));
_transfer(this, _recipient, _fighterId);
}
/// @notice Returns the number of Fighters owned by a specific address.
/// @param _owner The owner address to check.
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
/// @notice Transfers a Fighter to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
/// CryptoFighters specifically) or your Fighter may be lost forever. Seriously.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the Fighter to transfer.
function transfer(
address _to,
uint256 _tokenId
)
public
whenNotPaused
{
require(_to != address(0));
require(_owns(msg.sender, _tokenId));
_transfer(msg.sender, _to, _tokenId);
}
/// @notice Grant another address the right to transfer a specific Fighter via
/// transferFrom(). This is the preferred flow for transfering NFTs to contracts.
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the Fighter that can be transferred if this call succeeds.
function approve(
address _to,
uint256 _tokenId
)
public
whenNotPaused
{
require(_owns(msg.sender, _tokenId));
_approve(_tokenId, _to);
Approval(msg.sender, _to, _tokenId);
}
/// @notice Transfer a Fighter owned by another address, for which the calling address
/// has previously been granted transfer approval by the owner.
/// @param _from The address that owns the Fighter to be transfered.
/// @param _to The address that should take ownership of the Fighter. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the Fighter to be transferred.
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
whenNotPaused
{
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
_transfer(_from, _to, _tokenId);
}
function totalSupply() public view returns (uint) {
return fighters.length - 1;
}
function ownerOf(uint256 _tokenId)
public
view
returns (address owner)
{
owner = fighterIndexToOwner[_tokenId];
require(owner != address(0));
}
/// @notice Returns the nth Fighter assigned to an address, with n specified by the
/// _index argument.
/// @param _owner The owner whose Fighters we are interested in.
/// @param _index The zero-based index of the fighter within the owner's list of fighters.
/// Must be less than balanceOf(_owner).
/// @dev This method MUST NEVER be called by smart contract code. It will almost
/// certainly blow past the block gas limit once there are a large number of
/// Fighters in existence. Exists only to allow off-chain queries of ownership.
/// Optional method for ERC-721.
function tokensOfOwnerByIndex(address _owner, uint256 _index)
external
view
returns (uint256 tokenId)
{
uint256 count = 0;
for (uint256 i = 1; i <= totalSupply(); i++) {
if (fighterIndexToOwner[i] == _owner) {
if (count == _index) {
return i;
} else {
count++;
}
}
}
revert();
}
}
// this helps with battle functionality
// it gives the ability to an external contract to do the following:
// * create fighters as rewards
// * update fighter stats
// * update cooldown data for next prize/battle
contract FighterBattle is FighterOwnership {
event FighterUpdated(uint256 fighterId);
/// @dev The address of the sibling contract that handles battles
address public battleContractAddress;
/// @dev If set to false the `battleContractAddress` can never be updated again
bool public battleContractAddressCanBeUpdated = true;
function setBattleAddress(address _address) public onlyCEO {
require(battleContractAddressCanBeUpdated == true);
battleContractAddress = _address;
}
function foreverBlockBattleAddressUpdate() public onlyCEO {
battleContractAddressCanBeUpdated = false;
}
modifier onlyBattleContract() {
require(msg.sender == battleContractAddress);
_;
}
function createPrizeFighter(
uint16 _generation,
uint256 _genes,
uint8 _dexterity,
uint8 _strength,
uint8 _vitality,
uint8 _luck,
address _owner
) public onlyBattleContract {
require(_generation > 0);
_createFighter(_generation, _genes, _dexterity, _strength, _vitality, _luck, _owner);
}
// Update fighter functions
// The logic for creating so many different functions is that it will be
// easier to optimise for gas costs having all these available to us.
// The contract deployment will be more expensive, but future costs can be
// cheaper.
function updateFighter(
uint256 _fighterId,
uint8 _dexterity,
uint8 _strength,
uint8 _vitality,
uint8 _luck,
uint32 _experience,
uint64 _prizeCooldownEndTime,
uint16 _prizeCooldownIndex,
uint64 _battleCooldownEndTime,
uint16 _battlesFought,
uint16 _battlesWon
)
public onlyBattleContract
{
Fighter storage fighter = fighters[_fighterId];
fighter.dexterity = _dexterity;
fighter.strength = _strength;
fighter.vitality = _vitality;
fighter.luck = _luck;
fighter.experience = _experience;
fighter.prizeCooldownEndTime = _prizeCooldownEndTime;
fighter.prizeCooldownIndex = _prizeCooldownIndex;
fighter.battleCooldownEndTime = _battleCooldownEndTime;
fighter.battlesFought = _battlesFought;
fighter.battlesWon = _battlesWon;
FighterUpdated(_fighterId);
}
function updateFighterStats(
uint256 _fighterId,
uint8 _dexterity,
uint8 _strength,
uint8 _vitality,
uint8 _luck,
uint32 _experience
)
public onlyBattleContract
{
Fighter storage fighter = fighters[_fighterId];
fighter.dexterity = _dexterity;
fighter.strength = _strength;
fighter.vitality = _vitality;
fighter.luck = _luck;
fighter.experience = _experience;
FighterUpdated(_fighterId);
}
function updateFighterBattleStats(
uint256 _fighterId,
uint64 _prizeCooldownEndTime,
uint16 _prizeCooldownIndex,
uint64 _battleCooldownEndTime,
uint16 _battlesFought,
uint16 _battlesWon
)
public onlyBattleContract
{
Fighter storage fighter = fighters[_fighterId];
fighter.prizeCooldownEndTime = _prizeCooldownEndTime;
fighter.prizeCooldownIndex = _prizeCooldownIndex;
fighter.battleCooldownEndTime = _battleCooldownEndTime;
fighter.battlesFought = _battlesFought;
fighter.battlesWon = _battlesWon;
FighterUpdated(_fighterId);
}
function updateDexterity(uint256 _fighterId, uint8 _dexterity) public onlyBattleContract {
fighters[_fighterId].dexterity = _dexterity;
FighterUpdated(_fighterId);
}
function updateStrength(uint256 _fighterId, uint8 _strength) public onlyBattleContract {
fighters[_fighterId].strength = _strength;
FighterUpdated(_fighterId);
}
function updateVitality(uint256 _fighterId, uint8 _vitality) public onlyBattleContract {
fighters[_fighterId].vitality = _vitality;
FighterUpdated(_fighterId);
}
function updateLuck(uint256 _fighterId, uint8 _luck) public onlyBattleContract {
fighters[_fighterId].luck = _luck;
FighterUpdated(_fighterId);
}
function updateExperience(uint256 _fighterId, uint32 _experience) public onlyBattleContract {
fighters[_fighterId].experience = _experience;
FighterUpdated(_fighterId);
}
}
/// @title Handles creating auctions for sale of fighters.
/// This wrapper of ReverseAuction exists only so that users can create
/// auctions with only one transaction.
contract FighterAuction is FighterBattle {
SaleClockAuction public saleAuction;
function setSaleAuctionAddress(address _address) public onlyCEO {
SaleClockAuction candidateContract = SaleClockAuction(_address);
require(candidateContract.isSaleClockAuction());
saleAuction = candidateContract;
}
function createSaleAuction(
uint256 _fighterId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
public
whenNotPaused
{
// Auction contract checks input sizes
// If fighter is already on any auction, this will throw
// because it will be owned by the auction contract.
require(_owns(msg.sender, _fighterId));
_approve(_fighterId, saleAuction);
// Sale auction throws if inputs are invalid and clears
// transfer approval after escrowing the fighter.
saleAuction.createAuction(
_fighterId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
/// @dev Transfers the balance of the sale auction contract
/// to the FighterCore contract. We use two-step withdrawal to
/// prevent two transfer calls in the auction bid function.
function withdrawAuctionBalances() external onlyCOO {
saleAuction.withdrawBalance();
}
}
/// @title all functions related to creating fighters
contract FighterMinting is FighterAuction {
// Limits the number of fighters the contract owner can ever create.
uint256 public promoCreationLimit = 5000;
uint256 public gen0CreationLimit = 25000;
// Constants for gen0 auctions.
uint256 public gen0StartingPrice = 500 finney;
uint256 public gen0EndingPrice = 10 finney;
uint256 public gen0AuctionDuration = 1 days;
// Counts the number of fighters the contract owner has created.
uint256 public promoCreatedCount;
uint256 public gen0CreatedCount;
/// @dev we can create promo fighters, up to a limit
function createPromoFighter(
uint256 _genes,
uint8 _dexterity,
uint8 _strength,
uint8 _vitality,
uint8 _luck,
address _owner
) public onlyCOO {
if (_owner == address(0)) {
_owner = cooAddress;
}
require(promoCreatedCount < promoCreationLimit);
require(gen0CreatedCount < gen0CreationLimit);
promoCreatedCount++;
gen0CreatedCount++;
_createFighter(0, _genes, _dexterity, _strength, _vitality, _luck, _owner);
}
/// @dev Creates a new gen0 fighter with the given genes and
/// creates an auction for it.
function createGen0Auction(
uint256 _genes,
uint8 _dexterity,
uint8 _strength,
uint8 _vitality,
uint8 _luck
) public onlyCOO {
require(gen0CreatedCount < gen0CreationLimit);
uint256 fighterId = _createFighter(0, _genes, _dexterity, _strength, _vitality, _luck, address(this));
_approve(fighterId, saleAuction);
saleAuction.createAuction(
fighterId,
_computeNextGen0Price(),
gen0EndingPrice,
gen0AuctionDuration,
address(this)
);
gen0CreatedCount++;
}
/// @dev Computes the next gen0 auction starting price, given
/// the average of the past 4 prices + 50%.
function _computeNextGen0Price() internal view returns (uint256) {
uint256 avePrice = saleAuction.averageGen0SalePrice();
// sanity check to ensure we don't overflow arithmetic (this big number is 2^128-1).
require(avePrice < 340282366920938463463374607431768211455);
uint256 nextPrice = avePrice + (avePrice / 2);
// We never auction for less than starting price
if (nextPrice < gen0StartingPrice) {
nextPrice = gen0StartingPrice;
}
return nextPrice;
}
}
/// @title CryptoFighters: Collectible, battlable fighters on the Ethereum blockchain.
/// @dev The main CryptoFighters contract
contract FighterCore is FighterMinting {
// This is the main CryptoFighters contract. We have several seperately-instantiated sibling contracts
// that handle auctions, battles and the creation of new fighters. By keeping
// them in their own contracts, we can upgrade them without disrupting the main contract that tracks
// fighter ownership.
//
// - FighterBase: This is where we define the most fundamental code shared throughout the core
// functionality. This includes our main data storage, constants and data types, plus
// internal functions for managing these items.
//
// - FighterAccessControl: This contract manages the various addresses and constraints for operations
// that can be executed only by specific roles. Namely CEO, CFO and COO.
//
// - FighterOwnership: This provides the methods required for basic non-fungible token
// transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721).
//
// - FighterBattle: This file contains the methods necessary to allow a separate contract to handle battles
// allowing it to reward new prize fighters as well as update fighter stats.
//
// - FighterAuction: Here we have the public methods for auctioning or bidding on fighters.
// The actual auction functionality is handled in a sibling sales contract,
// while auction creation and bidding is mostly mediated through this facet of the core contract.
//
// - FighterMinting: This final facet contains the functionality we use for creating new gen0 fighters.
// We can make up to 5000 "promo" fighters that can be given away, and all others can only be created and then immediately put up
// for auction via an algorithmically determined starting price. Regardless of how they
// are created, there is a hard limit of 25,000 gen0 fighters.
// Set in case the core contract is broken and an upgrade is required
address public newContractAddress;
function FighterCore() public {
paused = true;
ceoAddress = msg.sender;
cooAddress = msg.sender;
cfoAddress = msg.sender;
// start with the mythical fighter 0
_createFighter(0, uint256(-1), uint8(-1), uint8(-1), uint8(-1), uint8(-1), address(0));
}
/// @dev Used to mark the smart contract as upgraded, in case there is a serious
/// breaking bug. This method does nothing but keep track of the new contract and
/// emit a message indicating that the new address is set. It's up to clients of this
/// contract to update to the new contract address in that case. (This contract will
/// be paused indefinitely if such an upgrade takes place.)
/// @param _v2Address new address
function setNewAddress(address _v2Address) public onlyCEO whenPaused {
newContractAddress = _v2Address;
ContractUpgrade(_v2Address);
}
/// @notice No tipping!
/// @dev Reject all Ether from being sent here, unless it's from one of the
/// two auction contracts. (Hopefully, we can prevent user accidents.)
function() external payable {
require(msg.sender == address(saleAuction));
}
/// @param _id The ID of the fighter of interest.
function getFighter(uint256 _id)
public
view
returns (
uint256 prizeCooldownEndTime,
uint256 battleCooldownEndTime,
uint256 prizeCooldownIndex,
uint256 battlesFought,
uint256 battlesWon,
uint256 generation,
uint256 genes,
uint256 dexterity,
uint256 strength,
uint256 vitality,
uint256 luck,
uint256 experience
) {
Fighter storage fighter = fighters[_id];
prizeCooldownEndTime = fighter.prizeCooldownEndTime;
battleCooldownEndTime = fighter.battleCooldownEndTime;
prizeCooldownIndex = fighter.prizeCooldownIndex;
battlesFought = fighter.battlesFought;
battlesWon = fighter.battlesWon;
generation = fighter.generation;
genes = fighter.genes;
dexterity = fighter.dexterity;
strength = fighter.strength;
vitality = fighter.vitality;
luck = fighter.luck;
experience = fighter.experience;
}
/// @dev Override unpause so it requires all external contract addresses
/// to be set before contract can be unpaused. Also, we can't have
/// newContractAddress set either, because then the contract was upgraded.
function unpause() public onlyCEO whenPaused {
require(saleAuction != address(0));
require(newContractAddress == address(0));
super.unpause();
}
} | Override unpause so it requires all external contract addresses to be set before contract can be unpaused. Also, we can't have newContractAddress set either, because then the contract was upgraded. | function unpause() public onlyCEO whenPaused {
require(saleAuction != address(0));
require(newContractAddress == address(0));
super.unpause();
}
| 7,321,924 |
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.4;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-upgradeable/math/SignedSafeMathUpgradeable.sol";
import "../libraries/Constant.sol";
import "../libraries/Math.sol";
import "../libraries/SafeMathExt.sol";
import "../libraries/Utils.sol";
import "../module/MarginAccountModule.sol";
import "../module/PerpetualModule.sol";
import "../Type.sol";
library AMMModule {
using Math for int256;
using SafeMathExt for int256;
using SignedSafeMathUpgradeable for int256;
using MarginAccountModule for PerpetualStorage;
using PerpetualModule for PerpetualStorage;
struct Context {
int256 indexPrice;
int256 position;
int256 positionValue;
// squareValue is 10^36, others are 10^18
int256 squareValue;
int256 positionMargin;
int256 availableCash;
}
/**
* @dev Get the trading result when trader trades with AMM, divided into two parts:
* - AMM closes its position
* - AMM opens its position.
*
* @param liquidityPool The liquidity pool object of AMM.
* @param perpetualIndex The index of the perpetual in the liquidity pool to trade.
* @param tradeAmount The trading amount of position, positive if AMM longs, negative if AMM shorts.
* @param partialFill Whether to allow partially trading. Set to true when liquidation trading,
* set to false when normal trading.
* @return deltaCash The update cash(collateral) of AMM after the trade.
* @return deltaPosition The update position of AMM after the trade.
*/
function queryTradeWithAMM(
LiquidityPoolStorage storage liquidityPool,
uint256 perpetualIndex,
int256 tradeAmount,
bool partialFill
) public view returns (int256 deltaCash, int256 deltaPosition) {
require(tradeAmount != 0, "trading amount is zero");
Context memory context = prepareContext(liquidityPool, perpetualIndex);
PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex];
(int256 closePosition, int256 openPosition) = Utils.splitAmount(
context.position,
tradeAmount
);
// AMM close position
int256 closeBestPrice;
(deltaCash, closeBestPrice) = ammClosePosition(context, perpetual, closePosition);
context.availableCash = context.availableCash.add(deltaCash);
context.position = context.position.add(closePosition);
// AMM open position
(int256 openDeltaCash, int256 openDeltaPosition, int256 openBestPrice) = ammOpenPosition(
context,
perpetual,
openPosition,
partialFill
);
deltaCash = deltaCash.add(openDeltaCash);
deltaPosition = closePosition.add(openDeltaPosition);
int256 bestPrice = closePosition != 0 ? closeBestPrice : openBestPrice;
// If price is better(for trader) than best price, change price to best price
deltaCash = deltaCash.max(bestPrice.wmul(deltaPosition).neg());
}
/**
* @dev Calculate the amount of share token to mint when liquidity provider adds liquidity to the liquidity pool.
* If adding liquidity at first time, which means total supply of share token is zero,
* the amount of share token to mint equals to the pool margin after adding liquidity.
*
* @param liquidityPool The liquidity pool object of AMM.
* @param shareTotalSupply The total supply of the share token before adding liquidity.
* @param cashToAdd The amount of cash(collateral) added to the liquidity pool.
* @return shareToMint The amount of share token to mint.
* @return addedPoolMargin The added amount of pool margin after adding liquidity.
*/
function getShareToMint(
LiquidityPoolStorage storage liquidityPool,
int256 shareTotalSupply,
int256 cashToAdd
) public view returns (int256 shareToMint, int256 addedPoolMargin) {
Context memory context = prepareContext(liquidityPool);
(int256 poolMargin, ) = getPoolMargin(context);
context.availableCash = context.availableCash.add(cashToAdd);
(int256 newPoolMargin, ) = getPoolMargin(context);
addedPoolMargin = newPoolMargin.sub(poolMargin);
if (shareTotalSupply == 0) {
// first time, if there is pool margin left in pool, it belongs to the first person who adds liquidity
shareToMint = newPoolMargin;
} else {
// If share token's total supply is not zero and there is no money in pool,
// these share tokens have no value. This case should be avoided.
require(poolMargin > 0, "share token has no value");
shareToMint = newPoolMargin.sub(poolMargin).wfrac(shareTotalSupply, poolMargin);
}
}
/**
* @dev Calculate the amount of cash to add when liquidity provider adds liquidity to the liquidity pool.
* If adding liquidity at first time, which means total supply of share token is zero,
* the amount of cash to add equals to the share amount to mint minus pool margin before adding liquidity.
*
* @param liquidityPool The liquidity pool object of AMM.
* @param shareTotalSupply The total supply of the share token before adding liquidity.
* @param shareToMint The amount of share token to mint.
* @return cashToAdd The amount of cash(collateral) to add to the liquidity pool.
*/
function getCashToAdd(
LiquidityPoolStorage storage liquidityPool,
int256 shareTotalSupply,
int256 shareToMint
) public view returns (int256 cashToAdd) {
Context memory context = prepareContext(liquidityPool);
(int256 poolMargin, ) = getPoolMargin(context);
if (shareTotalSupply == 0) {
// first time, if there is pool margin left in pool, it belongs to the first person who adds liquidity
cashToAdd = shareToMint.sub(poolMargin).max(0);
} else {
// If share token's total supply is not zero and there is no money in pool,
// these share tokens have no value. This case should be avoided.
require(poolMargin > 0, "share token has no value");
int256 newPoolMargin = shareTotalSupply.add(shareToMint).wfrac(
poolMargin,
shareTotalSupply
);
int256 minPoolMargin = context.squareValue.div(2).sqrt();
int256 newCash;
if (newPoolMargin <= minPoolMargin) {
// pool is still unsafe after adding liquidity
newCash = newPoolMargin.mul(2).sub(context.positionValue);
} else {
// context.squareValue is 10^36, so use div instead of wdiv
newCash = context.squareValue.div(newPoolMargin).div(2).add(newPoolMargin).sub(
context.positionValue
);
}
cashToAdd = newCash.sub(context.availableCash);
}
}
/**
* @dev Calculate the amount of cash(collateral) to return when liquidity provider removes liquidity from the liquidity pool.
* Removing liquidity is forbidden at several cases:
* 1. AMM is unsafe before removing liquidity
* 2. AMM is unsafe after removing liquidity
* 3. AMM will offer negative price at any perpetual after removing liquidity
* 4. AMM will exceed maximum leverage at any perpetual after removing liquidity
*
* @param liquidityPool The liquidity pool object of AMM.
* @param shareTotalSupply The total supply of the share token before removing liquidity.
* @param shareToRemove The amount of share token to redeem.
* @return cashToReturn The amount of cash(collateral) to return.
* @return removedInsuranceFund The part of insurance fund returned to LP if all perpetuals are in CLEARED state.
* @return removedDonatedInsuranceFund The part of donated insurance fund returned to LP if all perpetuals are in CLEARED state.
* @return removedPoolMargin The removed amount of pool margin after removing liquidity.
*/
function getCashToReturn(
LiquidityPoolStorage storage liquidityPool,
int256 shareTotalSupply,
int256 shareToRemove
)
public
view
returns (
int256 cashToReturn,
int256 removedInsuranceFund,
int256 removedDonatedInsuranceFund,
int256 removedPoolMargin
)
{
require(
shareTotalSupply > 0,
"total supply of share token is zero when removing liquidity"
);
Context memory context = prepareContext(liquidityPool);
require(isAMMSafe(context, 0), "AMM is unsafe before removing liquidity");
removedPoolMargin = calculatePoolMarginWhenSafe(context, 0);
require(removedPoolMargin > 0, "pool margin must be positive");
int256 poolMargin = shareTotalSupply.sub(shareToRemove).wfrac(
removedPoolMargin,
shareTotalSupply
);
removedPoolMargin = removedPoolMargin.sub(poolMargin);
{
int256 minPoolMargin = context.squareValue.div(2).sqrt();
require(poolMargin >= minPoolMargin, "AMM is unsafe after removing liquidity");
}
cashToReturn = calculateCashToReturn(context, poolMargin);
require(cashToReturn >= 0, "received margin is negative");
uint256 length = liquidityPool.perpetualCount;
bool allCleared = true;
for (uint256 i = 0; i < length; i++) {
PerpetualStorage storage perpetual = liquidityPool.perpetuals[i];
if (perpetual.state != PerpetualState.CLEARED) {
allCleared = false;
}
if (perpetual.state != PerpetualState.NORMAL) {
continue;
}
// prevent AMM offering negative price
require(
perpetual.getPosition(address(this)) <=
poolMargin.wdiv(perpetual.openSlippageFactor.value).wdiv(
perpetual.getIndexPrice()
),
"AMM is unsafe after removing liquidity"
);
}
// prevent AMM exceeding max leverage
require(
context.availableCash.add(context.positionValue).sub(cashToReturn) >=
context.positionMargin,
"AMM exceeds max leverage after removing liquidity"
);
if (allCleared) {
// get insurance fund proportionally
removedInsuranceFund = liquidityPool.insuranceFund.wfrac(
shareToRemove,
shareTotalSupply,
Round.FLOOR
);
removedDonatedInsuranceFund = liquidityPool.donatedInsuranceFund.wfrac(
shareToRemove,
shareTotalSupply,
Round.FLOOR
);
cashToReturn = cashToReturn.add(removedInsuranceFund).add(removedDonatedInsuranceFund);
}
}
/**
* @dev Calculate the amount of share token to redeem when liquidity provider removes liquidity from the liquidity pool.
* Removing liquidity is forbidden at several cases:
* 1. AMM is unsafe before removing liquidity
* 2. AMM is unsafe after removing liquidity
* 3. AMM will offer negative price at any perpetual after removing liquidity
* 4. AMM will exceed maximum leverage at any perpetual after removing liquidity
*
* @param liquidityPool The liquidity pool object of AMM.
* @param shareTotalSupply The total supply of the share token before removing liquidity.
* @param cashToReturn The cash(collateral) to return.
* @return shareToRemove The amount of share token to redeem.
* @return removedInsuranceFund The part of insurance fund returned to LP if all perpetuals are in CLEARED state.
* @return removedDonatedInsuranceFund The part of donated insurance fund returned to LP if all perpetuals are in CLEARED state.
* @return removedPoolMargin The removed amount of pool margin after removing liquidity.
*/
function getShareToRemove(
LiquidityPoolStorage storage liquidityPool,
int256 shareTotalSupply,
int256 cashToReturn
)
public
view
returns (
int256 shareToRemove,
int256 removedInsuranceFund,
int256 removedDonatedInsuranceFund,
int256 removedPoolMargin
)
{
require(
shareTotalSupply > 0,
"total supply of share token is zero when removing liquidity"
);
Context memory context = prepareContext(liquidityPool);
require(isAMMSafe(context, 0), "AMM is unsafe before removing liquidity");
int256 poolMargin = calculatePoolMarginWhenSafe(context, 0);
context.availableCash = context.availableCash.sub(cashToReturn);
require(isAMMSafe(context, 0), "AMM is unsafe after removing liquidity");
int256 newPoolMargin = calculatePoolMarginWhenSafe(context, 0);
removedPoolMargin = poolMargin.sub(newPoolMargin);
shareToRemove = poolMargin.sub(newPoolMargin).wfrac(shareTotalSupply, poolMargin);
uint256 length = liquidityPool.perpetualCount;
bool allCleared = true;
for (uint256 i = 0; i < length; i++) {
PerpetualStorage storage perpetual = liquidityPool.perpetuals[i];
if (perpetual.state != PerpetualState.CLEARED) {
allCleared = false;
}
if (perpetual.state != PerpetualState.NORMAL) {
continue;
}
// prevent AMM offering negative price
require(
perpetual.getPosition(address(this)) <=
newPoolMargin.wdiv(perpetual.openSlippageFactor.value).wdiv(
perpetual.getIndexPrice()
),
"AMM is unsafe after removing liquidity"
);
}
// prevent AMM exceeding max leverage
require(
context.availableCash.add(context.positionValue) >= context.positionMargin,
"AMM exceeds max leverage after removing liquidity"
);
if (allCleared) {
// get insurance fund proportionally
(
shareToRemove,
removedInsuranceFund,
removedDonatedInsuranceFund,
removedPoolMargin
) = getShareToRemoveWhenAllCleared(
liquidityPool,
cashToReturn,
poolMargin,
shareTotalSupply
);
}
}
/**
* @dev Calculate the amount of share token to redeem when liquidity provider removes liquidity from the liquidity pool.
* Only called when all perpetuals in the liquidity pool are in CLEARED state.
*
* @param liquidityPool The liquidity pool object of AMM.
* @param cashToReturn The cash(collateral) to return.
* @param poolMargin The pool margin before removing liquidity.
* @param shareTotalSupply The total supply of the share token before removing liquidity.
* @return shareToRemove The amount of share token to redeem.
* @return removedInsuranceFund The part of insurance fund returned to LP if all perpetuals are in CLEARED state.
* @return removedDonatedInsuranceFund The part of donated insurance fund returned to LP if all perpetuals are in CLEARED state.
* @return removedPoolMargin The part of pool margin returned to LP if all perpetuals are in CLEARED state.
*/
function getShareToRemoveWhenAllCleared(
LiquidityPoolStorage storage liquidityPool,
int256 cashToReturn,
int256 poolMargin,
int256 shareTotalSupply
)
public
view
returns (
int256 shareToRemove,
int256 removedInsuranceFund,
int256 removedDonatedInsuranceFund,
int256 removedPoolMargin
)
{
// get insurance fund proportionally
require(
poolMargin.add(liquidityPool.insuranceFund).add(liquidityPool.donatedInsuranceFund) > 0,
"all cleared, insufficient liquidity"
);
shareToRemove = shareTotalSupply.wfrac(
cashToReturn,
poolMargin.add(liquidityPool.insuranceFund).add(liquidityPool.donatedInsuranceFund)
);
removedInsuranceFund = liquidityPool.insuranceFund.wfrac(
shareToRemove,
shareTotalSupply,
Round.FLOOR
);
removedDonatedInsuranceFund = liquidityPool.donatedInsuranceFund.wfrac(
shareToRemove,
shareTotalSupply,
Round.FLOOR
);
removedPoolMargin = poolMargin.wfrac(shareToRemove, shareTotalSupply, Round.FLOOR);
}
/**
* @dev Calculate the pool margin of AMM when AMM is safe.
* Pool margin is how much collateral of the pool considering the AMM's positions of perpetuals.
*
* @param context Context object of AMM, but current perpetual is not included.
* @param slippageFactor The slippage factor of current perpetual.
* @return poolMargin The pool margin of AMM.
*/
function calculatePoolMarginWhenSafe(Context memory context, int256 slippageFactor)
internal
pure
returns (int256 poolMargin)
{
// The context doesn't include the current perpetual, add them.
int256 positionValue = context.indexPrice.wmul(context.position);
int256 margin = positionValue.add(context.positionValue).add(context.availableCash);
// 10^36, the same as context.squareValue
int256 tmp = positionValue.wmul(positionValue).mul(slippageFactor).add(context.squareValue);
int256 beforeSqrt = margin.mul(margin).sub(tmp.mul(2));
require(beforeSqrt >= 0, "AMM is unsafe when calculating pool margin");
poolMargin = beforeSqrt.sqrt().add(margin).div(2);
require(poolMargin >= 0, "pool margin is negative when calculating pool margin");
}
/**
* @dev Check if AMM is safe
* @param context Context object of AMM, but current perpetual is not included.
* @param slippageFactor The slippage factor of current perpetual.
* @return bool True if AMM is safe.
*/
function isAMMSafe(Context memory context, int256 slippageFactor) internal pure returns (bool) {
int256 positionValue = context.indexPrice.wmul(context.position);
// 10^36, the same as context.squareValue
int256 minAvailableCash = positionValue.wmul(positionValue).mul(slippageFactor);
minAvailableCash = minAvailableCash.add(context.squareValue).mul(2).sqrt().sub(
context.positionValue.add(positionValue)
);
return context.availableCash >= minAvailableCash;
}
/**
* @dev Get the trading result when AMM closes its position.
* If the AMM is unsafe, the trading price is the best price.
* If trading price is too bad, it will be limited to index price * (1 +/- max close price discount)
*
* @param context Context object of AMM, but current perpetual is not included.
* @param perpetual The perpetual object to trade.
* @param tradeAmount The amount of position to trade.
* Positive for long and negative for short from AMM's perspective.
* @return deltaCash The update cash(collateral) of AMM after the trade.
* @return bestPrice The best price, is used for clipping to spread price if needed outside.
* If AMM is safe, best price = middle price * (1 +/- half spread).
* If AMM is unsafe and normal case, best price = index price.
*/
function ammClosePosition(
Context memory context,
PerpetualStorage storage perpetual,
int256 tradeAmount
) internal view returns (int256 deltaCash, int256 bestPrice) {
if (tradeAmount == 0) {
return (0, 0);
}
int256 positionBefore = context.position;
int256 indexPrice = context.indexPrice;
int256 slippageFactor = perpetual.closeSlippageFactor.value;
int256 maxClosePriceDiscount = perpetual.maxClosePriceDiscount.value;
int256 halfSpread = tradeAmount < 0
? perpetual.halfSpread.value
: perpetual.halfSpread.value.neg();
if (isAMMSafe(context, slippageFactor)) {
int256 poolMargin = calculatePoolMarginWhenSafe(context, slippageFactor);
require(poolMargin > 0, "pool margin must be positive");
bestPrice = getMidPrice(poolMargin, indexPrice, positionBefore, slippageFactor).wmul(
halfSpread.add(Constant.SIGNED_ONE)
);
deltaCash = getDeltaCash(
poolMargin,
positionBefore,
positionBefore.add(tradeAmount),
indexPrice,
slippageFactor
);
} else {
bestPrice = indexPrice;
deltaCash = bestPrice.wmul(tradeAmount).neg();
}
int256 priceLimit = tradeAmount > 0
? Constant.SIGNED_ONE.add(maxClosePriceDiscount)
: Constant.SIGNED_ONE.sub(maxClosePriceDiscount);
// prevent too bad price
deltaCash = deltaCash.max(indexPrice.wmul(priceLimit).wmul(tradeAmount).neg());
// prevent negative price
require(
!Utils.hasTheSameSign(deltaCash, tradeAmount),
"price is negative when AMM closes position"
);
}
/**
* @dev Get the trading result when AMM opens its position.
* AMM can't open position when unsafe and can't open position to exceed the maximum position
*
* @param context Context object of AMM, but current perpetual is not included.
* @param perpetual The perpetual object to trade
* @param tradeAmount The trading amount of position, positive if AMM longs, negative if AMM shorts
* @param partialFill Whether to allow partially trading. Set to true when liquidation trading,
* set to false when normal trading
* @return deltaCash The update cash(collateral) of AMM after the trade
* @return deltaPosition The update position of AMM after the trade
* @return bestPrice The best price, is used for clipping to spread price if needed outside.
* Equal to middle price * (1 +/- half spread)
*/
function ammOpenPosition(
Context memory context,
PerpetualStorage storage perpetual,
int256 tradeAmount,
bool partialFill
)
internal
view
returns (
int256 deltaCash,
int256 deltaPosition,
int256 bestPrice
)
{
if (tradeAmount == 0) {
return (0, 0, 0);
}
int256 slippageFactor = perpetual.openSlippageFactor.value;
if (!isAMMSafe(context, slippageFactor)) {
require(partialFill, "AMM is unsafe when open");
return (0, 0, 0);
}
int256 poolMargin = calculatePoolMarginWhenSafe(context, slippageFactor);
require(poolMargin > 0, "pool margin must be positive");
int256 indexPrice = context.indexPrice;
int256 positionBefore = context.position;
int256 positionAfter = positionBefore.add(tradeAmount);
int256 maxPosition = getMaxPosition(
context,
poolMargin,
perpetual.ammMaxLeverage.value,
slippageFactor,
positionAfter > 0
);
if (positionAfter.abs() > maxPosition.abs()) {
require(partialFill, "trade amount exceeds max amount");
// trade to max position if partialFill
deltaPosition = maxPosition.sub(positionBefore);
// current position already exeeds max position before trade, can't open
if (Utils.hasTheSameSign(deltaPosition, tradeAmount.neg())) {
return (0, 0, 0);
}
positionAfter = maxPosition;
} else {
deltaPosition = tradeAmount;
}
deltaCash = getDeltaCash(
poolMargin,
positionBefore,
positionAfter,
indexPrice,
slippageFactor
);
// prevent negative price
require(
!Utils.hasTheSameSign(deltaCash, deltaPosition),
"price is negative when AMM opens position"
);
int256 halfSpread = tradeAmount < 0
? perpetual.halfSpread.value
: perpetual.halfSpread.value.neg();
bestPrice = getMidPrice(poolMargin, indexPrice, positionBefore, slippageFactor).wmul(
halfSpread.add(Constant.SIGNED_ONE)
);
}
/**
* @dev Calculate the status of AMM
*
* @param liquidityPool The reference of liquidity pool storage.
* @return context Context object of AMM, but current perpetual is not included.
*/
function prepareContext(LiquidityPoolStorage storage liquidityPool)
internal
view
returns (Context memory context)
{
context = prepareContext(liquidityPool, liquidityPool.perpetualCount);
}
/**
* @dev Calculate the status of AMM, but specified perpetual index is not included.
*
* @param liquidityPool The reference of liquidity pool storage.
* @param perpetualIndex The index of the perpetual in the liquidity pool to distinguish,
* set to liquidityPool.perpetualCount to skip distinguishing.
* @return context Context object of AMM.
*/
function prepareContext(LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex)
internal
view
returns (Context memory context)
{
int256 maintenanceMargin;
uint256 length = liquidityPool.perpetualCount;
for (uint256 i = 0; i < length; i++) {
PerpetualStorage storage perpetual = liquidityPool.perpetuals[i];
// only involve normal market
if (perpetual.state != PerpetualState.NORMAL) {
continue;
}
int256 position = perpetual.getPosition(address(this));
int256 indexPrice = perpetual.getIndexPrice();
require(indexPrice > 0, "index price must be positive");
context.availableCash = context.availableCash.add(
perpetual.getAvailableCash(address(this))
);
maintenanceMargin = maintenanceMargin.add(
indexPrice.wmul(position).wmul(perpetual.maintenanceMarginRate).abs()
);
if (i == perpetualIndex) {
context.indexPrice = indexPrice;
context.position = position;
} else {
// To avoid returning more cash than pool has because of precision error,
// cashToReturn should be smaller, which means positionValue should be smaller, squareValue should be bigger
context.positionValue = context.positionValue.add(
indexPrice.wmul(position, Round.FLOOR)
);
// 10^36
context.squareValue = context.squareValue.add(
position
.wmul(position, Round.CEIL)
.wmul(indexPrice, Round.CEIL)
.wmul(indexPrice, Round.CEIL)
.mul(perpetual.openSlippageFactor.value)
);
context.positionMargin = context.positionMargin.add(
indexPrice.wmul(position).abs().wdiv(perpetual.ammMaxLeverage.value)
);
}
}
context.availableCash = context.availableCash.add(liquidityPool.poolCash);
// prevent margin balance < maintenance margin.
// call setEmergencyState(SET_ALL_PERPETUALS_TO_EMERGENCY_STATE) when AMM is maintenance margin unsafe
require(
context.availableCash.add(context.positionValue).add(
context.indexPrice.wmul(context.position)
) >= maintenanceMargin,
"AMM is mm unsafe"
);
}
/**
* @dev Calculate the cash(collateral) to return when removing liquidity.
*
* @param context Context object of AMM, but current perpetual is not included.
* @param poolMargin The pool margin of AMM before removing liquidity.
* @return cashToReturn The cash(collateral) to return.
*/
function calculateCashToReturn(Context memory context, int256 poolMargin)
public
pure
returns (int256 cashToReturn)
{
if (poolMargin == 0) {
// remove all
return context.availableCash;
}
require(poolMargin > 0, "pool margin must be positive when removing liquidity");
// context.squareValue is 10^36, so use div instead of wdiv
cashToReturn = context.squareValue.div(poolMargin).div(2).add(poolMargin).sub(
context.positionValue
);
cashToReturn = context.availableCash.sub(cashToReturn);
}
/**
* @dev Get the middle price offered by AMM
*
* @param poolMargin The pool margin of AMM.
* @param indexPrice The index price of the perpetual.
* @param position The position of AMM in the perpetual.
* @param slippageFactor The slippage factor of AMM in the perpetual.
* @return midPrice A middle price offered by AMM.
*/
function getMidPrice(
int256 poolMargin,
int256 indexPrice,
int256 position,
int256 slippageFactor
) internal pure returns (int256 midPrice) {
midPrice = Constant
.SIGNED_ONE
.sub(indexPrice.wmul(position).wfrac(slippageFactor, poolMargin))
.wmul(indexPrice);
}
/**
* @dev Get update cash(collateral) of AMM if trader trades against AMM.
*
* @param poolMargin The pool margin of AMM.
* @param positionBefore The position of AMM in the perpetual before trading.
* @param positionAfter The position of AMM in the perpetual after trading.
* @param indexPrice The index price of the perpetual.
* @param slippageFactor The slippage factor of AMM in the perpetual.
* @return deltaCash The update cash(collateral) of AMM after trading.
*/
function getDeltaCash(
int256 poolMargin,
int256 positionBefore,
int256 positionAfter,
int256 indexPrice,
int256 slippageFactor
) internal pure returns (int256 deltaCash) {
deltaCash = positionAfter.add(positionBefore).wmul(indexPrice).div(2).wfrac(
slippageFactor,
poolMargin
);
deltaCash = Constant.SIGNED_ONE.sub(deltaCash).wmul(indexPrice).wmul(
positionBefore.sub(positionAfter)
);
}
/**
* @dev Get the max position of AMM in the perpetual when AMM is opening position, calculated by three restrictions:
* 1. AMM must be safe after the trade.
* 2. AMM mustn't exceed maximum leverage in any perpetual after the trade.
* 3. AMM must offer positive price in any perpetual after the trade. It's easy to prove that, in the
* perpetual, AMM definitely offers positive price when AMM holds short position.
*
* @param context Context object of AMM, but current perpetual is not included.
* @param poolMargin The pool margin of AMM.
* @param ammMaxLeverage The max leverage of AMM in the perpetual.
* @param slippageFactor The slippage factor of AMM in the perpetual.
* @return maxPosition The max position of AMM in the perpetual.
*/
function getMaxPosition(
Context memory context,
int256 poolMargin,
int256 ammMaxLeverage,
int256 slippageFactor,
bool isLongSide
) internal pure returns (int256 maxPosition) {
int256 indexPrice = context.indexPrice;
int256 beforeSqrt = poolMargin.mul(poolMargin).mul(2).sub(context.squareValue).wdiv(
slippageFactor
);
if (beforeSqrt <= 0) {
// 1. already unsafe, can't open position
// 2. initial AMM is also this case, position = 0, available cash = 0, pool margin = 0
return 0;
}
int256 maxPosition3 = beforeSqrt.sqrt().wdiv(indexPrice);
int256 maxPosition2;
// context.squareValue is 10^36, so use div instead of wdiv
beforeSqrt = poolMargin.sub(context.positionMargin).add(
context.squareValue.div(poolMargin).div(2)
);
beforeSqrt = beforeSqrt.wmul(ammMaxLeverage).wmul(ammMaxLeverage).wmul(slippageFactor);
beforeSqrt = poolMargin.sub(beforeSqrt.mul(2));
if (beforeSqrt < 0) {
// never exceed max leverage
maxPosition2 = type(int256).max;
} else {
// might be negative, clip to zero
maxPosition2 = poolMargin.sub(beforeSqrt.mul(poolMargin).sqrt()).max(0);
maxPosition2 = maxPosition2.wdiv(ammMaxLeverage).wdiv(slippageFactor).wdiv(indexPrice);
}
maxPosition = maxPosition3.min(maxPosition2);
if (isLongSide) {
// long side has one more restriction than short side
int256 maxPosition1 = poolMargin.wdiv(slippageFactor).wdiv(indexPrice);
maxPosition = maxPosition.min(maxPosition1);
} else {
maxPosition = maxPosition.neg();
}
}
/**
* @dev Get pool margin of AMM, equal to 1/2 margin of AMM when AMM is unsafe.
* Marin of AMM: cash + index price1 * position1 + index price2 * position2 + ...
*
* @param context Context object of AMM, but current perpetual is not included.
* @return poolMargin The pool margin of AMM.
* @return isSafe True if AMM is safe or false.
*/
function getPoolMargin(Context memory context)
internal
pure
returns (int256 poolMargin, bool isSafe)
{
isSafe = isAMMSafe(context, 0);
if (isSafe) {
poolMargin = calculatePoolMarginWhenSafe(context, 0);
} else {
poolMargin = context.availableCash.add(context.positionValue).div(2);
require(poolMargin >= 0, "pool margin is negative when getting pool margin");
}
}
/**
* @dev Get pool margin of AMM, prepare context first.
* @param liquidityPool The liquidity pool object
* @return int256 The pool margin of AMM
* @return bool True if AMM is safe
*/
function getPoolMargin(LiquidityPoolStorage storage liquidityPool)
public
view
returns (int256, bool)
{
return getPoolMargin(prepareContext(liquidityPool));
}
}
| Get pool margin of AMM, prepare context first. liquidityPool The liquidity pool object return int256 The pool margin of AMM return bool True if AMM is safe/ | function getPoolMargin(LiquidityPoolStorage storage liquidityPool)
public
view
returns (int256, bool)
{
return getPoolMargin(prepareContext(liquidityPool));
}
| 6,381,087 |
// SPDX-License-Identifier: APACHE-2.0
pragma solidity ^0.8.14;
import "https://github.com/Block-Star-Logic/open-roles/blob/732f4f476d87bece7e53bd0873076771e90da7d5/blockchain_ethereum/solidity/v2/contracts/core/OpenRolesSecureDerivative.sol";
import "https://github.com/Block-Star-Logic/open-register/blob/03fb07e69bfdfaa6a396a063988034de65bdab3d/blockchain_ethereum/solidity/V1/interfaces/IOpenRegister.sol";
import "../interfaces/IOpenProduct.sol";
contract OpenProduct is OpenRolesSecureDerivative, IOpenProduct {
using LOpenUtilities for string;
IOpenRegister registry;
mapping(string=>address) featureADDRESSValueByFeatureName;
mapping(string=>string) featureSTRValueByFeatureName;
mapping(string=>uint256) featureUINTValueByFeatureName;
mapping(string=>bool) hasFeatureByFeatureName;
mapping(string=>string) typeByFeatureName;
mapping(string=>address) featureManagerAddressByFeature;
mapping(string=>uint256) featureFeeByFeature;
string productManagerRole = "PRODUCT_MANAGER_ROLE";
string openAdminRole = "RESERVED_OPEN_ADMIN_ROLE";
string registerCA = "RESERVED_OPEN_REGISTER_CORE";
string roleManagerCA = "RESERVED_OPEN_ROLES_CORE";
string priceKey = "PRODUCT_PRICE";
string name;
uint256 id;
struct Price {
string currency;
uint256 value;
address erc20;
}
Price price;
constructor(address _registryAddress, uint256 _id, string memory _name, uint256 _priceValue, string memory _priceCurrency, address _priceContract) {
registry = IOpenRegister(_registryAddress);
setRoleManager(registry.getAddress(roleManagerCA));
addConfigurationItem(_registryAddress);
addConfigurationItem(address(roleManager));
id = _id;
name = _name;
setPriceInternal(_priceValue, _priceCurrency, _priceContract);
}
function getId() override view external returns (uint _id){
return id;
}
function getName() override view external returns (string memory _name){
return name;
}
function getPrice() override view external returns (uint256 _price){
return (price.value);
}
function getCurrency() override view external returns (string memory _currency) {
return price.currency;
}
function getErc20() override view external returns (address _erc20) {
return price.erc20;
}
function getFeatureFee(string memory _feature) override view external returns (uint256 _fee){
return featureFeeByFeature[_feature];
}
function getFeatureUINTValue(string memory _featureName) override view external returns (uint256 _value){
return featureUINTValueByFeatureName[_featureName];
}
function getFeatureSTRValue(string memory _featureName) override view external returns (string memory _value){
return featureSTRValueByFeatureName[_featureName];
}
function getFeatureUADDRESSValue(string memory _featureName) override view external returns (address _value){
return featureADDRESSValueByFeatureName[_featureName];
}
function hasFeature(string memory _featureName) override view external returns (bool _hasFeature){
return hasFeatureByFeatureName[_featureName];
}
function getFeatureManager(string memory _feature) override view external returns (address _featureManager){
return featureManagerAddressByFeature[_feature];
}
function setFeatureUINTValue(string memory _featureName, uint256 _featureValue) external returns(bool _set) {
require(isSecure(productManagerRole, "setFeatureUINTValue")," product manager only ");
require(!hasFeatureByFeatureName[_featureName], string(" known feature of type ").append(typeByFeatureName[_featureName]));
return setFeatureUINTValueInternal(_featureName, _featureValue);
}
function setFeatureSTRValue(string memory _featureName, string memory _featureValue) external returns(bool _set) {
require(isSecure(productManagerRole, "setFeatureSTRValue")," product manager only ");
require(!hasFeatureByFeatureName[_featureName], string(" known feature of type ").append(typeByFeatureName[_featureName]));
return setFeatureSTRValueInternal(_featureName, _featureValue);
}
function setFeatureADDRESSValue(string memory _featureName, address _featureValue) external returns(bool _set) {
require(isSecure(productManagerRole, "setFeatureADDRESSValue")," product manager only ");
require(!hasFeatureByFeatureName[_featureName], string(" known feature of type ").append(typeByFeatureName[_featureName]));
return setFeatureADDRESSValueInternal(_featureName, _featureValue);
}
function removeFeatureValue(string memory _featureName) external returns (bool _removed) {
require(isSecure(productManagerRole, "removeFeatureValue")," product manager only ");
string memory featureType_ = typeByFeatureName[_featureName];
if(featureType_.isEqual("STR")) {
delete featureSTRValueByFeatureName[_featureName];
}
if(featureType_.isEqual("UINT")) {
delete featureUINTValueByFeatureName[_featureName];
}
if(featureType_.isEqual("ADDRESS")) {
delete featureADDRESSValueByFeatureName[_featureName];
}
delete hasFeatureByFeatureName[_featureName];
return true;
}
function setPrice (uint256 _priceValue, string memory _priceCurrency, address _priceContract) external returns (bool _set) {
require(isSecure(productManagerRole, "setPrice")," product manager only ");
return setPriceInternal(_priceValue, _priceCurrency, _priceContract);
}
function setFeatureFee(string memory _feature, uint256 _fee) external returns (bool _set){
require(isSecure(productManagerRole, "setFeatureFee")," product manager only ");
featureFeeByFeature[_feature] = _fee;
return true;
}
function addFeatureManager(string memory _feature, address featureManager) external returns (bool _added) {
require(isSecure(productManagerRole, "addFeatureManager")," product manager only ");
featureManagerAddressByFeature[_feature] = featureManager;
return true;
}
function removeFeatureManager(string memory _feature) external returns (bool _removed){
require(isSecure(productManagerRole, "removeFeatureManager")," product manager only ");
delete featureManagerAddressByFeature[_feature];
return true;
}
function notifyChangeOfAddress() external returns (bool _recieved){
require(isSecure(openAdminRole, "notifyChangeOfAddress")," admin only ");
registry = IOpenRegister(registry.getAddress(registerCA)); // make sure this is NOT a zero address
roleManager = IOpenRoles(registry.getAddress(roleManagerCA));
addConfigurationItem(address(registry));
addConfigurationItem(address(roleManager));
return true;
}
//=============================================== INTERNAL ==========================================
function setPriceInternal(uint256 _priceValue, string memory _priceCurrency, address _priceContract) internal returns (bool _set) {
//@todo add product admin feature
price = Price({
currency : _priceCurrency,
value : _priceValue,
erc20 : _priceContract
});
setFeatureUINTValueInternal(priceKey, _priceValue);
return true;
}
function setFeatureUINTValueInternal(string memory _name, uint256 _value) internal returns (bool _set) {
featureUINTValueByFeatureName[_name] = _value;
hasFeatureByFeatureName[_name] = true;
typeByFeatureName[_name] = "UINT";
return true;
}
function setFeatureSTRValueInternal(string memory _name, string memory _value) internal returns (bool _set) {
featureSTRValueByFeatureName[_name] = _value;
hasFeatureByFeatureName[_name] = true;
typeByFeatureName[_name] = "STR";
return true;
}
function setFeatureADDRESSValueInternal(string memory _name, address _value) internal returns (bool _set) {
featureADDRESSValueByFeatureName[_name] = _value;
hasFeatureByFeatureName[_name] = true;
typeByFeatureName[_name] = "ADDRESS";
return true;
}
} | @todo add product admin feature | function setPriceInternal(uint256 _priceValue, string memory _priceCurrency, address _priceContract) internal returns (bool _set) {
price = Price({
currency : _priceCurrency,
value : _priceValue,
erc20 : _priceContract
});
setFeatureUINTValueInternal(priceKey, _priceValue);
return true;
}
| 934,963 |
pragma solidity >=0.4.25 <0.6.0;
pragma experimental ABIEncoderV2;
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Modifiable
* @notice A contract with basic modifiers
*/
contract Modifiable {
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier notNullAddress(address _address) {
require(_address != address(0));
_;
}
modifier notThisAddress(address _address) {
require(_address != address(this));
_;
}
modifier notNullOrThisAddress(address _address) {
require(_address != address(0));
require(_address != address(this));
_;
}
modifier notSameAddresses(address _address1, address _address2) {
if (_address1 != _address2)
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SelfDestructible
* @notice Contract that allows for self-destruction
*/
contract SelfDestructible {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bool public selfDestructionDisabled;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SelfDestructionDisabledEvent(address wallet);
event TriggerSelfDestructionEvent(address wallet);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the address of the destructor role
function destructor()
public
view
returns (address);
/// @notice Disable self-destruction of this contract
/// @dev This operation can not be undone
function disableSelfDestruction()
public
{
// Require that sender is the assigned destructor
require(destructor() == msg.sender);
// Disable self-destruction
selfDestructionDisabled = true;
// Emit event
emit SelfDestructionDisabledEvent(msg.sender);
}
/// @notice Destroy this contract
function triggerSelfDestruction()
public
{
// Require that sender is the assigned destructor
require(destructor() == msg.sender);
// Require that self-destruction has not been disabled
require(!selfDestructionDisabled);
// Emit event
emit TriggerSelfDestructionEvent(msg.sender);
// Self-destruct and reward destructor
selfdestruct(msg.sender);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Ownable
* @notice A modifiable that has ownership roles
*/
contract Ownable is Modifiable, SelfDestructible {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
address public deployer;
address public operator;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetDeployerEvent(address oldDeployer, address newDeployer);
event SetOperatorEvent(address oldOperator, address newOperator);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address _deployer) internal notNullOrThisAddress(_deployer) {
deployer = _deployer;
operator = _deployer;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Return the address that is able to initiate self-destruction
function destructor()
public
view
returns (address)
{
return deployer;
}
/// @notice Set the deployer of this contract
/// @param newDeployer The address of the new deployer
function setDeployer(address newDeployer)
public
onlyDeployer
notNullOrThisAddress(newDeployer)
{
if (newDeployer != deployer) {
// Set new deployer
address oldDeployer = deployer;
deployer = newDeployer;
// Emit event
emit SetDeployerEvent(oldDeployer, newDeployer);
}
}
/// @notice Set the operator of this contract
/// @param newOperator The address of the new operator
function setOperator(address newOperator)
public
onlyOperator
notNullOrThisAddress(newOperator)
{
if (newOperator != operator) {
// Set new operator
address oldOperator = operator;
operator = newOperator;
// Emit event
emit SetOperatorEvent(oldOperator, newOperator);
}
}
/// @notice Gauge whether message sender is deployer or not
/// @return true if msg.sender is deployer, else false
function isDeployer()
internal
view
returns (bool)
{
return msg.sender == deployer;
}
/// @notice Gauge whether message sender is operator or not
/// @return true if msg.sender is operator, else false
function isOperator()
internal
view
returns (bool)
{
return msg.sender == operator;
}
/// @notice Gauge whether message sender is operator or deployer on the one hand, or none of these on these on
/// on the other hand
/// @return true if msg.sender is operator, else false
function isDeployerOrOperator()
internal
view
returns (bool)
{
return isDeployer() || isOperator();
}
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyDeployer() {
require(isDeployer());
_;
}
modifier notDeployer() {
require(!isDeployer());
_;
}
modifier onlyOperator() {
require(isOperator());
_;
}
modifier notOperator() {
require(!isOperator());
_;
}
modifier onlyDeployerOrOperator() {
require(isDeployerOrOperator());
_;
}
modifier notDeployerOrOperator() {
require(!isDeployerOrOperator());
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Servable
* @notice An ownable that contains registered services and their actions
*/
contract Servable is Ownable {
//
// Types
// -----------------------------------------------------------------------------------------------------------------
struct ServiceInfo {
bool registered;
uint256 activationTimestamp;
mapping(bytes32 => bool) actionsEnabledMap;
bytes32[] actionsList;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => ServiceInfo) internal registeredServicesMap;
uint256 public serviceActivationTimeout;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event ServiceActivationTimeoutEvent(uint256 timeoutInSeconds);
event RegisterServiceEvent(address service);
event RegisterServiceDeferredEvent(address service, uint256 timeout);
event DeregisterServiceEvent(address service);
event EnableServiceActionEvent(address service, string action);
event DisableServiceActionEvent(address service, string action);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the service activation timeout
/// @param timeoutInSeconds The set timeout in unit of seconds
function setServiceActivationTimeout(uint256 timeoutInSeconds)
public
onlyDeployer
{
serviceActivationTimeout = timeoutInSeconds;
// Emit event
emit ServiceActivationTimeoutEvent(timeoutInSeconds);
}
/// @notice Register a service contract whose activation is immediate
/// @param service The address of the service contract to be registered
function registerService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
_registerService(service, 0);
// Emit event
emit RegisterServiceEvent(service);
}
/// @notice Register a service contract whose activation is deferred by the service activation timeout
/// @param service The address of the service contract to be registered
function registerServiceDeferred(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
_registerService(service, serviceActivationTimeout);
// Emit event
emit RegisterServiceDeferredEvent(service, serviceActivationTimeout);
}
/// @notice Deregister a service contract
/// @param service The address of the service contract to be deregistered
function deregisterService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(registeredServicesMap[service].registered);
registeredServicesMap[service].registered = false;
// Emit event
emit DeregisterServiceEvent(service);
}
/// @notice Enable a named action in an already registered service contract
/// @param service The address of the registered service contract
/// @param action The name of the action to be enabled
function enableServiceAction(address service, string memory action)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(registeredServicesMap[service].registered);
bytes32 actionHash = hashString(action);
require(!registeredServicesMap[service].actionsEnabledMap[actionHash]);
registeredServicesMap[service].actionsEnabledMap[actionHash] = true;
registeredServicesMap[service].actionsList.push(actionHash);
// Emit event
emit EnableServiceActionEvent(service, action);
}
/// @notice Enable a named action in a service contract
/// @param service The address of the service contract
/// @param action The name of the action to be disabled
function disableServiceAction(address service, string memory action)
public
onlyDeployer
notNullOrThisAddress(service)
{
bytes32 actionHash = hashString(action);
require(registeredServicesMap[service].actionsEnabledMap[actionHash]);
registeredServicesMap[service].actionsEnabledMap[actionHash] = false;
// Emit event
emit DisableServiceActionEvent(service, action);
}
/// @notice Gauge whether a service contract is registered
/// @param service The address of the service contract
/// @return true if service is registered, else false
function isRegisteredService(address service)
public
view
returns (bool)
{
return registeredServicesMap[service].registered;
}
/// @notice Gauge whether a service contract is registered and active
/// @param service The address of the service contract
/// @return true if service is registered and activate, else false
function isRegisteredActiveService(address service)
public
view
returns (bool)
{
return isRegisteredService(service) && block.timestamp >= registeredServicesMap[service].activationTimestamp;
}
/// @notice Gauge whether a service contract action is enabled which implies also registered and active
/// @param service The address of the service contract
/// @param action The name of action
function isEnabledServiceAction(address service, string memory action)
public
view
returns (bool)
{
bytes32 actionHash = hashString(action);
return isRegisteredActiveService(service) && registeredServicesMap[service].actionsEnabledMap[actionHash];
}
//
// Internal functions
// -----------------------------------------------------------------------------------------------------------------
function hashString(string memory _string)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_string));
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _registerService(address service, uint256 timeout)
private
{
if (!registeredServicesMap[service].registered) {
registeredServicesMap[service].registered = true;
registeredServicesMap[service].activationTimestamp = block.timestamp + timeout;
}
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyActiveService() {
require(isRegisteredActiveService(msg.sender));
_;
}
modifier onlyEnabledServiceAction(string memory action) {
require(isEnabledServiceAction(msg.sender, action));
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Community vote
* @notice An oracle for relevant decisions made by the community.
*/
contract CommunityVote is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => bool) doubleSpenderByWallet;
uint256 maxDriipNonce;
uint256 maxNullNonce;
bool dataAvailable;
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
dataAvailable = true;
}
//
// Results functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the double spender status of given wallet
/// @param wallet The wallet address for which to check double spender status
/// @return true if wallet is double spender, false otherwise
function isDoubleSpenderWallet(address wallet)
public
view
returns (bool)
{
return doubleSpenderByWallet[wallet];
}
/// @notice Get the max driip nonce to be accepted in settlements
/// @return the max driip nonce
function getMaxDriipNonce()
public
view
returns (uint256)
{
return maxDriipNonce;
}
/// @notice Get the max null settlement nonce to be accepted in settlements
/// @return the max driip nonce
function getMaxNullNonce()
public
view
returns (uint256)
{
return maxNullNonce;
}
/// @notice Get the data availability status
/// @return true if data is available
function isDataAvailable()
public
view
returns (bool)
{
return dataAvailable;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title CommunityVotable
* @notice An ownable that has a community vote property
*/
contract CommunityVotable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
CommunityVote public communityVote;
bool public communityVoteFrozen;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetCommunityVoteEvent(CommunityVote oldCommunityVote, CommunityVote newCommunityVote);
event FreezeCommunityVoteEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the community vote contract
/// @param newCommunityVote The (address of) CommunityVote contract instance
function setCommunityVote(CommunityVote newCommunityVote)
public
onlyDeployer
notNullAddress(address(newCommunityVote))
notSameAddresses(address(newCommunityVote), address(communityVote))
{
require(!communityVoteFrozen, "Community vote frozen [CommunityVotable.sol:41]");
// Set new community vote
CommunityVote oldCommunityVote = communityVote;
communityVote = newCommunityVote;
// Emit event
emit SetCommunityVoteEvent(oldCommunityVote, newCommunityVote);
}
/// @notice Freeze the community vote from further updates
/// @dev This operation can not be undone
function freezeCommunityVote()
public
onlyDeployer
{
communityVoteFrozen = true;
// Emit event
emit FreezeCommunityVoteEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier communityVoteInitialized() {
require(address(communityVote) != address(0), "Community vote not initialized [CommunityVotable.sol:67]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Beneficiary
* @notice A recipient of ethers and tokens
*/
contract Beneficiary {
/// @notice Receive ethers to the given wallet's given balance type
/// @param wallet The address of the concerned wallet
/// @param balanceType The target balance type of the wallet
function receiveEthersTo(address wallet, string memory balanceType)
public
payable;
/// @notice Receive token to the given wallet's given balance type
/// @dev The wallet must approve of the token transfer prior to calling this function
/// @param wallet The address of the concerned wallet
/// @param balanceType The target balance type of the wallet
/// @param amount The amount to deposit
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function receiveTokensTo(address wallet, string memory balanceType, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public;
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title MonetaryTypesLib
* @dev Monetary data types
*/
library MonetaryTypesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Currency {
address ct;
uint256 id;
}
struct Figure {
int256 amount;
Currency currency;
}
struct NoncedAmount {
uint256 nonce;
int256 amount;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title AccrualBeneficiary
* @notice A beneficiary of accruals
*/
contract AccrualBeneficiary is Beneficiary {
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
event CloseAccrualPeriodEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function closeAccrualPeriod(MonetaryTypesLib.Currency[] memory)
public
{
emit CloseAccrualPeriodEvent();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Benefactor
* @notice An ownable that contains registered beneficiaries
*/
contract Benefactor is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
Beneficiary[] public beneficiaries;
mapping(address => uint256) public beneficiaryIndexByAddress;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event RegisterBeneficiaryEvent(Beneficiary beneficiary);
event DeregisterBeneficiaryEvent(Beneficiary beneficiary);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Register the given beneficiary
/// @param beneficiary Address of beneficiary to be registered
function registerBeneficiary(Beneficiary beneficiary)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
address _beneficiary = address(beneficiary);
if (beneficiaryIndexByAddress[_beneficiary] > 0)
return false;
beneficiaries.push(beneficiary);
beneficiaryIndexByAddress[_beneficiary] = beneficiaries.length;
// Emit event
emit RegisterBeneficiaryEvent(beneficiary);
return true;
}
/// @notice Deregister the given beneficiary
/// @param beneficiary Address of beneficiary to be deregistered
function deregisterBeneficiary(Beneficiary beneficiary)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
address _beneficiary = address(beneficiary);
if (beneficiaryIndexByAddress[_beneficiary] == 0)
return false;
uint256 idx = beneficiaryIndexByAddress[_beneficiary] - 1;
if (idx < beneficiaries.length - 1) {
// Remap the last item in the array to this index
beneficiaries[idx] = beneficiaries[beneficiaries.length - 1];
beneficiaryIndexByAddress[address(beneficiaries[idx])] = idx + 1;
}
beneficiaries.length--;
beneficiaryIndexByAddress[_beneficiary] = 0;
// Emit event
emit DeregisterBeneficiaryEvent(beneficiary);
return true;
}
/// @notice Gauge whether the given address is the one of a registered beneficiary
/// @param beneficiary Address of beneficiary
/// @return true if beneficiary is registered, else false
function isRegisteredBeneficiary(Beneficiary beneficiary)
public
view
returns (bool)
{
return beneficiaryIndexByAddress[address(beneficiary)] > 0;
}
/// @notice Get the count of registered beneficiaries
/// @return The count of registered beneficiaries
function registeredBeneficiariesCount()
public
view
returns (uint256)
{
return beneficiaries.length;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library
*/
/**
* @title SafeMathIntLib
* @dev Math operations with safety checks that throw on error
*/
library SafeMathIntLib {
int256 constant INT256_MIN = int256((uint256(1) << 255));
int256 constant INT256_MAX = int256(~((uint256(1) << 255)));
//
//Functions below accept positive and negative integers and result must not overflow.
//
function div(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a != INT256_MIN || b != - 1);
return a / b;
}
function mul(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a != - 1 || b != INT256_MIN);
// overflow
require(b != - 1 || a != INT256_MIN);
// overflow
int256 c = a * b;
require((b == 0) || (c / b == a));
return c;
}
function sub(int256 a, int256 b)
internal
pure
returns (int256)
{
require((b >= 0 && a - b <= a) || (b < 0 && a - b > a));
return a - b;
}
function add(int256 a, int256 b)
internal
pure
returns (int256)
{
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
//
//Functions below only accept positive integers and result must be greater or equal to zero too.
//
function div_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b > 0);
return a / b;
}
function mul_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0);
int256 c = a * b;
require(a == 0 || c / a == b);
require(c >= 0);
return c;
}
function sub_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0 && b <= a);
return a - b;
}
function add_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0);
int256 c = a + b;
require(c >= a);
return c;
}
//
//Conversion and validation functions.
//
function abs(int256 a)
public
pure
returns (int256)
{
return a < 0 ? neg(a) : a;
}
function neg(int256 a)
public
pure
returns (int256)
{
return mul(a, - 1);
}
function toNonZeroInt256(uint256 a)
public
pure
returns (int256)
{
require(a > 0 && a < (uint256(1) << 255));
return int256(a);
}
function toInt256(uint256 a)
public
pure
returns (int256)
{
require(a >= 0 && a < (uint256(1) << 255));
return int256(a);
}
function toUInt256(int256 a)
public
pure
returns (uint256)
{
require(a >= 0);
return uint256(a);
}
function isNonZeroPositiveInt256(int256 a)
public
pure
returns (bool)
{
return (a > 0);
}
function isPositiveInt256(int256 a)
public
pure
returns (bool)
{
return (a >= 0);
}
function isNonZeroNegativeInt256(int256 a)
public
pure
returns (bool)
{
return (a < 0);
}
function isNegativeInt256(int256 a)
public
pure
returns (bool)
{
return (a <= 0);
}
//
//Clamping functions.
//
function clamp(int256 a, int256 min, int256 max)
public
pure
returns (int256)
{
if (a < min)
return min;
return (a > max) ? max : a;
}
function clampMin(int256 a, int256 min)
public
pure
returns (int256)
{
return (a < min) ? min : a;
}
function clampMax(int256 a, int256 max)
public
pure
returns (int256)
{
return (a > max) ? max : a;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library ConstantsLib {
// Get the fraction that represents the entirety, equivalent of 100%
function PARTS_PER()
public
pure
returns (int256)
{
return 1e18;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title AccrualBenefactor
* @notice A benefactor whose registered beneficiaries obtain a predefined fraction of total amount
*/
contract AccrualBenefactor is Benefactor {
using SafeMathIntLib for int256;
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => int256) private _beneficiaryFractionMap;
int256 public totalBeneficiaryFraction;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event RegisterAccrualBeneficiaryEvent(Beneficiary beneficiary, int256 fraction);
event DeregisterAccrualBeneficiaryEvent(Beneficiary beneficiary);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Register the given accrual beneficiary for the entirety fraction
/// @param beneficiary Address of accrual beneficiary to be registered
function registerBeneficiary(Beneficiary beneficiary)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
return registerFractionalBeneficiary(AccrualBeneficiary(address(beneficiary)), ConstantsLib.PARTS_PER());
}
/// @notice Register the given accrual beneficiary for the given fraction
/// @param beneficiary Address of accrual beneficiary to be registered
/// @param fraction Fraction of benefits to be given
function registerFractionalBeneficiary(AccrualBeneficiary beneficiary, int256 fraction)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
require(fraction > 0, "Fraction not strictly positive [AccrualBenefactor.sol:59]");
require(
totalBeneficiaryFraction.add(fraction) <= ConstantsLib.PARTS_PER(),
"Total beneficiary fraction out of bounds [AccrualBenefactor.sol:60]"
);
if (!super.registerBeneficiary(beneficiary))
return false;
_beneficiaryFractionMap[address(beneficiary)] = fraction;
totalBeneficiaryFraction = totalBeneficiaryFraction.add(fraction);
// Emit event
emit RegisterAccrualBeneficiaryEvent(beneficiary, fraction);
return true;
}
/// @notice Deregister the given accrual beneficiary
/// @param beneficiary Address of accrual beneficiary to be deregistered
function deregisterBeneficiary(Beneficiary beneficiary)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
if (!super.deregisterBeneficiary(beneficiary))
return false;
address _beneficiary = address(beneficiary);
totalBeneficiaryFraction = totalBeneficiaryFraction.sub(_beneficiaryFractionMap[_beneficiary]);
_beneficiaryFractionMap[_beneficiary] = 0;
// Emit event
emit DeregisterAccrualBeneficiaryEvent(beneficiary);
return true;
}
/// @notice Get the fraction of benefits that is granted the given accrual beneficiary
/// @param beneficiary Address of accrual beneficiary
/// @return The beneficiary's fraction
function beneficiaryFraction(AccrualBeneficiary beneficiary)
public
view
returns (int256)
{
return _beneficiaryFractionMap[address(beneficiary)];
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferController
* @notice A base contract to handle transfers of different currency types
*/
contract TransferController {
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event CurrencyTransferred(address from, address to, uint256 value,
address currencyCt, uint256 currencyId);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function isFungible()
public
view
returns (bool);
function standard()
public
view
returns (string memory);
/// @notice MUST be called with DELEGATECALL
function receive(address from, address to, uint256 value, address currencyCt, uint256 currencyId)
public;
/// @notice MUST be called with DELEGATECALL
function approve(address to, uint256 value, address currencyCt, uint256 currencyId)
public;
/// @notice MUST be called with DELEGATECALL
function dispatch(address from, address to, uint256 value, address currencyCt, uint256 currencyId)
public;
//----------------------------------------
function getReceiveSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("receive(address,address,uint256,address,uint256)"));
}
function getApproveSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("approve(address,uint256,address,uint256)"));
}
function getDispatchSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("dispatch(address,address,uint256,address,uint256)"));
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferControllerManager
* @notice Handles the management of transfer controllers
*/
contract TransferControllerManager is Ownable {
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
struct CurrencyInfo {
bytes32 standard;
bool blacklisted;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(bytes32 => address) public registeredTransferControllers;
mapping(address => CurrencyInfo) public registeredCurrencies;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event RegisterTransferControllerEvent(string standard, address controller);
event ReassociateTransferControllerEvent(string oldStandard, string newStandard, address controller);
event RegisterCurrencyEvent(address currencyCt, string standard);
event DeregisterCurrencyEvent(address currencyCt);
event BlacklistCurrencyEvent(address currencyCt);
event WhitelistCurrencyEvent(address currencyCt);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function registerTransferController(string calldata standard, address controller)
external
onlyDeployer
notNullAddress(controller)
{
require(bytes(standard).length > 0, "Empty standard not supported [TransferControllerManager.sol:58]");
bytes32 standardHash = keccak256(abi.encodePacked(standard));
registeredTransferControllers[standardHash] = controller;
// Emit event
emit RegisterTransferControllerEvent(standard, controller);
}
function reassociateTransferController(string calldata oldStandard, string calldata newStandard, address controller)
external
onlyDeployer
notNullAddress(controller)
{
require(bytes(newStandard).length > 0, "Empty new standard not supported [TransferControllerManager.sol:72]");
bytes32 oldStandardHash = keccak256(abi.encodePacked(oldStandard));
bytes32 newStandardHash = keccak256(abi.encodePacked(newStandard));
require(registeredTransferControllers[oldStandardHash] != address(0), "Old standard not registered [TransferControllerManager.sol:76]");
require(registeredTransferControllers[newStandardHash] == address(0), "New standard previously registered [TransferControllerManager.sol:77]");
registeredTransferControllers[newStandardHash] = registeredTransferControllers[oldStandardHash];
registeredTransferControllers[oldStandardHash] = address(0);
// Emit event
emit ReassociateTransferControllerEvent(oldStandard, newStandard, controller);
}
function registerCurrency(address currencyCt, string calldata standard)
external
onlyOperator
notNullAddress(currencyCt)
{
require(bytes(standard).length > 0, "Empty standard not supported [TransferControllerManager.sol:91]");
bytes32 standardHash = keccak256(abi.encodePacked(standard));
require(registeredCurrencies[currencyCt].standard == bytes32(0), "Currency previously registered [TransferControllerManager.sol:94]");
registeredCurrencies[currencyCt].standard = standardHash;
// Emit event
emit RegisterCurrencyEvent(currencyCt, standard);
}
function deregisterCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != 0, "Currency not registered [TransferControllerManager.sol:106]");
registeredCurrencies[currencyCt].standard = bytes32(0);
registeredCurrencies[currencyCt].blacklisted = false;
// Emit event
emit DeregisterCurrencyEvent(currencyCt);
}
function blacklistCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:119]");
registeredCurrencies[currencyCt].blacklisted = true;
// Emit event
emit BlacklistCurrencyEvent(currencyCt);
}
function whitelistCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:131]");
registeredCurrencies[currencyCt].blacklisted = false;
// Emit event
emit WhitelistCurrencyEvent(currencyCt);
}
/**
@notice The provided standard takes priority over assigned interface to currency
*/
function transferController(address currencyCt, string memory standard)
public
view
returns (TransferController)
{
if (bytes(standard).length > 0) {
bytes32 standardHash = keccak256(abi.encodePacked(standard));
require(registeredTransferControllers[standardHash] != address(0), "Standard not registered [TransferControllerManager.sol:150]");
return TransferController(registeredTransferControllers[standardHash]);
}
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:154]");
require(!registeredCurrencies[currencyCt].blacklisted, "Currency blacklisted [TransferControllerManager.sol:155]");
address controllerAddress = registeredTransferControllers[registeredCurrencies[currencyCt].standard];
require(controllerAddress != address(0), "No matching transfer controller [TransferControllerManager.sol:158]");
return TransferController(controllerAddress);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferControllerManageable
* @notice An ownable with a transfer controller manager
*/
contract TransferControllerManageable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
TransferControllerManager public transferControllerManager;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetTransferControllerManagerEvent(TransferControllerManager oldTransferControllerManager,
TransferControllerManager newTransferControllerManager);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the currency manager contract
/// @param newTransferControllerManager The (address of) TransferControllerManager contract instance
function setTransferControllerManager(TransferControllerManager newTransferControllerManager)
public
onlyDeployer
notNullAddress(address(newTransferControllerManager))
notSameAddresses(address(newTransferControllerManager), address(transferControllerManager))
{
//set new currency manager
TransferControllerManager oldTransferControllerManager = transferControllerManager;
transferControllerManager = newTransferControllerManager;
// Emit event
emit SetTransferControllerManagerEvent(oldTransferControllerManager, newTransferControllerManager);
}
/// @notice Get the transfer controller of the given currency contract address and standard
function transferController(address currencyCt, string memory standard)
internal
view
returns (TransferController)
{
return transferControllerManager.transferController(currencyCt, standard);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier transferControllerManagerInitialized() {
require(address(transferControllerManager) != address(0), "Transfer controller manager not initialized [TransferControllerManageable.sol:63]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library
*/
/**
* @title SafeMathUintLib
* @dev Math operations with safety checks that throw on error
*/
library SafeMathUintLib {
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;
}
//
//Clamping functions.
//
function clamp(uint256 a, uint256 min, uint256 max)
public
pure
returns (uint256)
{
return (a > max) ? max : ((a < min) ? min : a);
}
function clampMin(uint256 a, uint256 min)
public
pure
returns (uint256)
{
return (a < min) ? min : a;
}
function clampMax(uint256 a, uint256 max)
public
pure
returns (uint256)
{
return (a > max) ? max : a;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library CurrenciesLib {
using SafeMathUintLib for uint256;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Currencies {
MonetaryTypesLib.Currency[] currencies;
mapping(address => mapping(uint256 => uint256)) indexByCurrency;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function add(Currencies storage self, address currencyCt, uint256 currencyId)
internal
{
// Index is 1-based
if (0 == self.indexByCurrency[currencyCt][currencyId]) {
self.currencies.push(MonetaryTypesLib.Currency(currencyCt, currencyId));
self.indexByCurrency[currencyCt][currencyId] = self.currencies.length;
}
}
function removeByCurrency(Currencies storage self, address currencyCt, uint256 currencyId)
internal
{
// Index is 1-based
uint256 index = self.indexByCurrency[currencyCt][currencyId];
if (0 < index)
removeByIndex(self, index - 1);
}
function removeByIndex(Currencies storage self, uint256 index)
internal
{
require(index < self.currencies.length, "Index out of bounds [CurrenciesLib.sol:51]");
address currencyCt = self.currencies[index].ct;
uint256 currencyId = self.currencies[index].id;
if (index < self.currencies.length - 1) {
self.currencies[index] = self.currencies[self.currencies.length - 1];
self.indexByCurrency[self.currencies[index].ct][self.currencies[index].id] = index + 1;
}
self.currencies.length--;
self.indexByCurrency[currencyCt][currencyId] = 0;
}
function count(Currencies storage self)
internal
view
returns (uint256)
{
return self.currencies.length;
}
function has(Currencies storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return 0 != self.indexByCurrency[currencyCt][currencyId];
}
function getByIndex(Currencies storage self, uint256 index)
internal
view
returns (MonetaryTypesLib.Currency memory)
{
require(index < self.currencies.length, "Index out of bounds [CurrenciesLib.sol:85]");
return self.currencies[index];
}
function getByIndices(Currencies storage self, uint256 low, uint256 up)
internal
view
returns (MonetaryTypesLib.Currency[] memory)
{
require(0 < self.currencies.length, "No currencies found [CurrenciesLib.sol:94]");
require(low <= up, "Bounds parameters mismatch [CurrenciesLib.sol:95]");
up = up.clampMax(self.currencies.length - 1);
MonetaryTypesLib.Currency[] memory _currencies = new MonetaryTypesLib.Currency[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_currencies[i - low] = self.currencies[i];
return _currencies;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library FungibleBalanceLib {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Record {
int256 amount;
uint256 blockNumber;
}
struct Balance {
mapping(address => mapping(uint256 => int256)) amountByCurrency;
mapping(address => mapping(uint256 => Record[])) recordsByCurrency;
CurrenciesLib.Currencies inUseCurrencies;
CurrenciesLib.Currencies everUsedCurrencies;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function get(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256)
{
return self.amountByCurrency[currencyCt][currencyId];
}
function getByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256)
{
(int256 amount,) = recordByBlockNumber(self, currencyCt, currencyId, blockNumber);
return amount;
}
function set(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = amount;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function add(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function sub(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function transfer(Balance storage _from, Balance storage _to, int256 amount,
address currencyCt, uint256 currencyId)
internal
{
sub(_from, amount, currencyCt, currencyId);
add(_to, amount, currencyCt, currencyId);
}
function add_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add_nn(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function sub_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub_nn(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function transfer_nn(Balance storage _from, Balance storage _to, int256 amount,
address currencyCt, uint256 currencyId)
internal
{
sub_nn(_from, amount, currencyCt, currencyId);
add_nn(_to, amount, currencyCt, currencyId);
}
function recordsCount(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.recordsByCurrency[currencyCt][currencyId].length;
}
function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256, uint256)
{
uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber);
return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (0, 0);
}
function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index)
internal
view
returns (int256, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (0, 0);
index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][index];
return (record.amount, record.blockNumber);
}
function lastRecord(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (0, 0);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1];
return (record.amount, record.blockNumber);
}
function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.inUseCurrencies.has(currencyCt, currencyId);
}
function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.everUsedCurrencies.has(currencyCt, currencyId);
}
function updateCurrencies(Balance storage self, address currencyCt, uint256 currencyId)
internal
{
if (0 == self.amountByCurrency[currencyCt][currencyId] && self.inUseCurrencies.has(currencyCt, currencyId))
self.inUseCurrencies.removeByCurrency(currencyCt, currencyId);
else if (!self.inUseCurrencies.has(currencyCt, currencyId)) {
self.inUseCurrencies.add(currencyCt, currencyId);
self.everUsedCurrencies.add(currencyCt, currencyId);
}
}
function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return 0;
for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--)
if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber)
return i;
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library TxHistoryLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct AssetEntry {
int256 amount;
uint256 blockNumber;
address currencyCt; //0 for ethers
uint256 currencyId;
}
struct TxHistory {
AssetEntry[] deposits;
mapping(address => mapping(uint256 => AssetEntry[])) currencyDeposits;
AssetEntry[] withdrawals;
mapping(address => mapping(uint256 => AssetEntry[])) currencyWithdrawals;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function addDeposit(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
AssetEntry memory deposit = AssetEntry(amount, block.number, currencyCt, currencyId);
self.deposits.push(deposit);
self.currencyDeposits[currencyCt][currencyId].push(deposit);
}
function addWithdrawal(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
AssetEntry memory withdrawal = AssetEntry(amount, block.number, currencyCt, currencyId);
self.withdrawals.push(withdrawal);
self.currencyWithdrawals[currencyCt][currencyId].push(withdrawal);
}
//----
function deposit(TxHistory storage self, uint index)
internal
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
require(index < self.deposits.length, "Index ouf of bounds [TxHistoryLib.sol:56]");
amount = self.deposits[index].amount;
blockNumber = self.deposits[index].blockNumber;
currencyCt = self.deposits[index].currencyCt;
currencyId = self.deposits[index].currencyId;
}
function depositsCount(TxHistory storage self)
internal
view
returns (uint256)
{
return self.deposits.length;
}
function currencyDeposit(TxHistory storage self, address currencyCt, uint256 currencyId, uint index)
internal
view
returns (int256 amount, uint256 blockNumber)
{
require(index < self.currencyDeposits[currencyCt][currencyId].length, "Index out of bounds [TxHistoryLib.sol:77]");
amount = self.currencyDeposits[currencyCt][currencyId][index].amount;
blockNumber = self.currencyDeposits[currencyCt][currencyId][index].blockNumber;
}
function currencyDepositsCount(TxHistory storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.currencyDeposits[currencyCt][currencyId].length;
}
//----
function withdrawal(TxHistory storage self, uint index)
internal
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
require(index < self.withdrawals.length, "Index out of bounds [TxHistoryLib.sol:98]");
amount = self.withdrawals[index].amount;
blockNumber = self.withdrawals[index].blockNumber;
currencyCt = self.withdrawals[index].currencyCt;
currencyId = self.withdrawals[index].currencyId;
}
function withdrawalsCount(TxHistory storage self)
internal
view
returns (uint256)
{
return self.withdrawals.length;
}
function currencyWithdrawal(TxHistory storage self, address currencyCt, uint256 currencyId, uint index)
internal
view
returns (int256 amount, uint256 blockNumber)
{
require(index < self.currencyWithdrawals[currencyCt][currencyId].length, "Index out of bounds [TxHistoryLib.sol:119]");
amount = self.currencyWithdrawals[currencyCt][currencyId][index].amount;
blockNumber = self.currencyWithdrawals[currencyCt][currencyId][index].blockNumber;
}
function currencyWithdrawalsCount(TxHistory storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.currencyWithdrawals[currencyCt][currencyId].length;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title RevenueFund
* @notice The target of all revenue earned in driip settlements and from which accrued revenue is split amongst
* accrual beneficiaries.
*/
contract RevenueFund is Ownable, AccrualBeneficiary, AccrualBenefactor, TransferControllerManageable {
using FungibleBalanceLib for FungibleBalanceLib.Balance;
using TxHistoryLib for TxHistoryLib.TxHistory;
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
FungibleBalanceLib.Balance periodAccrual;
CurrenciesLib.Currencies periodCurrencies;
FungibleBalanceLib.Balance aggregateAccrual;
CurrenciesLib.Currencies aggregateCurrencies;
TxHistoryLib.TxHistory private txHistory;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event ReceiveEvent(address from, int256 amount, address currencyCt, uint256 currencyId);
event CloseAccrualPeriodEvent();
event RegisterServiceEvent(address service);
event DeregisterServiceEvent(address service);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Fallback function that deposits ethers
function() external payable {
receiveEthersTo(msg.sender, "");
}
/// @notice Receive ethers to
/// @param wallet The concerned wallet address
function receiveEthersTo(address wallet, string memory)
public
payable
{
int256 amount = SafeMathIntLib.toNonZeroInt256(msg.value);
// Add to balances
periodAccrual.add(amount, address(0), 0);
aggregateAccrual.add(amount, address(0), 0);
// Add currency to stores of currencies
periodCurrencies.add(address(0), 0);
aggregateCurrencies.add(address(0), 0);
// Add to transaction history
txHistory.addDeposit(amount, address(0), 0);
// Emit event
emit ReceiveEvent(wallet, amount, address(0), 0);
}
/// @notice Receive tokens
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokens(string memory balanceType, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public
{
receiveTokensTo(msg.sender, balanceType, amount, currencyCt, currencyId, standard);
}
/// @notice Receive tokens to
/// @param wallet The address of the concerned wallet
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokensTo(address wallet, string memory, int256 amount,
address currencyCt, uint256 currencyId, string memory standard)
public
{
require(amount.isNonZeroPositiveInt256(), "Amount not strictly positive [RevenueFund.sol:115]");
// Execute transfer
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId
)
);
require(success, "Reception by controller failed [RevenueFund.sol:124]");
// Add to balances
periodAccrual.add(amount, currencyCt, currencyId);
aggregateAccrual.add(amount, currencyCt, currencyId);
// Add currency to stores of currencies
periodCurrencies.add(currencyCt, currencyId);
aggregateCurrencies.add(currencyCt, currencyId);
// Add to transaction history
txHistory.addDeposit(amount, currencyCt, currencyId);
// Emit event
emit ReceiveEvent(wallet, amount, currencyCt, currencyId);
}
/// @notice Get the period accrual balance of the given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The current period's accrual balance
function periodAccrualBalance(address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return periodAccrual.get(currencyCt, currencyId);
}
/// @notice Get the aggregate accrual balance of the given currency, including contribution from the
/// current accrual period
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The aggregate accrual balance
function aggregateAccrualBalance(address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return aggregateAccrual.get(currencyCt, currencyId);
}
/// @notice Get the count of currencies recorded in the accrual period
/// @return The number of currencies in the current accrual period
function periodCurrenciesCount()
public
view
returns (uint256)
{
return periodCurrencies.count();
}
/// @notice Get the currencies with indices in the given range that have been recorded in the current accrual period
/// @param low The lower currency index
/// @param up The upper currency index
/// @return The currencies of the given index range in the current accrual period
function periodCurrenciesByIndices(uint256 low, uint256 up)
public
view
returns (MonetaryTypesLib.Currency[] memory)
{
return periodCurrencies.getByIndices(low, up);
}
/// @notice Get the count of currencies ever recorded
/// @return The number of currencies ever recorded
function aggregateCurrenciesCount()
public
view
returns (uint256)
{
return aggregateCurrencies.count();
}
/// @notice Get the currencies with indices in the given range that have ever been recorded
/// @param low The lower currency index
/// @param up The upper currency index
/// @return The currencies of the given index range ever recorded
function aggregateCurrenciesByIndices(uint256 low, uint256 up)
public
view
returns (MonetaryTypesLib.Currency[] memory)
{
return aggregateCurrencies.getByIndices(low, up);
}
/// @notice Get the count of deposits
/// @return The count of deposits
function depositsCount()
public
view
returns (uint256)
{
return txHistory.depositsCount();
}
/// @notice Get the deposit at the given index
/// @return The deposit at the given index
function deposit(uint index)
public
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
return txHistory.deposit(index);
}
/// @notice Close the current accrual period of the given currencies
/// @param currencies The concerned currencies
function closeAccrualPeriod(MonetaryTypesLib.Currency[] memory currencies)
public
onlyOperator
{
require(
ConstantsLib.PARTS_PER() == totalBeneficiaryFraction,
"Total beneficiary fraction out of bounds [RevenueFund.sol:236]"
);
// Execute transfer
for (uint256 i = 0; i < currencies.length; i++) {
MonetaryTypesLib.Currency memory currency = currencies[i];
int256 remaining = periodAccrual.get(currency.ct, currency.id);
if (0 >= remaining)
continue;
for (uint256 j = 0; j < beneficiaries.length; j++) {
AccrualBeneficiary beneficiary = AccrualBeneficiary(address(beneficiaries[j]));
if (beneficiaryFraction(beneficiary) > 0) {
int256 transferable = periodAccrual.get(currency.ct, currency.id)
.mul(beneficiaryFraction(beneficiary))
.div(ConstantsLib.PARTS_PER());
if (transferable > remaining)
transferable = remaining;
if (transferable > 0) {
// Transfer ETH to the beneficiary
if (currency.ct == address(0))
beneficiary.receiveEthersTo.value(uint256(transferable))(address(0), "");
// Transfer token to the beneficiary
else {
TransferController controller = transferController(currency.ct, "");
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getApproveSignature(), address(beneficiary), uint256(transferable), currency.ct, currency.id
)
);
require(success, "Approval by controller failed [RevenueFund.sol:274]");
beneficiary.receiveTokensTo(address(0), "", transferable, currency.ct, currency.id, "");
}
remaining = remaining.sub(transferable);
}
}
}
// Roll over remaining to next accrual period
periodAccrual.set(remaining, currency.ct, currency.id);
}
// Close accrual period of accrual beneficiaries
for (uint256 j = 0; j < beneficiaries.length; j++) {
AccrualBeneficiary beneficiary = AccrualBeneficiary(address(beneficiaries[j]));
// Require that beneficiary fraction is strictly positive
if (0 >= beneficiaryFraction(beneficiary))
continue;
// Close accrual period
beneficiary.closeAccrualPeriod(currencies);
}
// Emit event
emit CloseAccrualPeriodEvent();
}
}
/**
* Strings Library
*
* In summary this is a simple library of string functions which make simple
* string operations less tedious in solidity.
*
* Please be aware these functions can be quite gas heavy so use them only when
* necessary not to clog the blockchain with expensive transactions.
*
* @author James Lockhart <[email protected]>
*/
library Strings {
/**
* Concat (High gas cost)
*
* Appends two strings together and returns a new value
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string which will be the concatenated
* prefix
* @param _value The value to be the concatenated suffix
* @return string The resulting string from combinging the base and value
*/
function concat(string memory _base, string memory _value)
internal
pure
returns (string memory) {
bytes memory _baseBytes = bytes(_base);
bytes memory _valueBytes = bytes(_value);
assert(_valueBytes.length > 0);
string memory _tmpValue = new string(_baseBytes.length +
_valueBytes.length);
bytes memory _newValue = bytes(_tmpValue);
uint i;
uint j;
for (i = 0; i < _baseBytes.length; i++) {
_newValue[j++] = _baseBytes[i];
}
for (i = 0; i < _valueBytes.length; i++) {
_newValue[j++] = _valueBytes[i];
}
return string(_newValue);
}
/**
* Index Of
*
* Locates and returns the position of a character within a string
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string acting as the haystack to be
* searched
* @param _value The needle to search for, at present this is currently
* limited to one character
* @return int The position of the needle starting from 0 and returning -1
* in the case of no matches found
*/
function indexOf(string memory _base, string memory _value)
internal
pure
returns (int) {
return _indexOf(_base, _value, 0);
}
/**
* Index Of
*
* Locates and returns the position of a character within a string starting
* from a defined offset
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string acting as the haystack to be
* searched
* @param _value The needle to search for, at present this is currently
* limited to one character
* @param _offset The starting point to start searching from which can start
* from 0, but must not exceed the length of the string
* @return int The position of the needle starting from 0 and returning -1
* in the case of no matches found
*/
function _indexOf(string memory _base, string memory _value, uint _offset)
internal
pure
returns (int) {
bytes memory _baseBytes = bytes(_base);
bytes memory _valueBytes = bytes(_value);
assert(_valueBytes.length == 1);
for (uint i = _offset; i < _baseBytes.length; i++) {
if (_baseBytes[i] == _valueBytes[0]) {
return int(i);
}
}
return -1;
}
/**
* Length
*
* Returns the length of the specified string
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string to be measured
* @return uint The length of the passed string
*/
function length(string memory _base)
internal
pure
returns (uint) {
bytes memory _baseBytes = bytes(_base);
return _baseBytes.length;
}
/**
* Sub String
*
* Extracts the beginning part of a string based on the desired length
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string that will be used for
* extracting the sub string from
* @param _length The length of the sub string to be extracted from the base
* @return string The extracted sub string
*/
function substring(string memory _base, int _length)
internal
pure
returns (string memory) {
return _substring(_base, _length, 0);
}
/**
* Sub String
*
* Extracts the part of a string based on the desired length and offset. The
* offset and length must not exceed the lenth of the base string.
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string that will be used for
* extracting the sub string from
* @param _length The length of the sub string to be extracted from the base
* @param _offset The starting point to extract the sub string from
* @return string The extracted sub string
*/
function _substring(string memory _base, int _length, int _offset)
internal
pure
returns (string memory) {
bytes memory _baseBytes = bytes(_base);
assert(uint(_offset + _length) <= _baseBytes.length);
string memory _tmp = new string(uint(_length));
bytes memory _tmpBytes = bytes(_tmp);
uint j = 0;
for (uint i = uint(_offset); i < uint(_offset + _length); i++) {
_tmpBytes[j++] = _baseBytes[i];
}
return string(_tmpBytes);
}
/**
* String Split (Very high gas cost)
*
* Splits a string into an array of strings based off the delimiter value.
* Please note this can be quite a gas expensive function due to the use of
* storage so only use if really required.
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string value to be split.
* @param _value The delimiter to split the string on which must be a single
* character
* @return string[] An array of values split based off the delimiter, but
* do not container the delimiter.
*/
function split(string memory _base, string memory _value)
internal
pure
returns (string[] memory splitArr) {
bytes memory _baseBytes = bytes(_base);
uint _offset = 0;
uint _splitsCount = 1;
while (_offset < _baseBytes.length - 1) {
int _limit = _indexOf(_base, _value, _offset);
if (_limit == -1)
break;
else {
_splitsCount++;
_offset = uint(_limit) + 1;
}
}
splitArr = new string[](_splitsCount);
_offset = 0;
_splitsCount = 0;
while (_offset < _baseBytes.length - 1) {
int _limit = _indexOf(_base, _value, _offset);
if (_limit == - 1) {
_limit = int(_baseBytes.length);
}
string memory _tmp = new string(uint(_limit) - _offset);
bytes memory _tmpBytes = bytes(_tmp);
uint j = 0;
for (uint i = _offset; i < uint(_limit); i++) {
_tmpBytes[j++] = _baseBytes[i];
}
_offset = uint(_limit) + 1;
splitArr[_splitsCount++] = string(_tmpBytes);
}
return splitArr;
}
/**
* Compare To
*
* Compares the characters of two strings, to ensure that they have an
* identical footprint
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string base to compare against
* @param _value The string the base is being compared to
* @return bool Simply notates if the two string have an equivalent
*/
function compareTo(string memory _base, string memory _value)
internal
pure
returns (bool) {
bytes memory _baseBytes = bytes(_base);
bytes memory _valueBytes = bytes(_value);
if (_baseBytes.length != _valueBytes.length) {
return false;
}
for (uint i = 0; i < _baseBytes.length; i++) {
if (_baseBytes[i] != _valueBytes[i]) {
return false;
}
}
return true;
}
/**
* Compare To Ignore Case (High gas cost)
*
* Compares the characters of two strings, converting them to the same case
* where applicable to alphabetic characters to distinguish if the values
* match.
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string base to compare against
* @param _value The string the base is being compared to
* @return bool Simply notates if the two string have an equivalent value
* discarding case
*/
function compareToIgnoreCase(string memory _base, string memory _value)
internal
pure
returns (bool) {
bytes memory _baseBytes = bytes(_base);
bytes memory _valueBytes = bytes(_value);
if (_baseBytes.length != _valueBytes.length) {
return false;
}
for (uint i = 0; i < _baseBytes.length; i++) {
if (_baseBytes[i] != _valueBytes[i] &&
_upper(_baseBytes[i]) != _upper(_valueBytes[i])) {
return false;
}
}
return true;
}
/**
* Upper
*
* Converts all the values of a string to their corresponding upper case
* value.
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string base to convert to upper case
* @return string
*/
function upper(string memory _base)
internal
pure
returns (string memory) {
bytes memory _baseBytes = bytes(_base);
for (uint i = 0; i < _baseBytes.length; i++) {
_baseBytes[i] = _upper(_baseBytes[i]);
}
return string(_baseBytes);
}
/**
* Lower
*
* Converts all the values of a string to their corresponding lower case
* value.
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string base to convert to lower case
* @return string
*/
function lower(string memory _base)
internal
pure
returns (string memory) {
bytes memory _baseBytes = bytes(_base);
for (uint i = 0; i < _baseBytes.length; i++) {
_baseBytes[i] = _lower(_baseBytes[i]);
}
return string(_baseBytes);
}
/**
* Upper
*
* Convert an alphabetic character to upper case and return the original
* value when not alphabetic
*
* @param _b1 The byte to be converted to upper case
* @return bytes1 The converted value if the passed value was alphabetic
* and in a lower case otherwise returns the original value
*/
function _upper(bytes1 _b1)
private
pure
returns (bytes1) {
if (_b1 >= 0x61 && _b1 <= 0x7A) {
return bytes1(uint8(_b1) - 32);
}
return _b1;
}
/**
* Lower
*
* Convert an alphabetic character to lower case and return the original
* value when not alphabetic
*
* @param _b1 The byte to be converted to lower case
* @return bytes1 The converted value if the passed value was alphabetic
* and in a upper case otherwise returns the original value
*/
function _lower(bytes1 _b1)
private
pure
returns (bytes1) {
if (_b1 >= 0x41 && _b1 <= 0x5A) {
return bytes1(uint8(_b1) + 32);
}
return _b1;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title PartnerFund
* @notice Where partners’ fees are managed
*/
contract PartnerFund is Ownable, Beneficiary, TransferControllerManageable {
using FungibleBalanceLib for FungibleBalanceLib.Balance;
using TxHistoryLib for TxHistoryLib.TxHistory;
using SafeMathIntLib for int256;
using Strings for string;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Partner {
bytes32 nameHash;
uint256 fee;
address wallet;
uint256 index;
bool operatorCanUpdate;
bool partnerCanUpdate;
FungibleBalanceLib.Balance active;
FungibleBalanceLib.Balance staged;
TxHistoryLib.TxHistory txHistory;
FullBalanceHistory[] fullBalanceHistory;
}
struct FullBalanceHistory {
uint256 listIndex;
int256 balance;
uint256 blockNumber;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
Partner[] private partners;
mapping(bytes32 => uint256) private _indexByNameHash;
mapping(address => uint256) private _indexByWallet;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event ReceiveEvent(address from, int256 amount, address currencyCt, uint256 currencyId);
event RegisterPartnerByNameEvent(string name, uint256 fee, address wallet);
event RegisterPartnerByNameHashEvent(bytes32 nameHash, uint256 fee, address wallet);
event SetFeeByIndexEvent(uint256 index, uint256 oldFee, uint256 newFee);
event SetFeeByNameEvent(string name, uint256 oldFee, uint256 newFee);
event SetFeeByNameHashEvent(bytes32 nameHash, uint256 oldFee, uint256 newFee);
event SetFeeByWalletEvent(address wallet, uint256 oldFee, uint256 newFee);
event SetPartnerWalletByIndexEvent(uint256 index, address oldWallet, address newWallet);
event SetPartnerWalletByNameEvent(string name, address oldWallet, address newWallet);
event SetPartnerWalletByNameHashEvent(bytes32 nameHash, address oldWallet, address newWallet);
event SetPartnerWalletByWalletEvent(address oldWallet, address newWallet);
event StageEvent(address from, int256 amount, address currencyCt, uint256 currencyId);
event WithdrawEvent(address to, int256 amount, address currencyCt, uint256 currencyId);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Fallback function that deposits ethers
function() external payable {
_receiveEthersTo(
indexByWallet(msg.sender) - 1, SafeMathIntLib.toNonZeroInt256(msg.value)
);
}
/// @notice Receive ethers to
/// @param tag The tag of the concerned partner
function receiveEthersTo(address tag, string memory)
public
payable
{
_receiveEthersTo(
uint256(tag) - 1, SafeMathIntLib.toNonZeroInt256(msg.value)
);
}
/// @notice Receive tokens
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokens(string memory, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public
{
_receiveTokensTo(
indexByWallet(msg.sender) - 1, amount, currencyCt, currencyId, standard
);
}
/// @notice Receive tokens to
/// @param tag The tag of the concerned partner
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokensTo(address tag, string memory, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public
{
_receiveTokensTo(
uint256(tag) - 1, amount, currencyCt, currencyId, standard
);
}
/// @notice Hash name
/// @param name The name to be hashed
/// @return The hash value
function hashName(string memory name)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(name.upper()));
}
/// @notice Get deposit by partner and deposit indices
/// @param partnerIndex The index of the concerned partner
/// @param depositIndex The index of the concerned deposit
/// return The deposit parameters
function depositByIndices(uint256 partnerIndex, uint256 depositIndex)
public
view
returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
// Require partner index is one of registered partner
require(0 < partnerIndex && partnerIndex <= partners.length, "Some error message when require fails [PartnerFund.sol:160]");
return _depositByIndices(partnerIndex - 1, depositIndex);
}
/// @notice Get deposit by partner name and deposit indices
/// @param name The name of the concerned partner
/// @param depositIndex The index of the concerned deposit
/// return The deposit parameters
function depositByName(string memory name, uint depositIndex)
public
view
returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
// Implicitly require that partner name is registered
return _depositByIndices(indexByName(name) - 1, depositIndex);
}
/// @notice Get deposit by partner name hash and deposit indices
/// @param nameHash The hashed name of the concerned partner
/// @param depositIndex The index of the concerned deposit
/// return The deposit parameters
function depositByNameHash(bytes32 nameHash, uint depositIndex)
public
view
returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
// Implicitly require that partner name hash is registered
return _depositByIndices(indexByNameHash(nameHash) - 1, depositIndex);
}
/// @notice Get deposit by partner wallet and deposit indices
/// @param wallet The wallet of the concerned partner
/// @param depositIndex The index of the concerned deposit
/// return The deposit parameters
function depositByWallet(address wallet, uint depositIndex)
public
view
returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
// Implicitly require that partner wallet is registered
return _depositByIndices(indexByWallet(wallet) - 1, depositIndex);
}
/// @notice Get deposits count by partner index
/// @param index The index of the concerned partner
/// return The deposits count
function depositsCountByIndex(uint256 index)
public
view
returns (uint256)
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:213]");
return _depositsCountByIndex(index - 1);
}
/// @notice Get deposits count by partner name
/// @param name The name of the concerned partner
/// return The deposits count
function depositsCountByName(string memory name)
public
view
returns (uint256)
{
// Implicitly require that partner name is registered
return _depositsCountByIndex(indexByName(name) - 1);
}
/// @notice Get deposits count by partner name hash
/// @param nameHash The hashed name of the concerned partner
/// return The deposits count
function depositsCountByNameHash(bytes32 nameHash)
public
view
returns (uint256)
{
// Implicitly require that partner name hash is registered
return _depositsCountByIndex(indexByNameHash(nameHash) - 1);
}
/// @notice Get deposits count by partner wallet
/// @param wallet The wallet of the concerned partner
/// return The deposits count
function depositsCountByWallet(address wallet)
public
view
returns (uint256)
{
// Implicitly require that partner wallet is registered
return _depositsCountByIndex(indexByWallet(wallet) - 1);
}
/// @notice Get active balance by partner index and currency
/// @param index The index of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The active balance
function activeBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:265]");
return _activeBalanceByIndex(index - 1, currencyCt, currencyId);
}
/// @notice Get active balance by partner name and currency
/// @param name The name of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The active balance
function activeBalanceByName(string memory name, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Implicitly require that partner name is registered
return _activeBalanceByIndex(indexByName(name) - 1, currencyCt, currencyId);
}
/// @notice Get active balance by partner name hash and currency
/// @param nameHash The hashed name of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The active balance
function activeBalanceByNameHash(bytes32 nameHash, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Implicitly require that partner name hash is registered
return _activeBalanceByIndex(indexByNameHash(nameHash) - 1, currencyCt, currencyId);
}
/// @notice Get active balance by partner wallet and currency
/// @param wallet The wallet of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The active balance
function activeBalanceByWallet(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Implicitly require that partner wallet is registered
return _activeBalanceByIndex(indexByWallet(wallet) - 1, currencyCt, currencyId);
}
/// @notice Get staged balance by partner index and currency
/// @param index The index of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The staged balance
function stagedBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:323]");
return _stagedBalanceByIndex(index - 1, currencyCt, currencyId);
}
/// @notice Get staged balance by partner name and currency
/// @param name The name of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The staged balance
function stagedBalanceByName(string memory name, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Implicitly require that partner name is registered
return _stagedBalanceByIndex(indexByName(name) - 1, currencyCt, currencyId);
}
/// @notice Get staged balance by partner name hash and currency
/// @param nameHash The hashed name of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The staged balance
function stagedBalanceByNameHash(bytes32 nameHash, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Implicitly require that partner name is registered
return _stagedBalanceByIndex(indexByNameHash(nameHash) - 1, currencyCt, currencyId);
}
/// @notice Get staged balance by partner wallet and currency
/// @param wallet The wallet of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The staged balance
function stagedBalanceByWallet(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Implicitly require that partner wallet is registered
return _stagedBalanceByIndex(indexByWallet(wallet) - 1, currencyCt, currencyId);
}
/// @notice Get the number of partners
/// @return The number of partners
function partnersCount()
public
view
returns (uint256)
{
return partners.length;
}
/// @notice Register a partner by name
/// @param name The name of the concerned partner
/// @param fee The partner's fee fraction
/// @param wallet The partner's wallet
/// @param partnerCanUpdate Indicator of whether partner can update fee and wallet
/// @param operatorCanUpdate Indicator of whether operator can update fee and wallet
function registerByName(string memory name, uint256 fee, address wallet,
bool partnerCanUpdate, bool operatorCanUpdate)
public
onlyOperator
{
// Require not empty name string
require(bytes(name).length > 0, "Some error message when require fails [PartnerFund.sol:392]");
// Hash name
bytes32 nameHash = hashName(name);
// Register partner
_registerPartnerByNameHash(nameHash, fee, wallet, partnerCanUpdate, operatorCanUpdate);
// Emit event
emit RegisterPartnerByNameEvent(name, fee, wallet);
}
/// @notice Register a partner by name hash
/// @param nameHash The hashed name of the concerned partner
/// @param fee The partner's fee fraction
/// @param wallet The partner's wallet
/// @param partnerCanUpdate Indicator of whether partner can update fee and wallet
/// @param operatorCanUpdate Indicator of whether operator can update fee and wallet
function registerByNameHash(bytes32 nameHash, uint256 fee, address wallet,
bool partnerCanUpdate, bool operatorCanUpdate)
public
onlyOperator
{
// Register partner
_registerPartnerByNameHash(nameHash, fee, wallet, partnerCanUpdate, operatorCanUpdate);
// Emit event
emit RegisterPartnerByNameHashEvent(nameHash, fee, wallet);
}
/// @notice Gets the 1-based index of partner by its name
/// @dev Reverts if name does not correspond to registered partner
/// @return Index of partner by given name
function indexByNameHash(bytes32 nameHash)
public
view
returns (uint256)
{
uint256 index = _indexByNameHash[nameHash];
require(0 < index, "Some error message when require fails [PartnerFund.sol:431]");
return index;
}
/// @notice Gets the 1-based index of partner by its name
/// @dev Reverts if name does not correspond to registered partner
/// @return Index of partner by given name
function indexByName(string memory name)
public
view
returns (uint256)
{
return indexByNameHash(hashName(name));
}
/// @notice Gets the 1-based index of partner by its wallet
/// @dev Reverts if wallet does not correspond to registered partner
/// @return Index of partner by given wallet
function indexByWallet(address wallet)
public
view
returns (uint256)
{
uint256 index = _indexByWallet[wallet];
require(0 < index, "Some error message when require fails [PartnerFund.sol:455]");
return index;
}
/// @notice Gauge whether a partner by the given name is registered
/// @param name The name of the concerned partner
/// @return true if partner is registered, else false
function isRegisteredByName(string memory name)
public
view
returns (bool)
{
return (0 < _indexByNameHash[hashName(name)]);
}
/// @notice Gauge whether a partner by the given name hash is registered
/// @param nameHash The hashed name of the concerned partner
/// @return true if partner is registered, else false
function isRegisteredByNameHash(bytes32 nameHash)
public
view
returns (bool)
{
return (0 < _indexByNameHash[nameHash]);
}
/// @notice Gauge whether a partner by the given wallet is registered
/// @param wallet The wallet of the concerned partner
/// @return true if partner is registered, else false
function isRegisteredByWallet(address wallet)
public
view
returns (bool)
{
return (0 < _indexByWallet[wallet]);
}
/// @notice Get the partner fee fraction by the given partner index
/// @param index The index of the concerned partner
/// @return The fee fraction
function feeByIndex(uint256 index)
public
view
returns (uint256)
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:501]");
return _partnerFeeByIndex(index - 1);
}
/// @notice Get the partner fee fraction by the given partner name
/// @param name The name of the concerned partner
/// @return The fee fraction
function feeByName(string memory name)
public
view
returns (uint256)
{
// Get fee, implicitly requiring that partner name is registered
return _partnerFeeByIndex(indexByName(name) - 1);
}
/// @notice Get the partner fee fraction by the given partner name hash
/// @param nameHash The hashed name of the concerned partner
/// @return The fee fraction
function feeByNameHash(bytes32 nameHash)
public
view
returns (uint256)
{
// Get fee, implicitly requiring that partner name hash is registered
return _partnerFeeByIndex(indexByNameHash(nameHash) - 1);
}
/// @notice Get the partner fee fraction by the given partner wallet
/// @param wallet The wallet of the concerned partner
/// @return The fee fraction
function feeByWallet(address wallet)
public
view
returns (uint256)
{
// Get fee, implicitly requiring that partner wallet is registered
return _partnerFeeByIndex(indexByWallet(wallet) - 1);
}
/// @notice Set the partner fee fraction by the given partner index
/// @param index The index of the concerned partner
/// @param newFee The partner's fee fraction
function setFeeByIndex(uint256 index, uint256 newFee)
public
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:549]");
// Update fee
uint256 oldFee = _setPartnerFeeByIndex(index - 1, newFee);
// Emit event
emit SetFeeByIndexEvent(index, oldFee, newFee);
}
/// @notice Set the partner fee fraction by the given partner name
/// @param name The name of the concerned partner
/// @param newFee The partner's fee fraction
function setFeeByName(string memory name, uint256 newFee)
public
{
// Update fee, implicitly requiring that partner name is registered
uint256 oldFee = _setPartnerFeeByIndex(indexByName(name) - 1, newFee);
// Emit event
emit SetFeeByNameEvent(name, oldFee, newFee);
}
/// @notice Set the partner fee fraction by the given partner name hash
/// @param nameHash The hashed name of the concerned partner
/// @param newFee The partner's fee fraction
function setFeeByNameHash(bytes32 nameHash, uint256 newFee)
public
{
// Update fee, implicitly requiring that partner name hash is registered
uint256 oldFee = _setPartnerFeeByIndex(indexByNameHash(nameHash) - 1, newFee);
// Emit event
emit SetFeeByNameHashEvent(nameHash, oldFee, newFee);
}
/// @notice Set the partner fee fraction by the given partner wallet
/// @param wallet The wallet of the concerned partner
/// @param newFee The partner's fee fraction
function setFeeByWallet(address wallet, uint256 newFee)
public
{
// Update fee, implicitly requiring that partner wallet is registered
uint256 oldFee = _setPartnerFeeByIndex(indexByWallet(wallet) - 1, newFee);
// Emit event
emit SetFeeByWalletEvent(wallet, oldFee, newFee);
}
/// @notice Get the partner wallet by the given partner index
/// @param index The index of the concerned partner
/// @return The wallet
function walletByIndex(uint256 index)
public
view
returns (address)
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:606]");
return partners[index - 1].wallet;
}
/// @notice Get the partner wallet by the given partner name
/// @param name The name of the concerned partner
/// @return The wallet
function walletByName(string memory name)
public
view
returns (address)
{
// Get wallet, implicitly requiring that partner name is registered
return partners[indexByName(name) - 1].wallet;
}
/// @notice Get the partner wallet by the given partner name hash
/// @param nameHash The hashed name of the concerned partner
/// @return The wallet
function walletByNameHash(bytes32 nameHash)
public
view
returns (address)
{
// Get wallet, implicitly requiring that partner name hash is registered
return partners[indexByNameHash(nameHash) - 1].wallet;
}
/// @notice Set the partner wallet by the given partner index
/// @param index The index of the concerned partner
/// @return newWallet The partner's wallet
function setWalletByIndex(uint256 index, address newWallet)
public
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:642]");
// Update wallet
address oldWallet = _setPartnerWalletByIndex(index - 1, newWallet);
// Emit event
emit SetPartnerWalletByIndexEvent(index, oldWallet, newWallet);
}
/// @notice Set the partner wallet by the given partner name
/// @param name The name of the concerned partner
/// @return newWallet The partner's wallet
function setWalletByName(string memory name, address newWallet)
public
{
// Update wallet
address oldWallet = _setPartnerWalletByIndex(indexByName(name) - 1, newWallet);
// Emit event
emit SetPartnerWalletByNameEvent(name, oldWallet, newWallet);
}
/// @notice Set the partner wallet by the given partner name hash
/// @param nameHash The hashed name of the concerned partner
/// @return newWallet The partner's wallet
function setWalletByNameHash(bytes32 nameHash, address newWallet)
public
{
// Update wallet
address oldWallet = _setPartnerWalletByIndex(indexByNameHash(nameHash) - 1, newWallet);
// Emit event
emit SetPartnerWalletByNameHashEvent(nameHash, oldWallet, newWallet);
}
/// @notice Set the new partner wallet by the given old partner wallet
/// @param oldWallet The old wallet of the concerned partner
/// @return newWallet The partner's new wallet
function setWalletByWallet(address oldWallet, address newWallet)
public
{
// Update wallet
_setPartnerWalletByIndex(indexByWallet(oldWallet) - 1, newWallet);
// Emit event
emit SetPartnerWalletByWalletEvent(oldWallet, newWallet);
}
/// @notice Stage the amount for subsequent withdrawal
/// @param amount The concerned amount to stage
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function stage(int256 amount, address currencyCt, uint256 currencyId)
public
{
// Get index, implicitly requiring that msg.sender is wallet of registered partner
uint256 index = indexByWallet(msg.sender);
// Require positive amount
require(amount.isPositiveInt256(), "Some error message when require fails [PartnerFund.sol:701]");
// Clamp amount to move
amount = amount.clampMax(partners[index - 1].active.get(currencyCt, currencyId));
partners[index - 1].active.sub(amount, currencyCt, currencyId);
partners[index - 1].staged.add(amount, currencyCt, currencyId);
partners[index - 1].txHistory.addDeposit(amount, currencyCt, currencyId);
// Add to full deposit history
partners[index - 1].fullBalanceHistory.push(
FullBalanceHistory(
partners[index - 1].txHistory.depositsCount() - 1,
partners[index - 1].active.get(currencyCt, currencyId),
block.number
)
);
// Emit event
emit StageEvent(msg.sender, amount, currencyCt, currencyId);
}
/// @notice Withdraw the given amount from staged balance
/// @param amount The concerned amount to withdraw
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function withdraw(int256 amount, address currencyCt, uint256 currencyId, string memory standard)
public
{
// Get index, implicitly requiring that msg.sender is wallet of registered partner
uint256 index = indexByWallet(msg.sender);
// Require positive amount
require(amount.isPositiveInt256(), "Some error message when require fails [PartnerFund.sol:736]");
// Clamp amount to move
amount = amount.clampMax(partners[index - 1].staged.get(currencyCt, currencyId));
partners[index - 1].staged.sub(amount, currencyCt, currencyId);
// Execute transfer
if (address(0) == currencyCt && 0 == currencyId)
msg.sender.transfer(uint256(amount));
else {
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getDispatchSignature(), address(this), msg.sender, uint256(amount), currencyCt, currencyId
)
);
require(success, "Some error message when require fails [PartnerFund.sol:754]");
}
// Emit event
emit WithdrawEvent(msg.sender, amount, currencyCt, currencyId);
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
/// @dev index is 0-based
function _receiveEthersTo(uint256 index, int256 amount)
private
{
// Require that index is within bounds
require(index < partners.length, "Some error message when require fails [PartnerFund.sol:769]");
// Add to active
partners[index].active.add(amount, address(0), 0);
partners[index].txHistory.addDeposit(amount, address(0), 0);
// Add to full deposit history
partners[index].fullBalanceHistory.push(
FullBalanceHistory(
partners[index].txHistory.depositsCount() - 1,
partners[index].active.get(address(0), 0),
block.number
)
);
// Emit event
emit ReceiveEvent(msg.sender, amount, address(0), 0);
}
/// @dev index is 0-based
function _receiveTokensTo(uint256 index, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
private
{
// Require that index is within bounds
require(index < partners.length, "Some error message when require fails [PartnerFund.sol:794]");
require(amount.isNonZeroPositiveInt256(), "Some error message when require fails [PartnerFund.sol:796]");
// Execute transfer
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId
)
);
require(success, "Some error message when require fails [PartnerFund.sol:805]");
// Add to active
partners[index].active.add(amount, currencyCt, currencyId);
partners[index].txHistory.addDeposit(amount, currencyCt, currencyId);
// Add to full deposit history
partners[index].fullBalanceHistory.push(
FullBalanceHistory(
partners[index].txHistory.depositsCount() - 1,
partners[index].active.get(currencyCt, currencyId),
block.number
)
);
// Emit event
emit ReceiveEvent(msg.sender, amount, currencyCt, currencyId);
}
/// @dev partnerIndex is 0-based
function _depositByIndices(uint256 partnerIndex, uint256 depositIndex)
private
view
returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
require(depositIndex < partners[partnerIndex].fullBalanceHistory.length, "Some error message when require fails [PartnerFund.sol:830]");
FullBalanceHistory storage entry = partners[partnerIndex].fullBalanceHistory[depositIndex];
(,, currencyCt, currencyId) = partners[partnerIndex].txHistory.deposit(entry.listIndex);
balance = entry.balance;
blockNumber = entry.blockNumber;
}
/// @dev index is 0-based
function _depositsCountByIndex(uint256 index)
private
view
returns (uint256)
{
return partners[index].fullBalanceHistory.length;
}
/// @dev index is 0-based
function _activeBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId)
private
view
returns (int256)
{
return partners[index].active.get(currencyCt, currencyId);
}
/// @dev index is 0-based
function _stagedBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId)
private
view
returns (int256)
{
return partners[index].staged.get(currencyCt, currencyId);
}
function _registerPartnerByNameHash(bytes32 nameHash, uint256 fee, address wallet,
bool partnerCanUpdate, bool operatorCanUpdate)
private
{
// Require that the name is not previously registered
require(0 == _indexByNameHash[nameHash], "Some error message when require fails [PartnerFund.sol:871]");
// Require possibility to update
require(partnerCanUpdate || operatorCanUpdate, "Some error message when require fails [PartnerFund.sol:874]");
// Add new partner
partners.length++;
// Reference by 1-based index
uint256 index = partners.length;
// Update partner map
partners[index - 1].nameHash = nameHash;
partners[index - 1].fee = fee;
partners[index - 1].wallet = wallet;
partners[index - 1].partnerCanUpdate = partnerCanUpdate;
partners[index - 1].operatorCanUpdate = operatorCanUpdate;
partners[index - 1].index = index;
// Update name hash to index map
_indexByNameHash[nameHash] = index;
// Update wallet to index map
_indexByWallet[wallet] = index;
}
/// @dev index is 0-based
function _setPartnerFeeByIndex(uint256 index, uint256 fee)
private
returns (uint256)
{
uint256 oldFee = partners[index].fee;
// If operator tries to change verify that operator has access
if (isOperator())
require(partners[index].operatorCanUpdate, "Some error message when require fails [PartnerFund.sol:906]");
else {
// Require that msg.sender is partner
require(msg.sender == partners[index].wallet, "Some error message when require fails [PartnerFund.sol:910]");
// If partner tries to change verify that partner has access
require(partners[index].partnerCanUpdate, "Some error message when require fails [PartnerFund.sol:913]");
}
// Update stored fee
partners[index].fee = fee;
return oldFee;
}
// @dev index is 0-based
function _setPartnerWalletByIndex(uint256 index, address newWallet)
private
returns (address)
{
address oldWallet = partners[index].wallet;
// If address has not been set operator is the only allowed to change it
if (oldWallet == address(0))
require(isOperator(), "Some error message when require fails [PartnerFund.sol:931]");
// Else if operator tries to change verify that operator has access
else if (isOperator())
require(partners[index].operatorCanUpdate, "Some error message when require fails [PartnerFund.sol:935]");
else {
// Require that msg.sender is partner
require(msg.sender == oldWallet, "Some error message when require fails [PartnerFund.sol:939]");
// If partner tries to change verify that partner has access
require(partners[index].partnerCanUpdate, "Some error message when require fails [PartnerFund.sol:942]");
// Require that new wallet is not zero-address if it can not be changed by operator
require(partners[index].operatorCanUpdate || newWallet != address(0), "Some error message when require fails [PartnerFund.sol:945]");
}
// Update stored wallet
partners[index].wallet = newWallet;
// Update address to tag map
if (oldWallet != address(0))
_indexByWallet[oldWallet] = 0;
if (newWallet != address(0))
_indexByWallet[newWallet] = index;
return oldWallet;
}
// @dev index is 0-based
function _partnerFeeByIndex(uint256 index)
private
view
returns (uint256)
{
return partners[index].fee;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NahmiiTypesLib
* @dev Data types of general nahmii character
*/
library NahmiiTypesLib {
//
// Enums
// -----------------------------------------------------------------------------------------------------------------
enum ChallengePhase {Dispute, Closed}
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct OriginFigure {
uint256 originId;
MonetaryTypesLib.Figure figure;
}
struct IntendedConjugateCurrency {
MonetaryTypesLib.Currency intended;
MonetaryTypesLib.Currency conjugate;
}
struct SingleFigureTotalOriginFigures {
MonetaryTypesLib.Figure single;
OriginFigure[] total;
}
struct TotalOriginFigures {
OriginFigure[] total;
}
struct CurrentPreviousInt256 {
int256 current;
int256 previous;
}
struct SingleTotalInt256 {
int256 single;
int256 total;
}
struct IntendedConjugateCurrentPreviousInt256 {
CurrentPreviousInt256 intended;
CurrentPreviousInt256 conjugate;
}
struct IntendedConjugateSingleTotalInt256 {
SingleTotalInt256 intended;
SingleTotalInt256 conjugate;
}
struct WalletOperatorHashes {
bytes32 wallet;
bytes32 operator;
}
struct Signature {
bytes32 r;
bytes32 s;
uint8 v;
}
struct Seal {
bytes32 hash;
Signature signature;
}
struct WalletOperatorSeal {
Seal wallet;
Seal operator;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title DriipSettlementTypesLib
* @dev Types for driip settlements
*/
library DriipSettlementTypesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
enum SettlementRole {Origin, Target}
struct SettlementParty {
uint256 nonce;
address wallet;
bool done;
uint256 doneBlockNumber;
}
struct Settlement {
string settledKind;
bytes32 settledHash;
SettlementParty origin;
SettlementParty target;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title DriipSettlementState
* @notice Where driip settlement state is managed
*/
contract DriipSettlementState is Ownable, Servable, CommunityVotable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public INIT_SETTLEMENT_ACTION = "init_settlement";
string constant public SET_SETTLEMENT_ROLE_DONE_ACTION = "set_settlement_role_done";
string constant public SET_MAX_NONCE_ACTION = "set_max_nonce";
string constant public SET_FEE_TOTAL_ACTION = "set_fee_total";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
uint256 public maxDriipNonce;
DriipSettlementTypesLib.Settlement[] public settlements;
mapping(address => uint256[]) public walletSettlementIndices;
mapping(address => mapping(uint256 => uint256)) public walletNonceSettlementIndex;
mapping(address => mapping(address => mapping(uint256 => uint256))) public walletCurrencyMaxNonce;
mapping(address => mapping(address => mapping(address => mapping(address => mapping(uint256 => MonetaryTypesLib.NoncedAmount))))) public totalFeesMap;
bool public upgradesFrozen;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event InitSettlementEvent(DriipSettlementTypesLib.Settlement settlement);
event CompleteSettlementPartyEvent(address wallet, uint256 nonce, DriipSettlementTypesLib.SettlementRole settlementRole,
bool done, uint256 doneBlockNumber);
event SetMaxNonceByWalletAndCurrencyEvent(address wallet, MonetaryTypesLib.Currency currency,
uint256 maxNonce);
event SetMaxDriipNonceEvent(uint256 maxDriipNonce);
event UpdateMaxDriipNonceFromCommunityVoteEvent(uint256 maxDriipNonce);
event SetTotalFeeEvent(address wallet, Beneficiary beneficiary, address destination,
MonetaryTypesLib.Currency currency, MonetaryTypesLib.NoncedAmount totalFee);
event FreezeUpgradesEvent();
event UpgradeSettlementEvent(DriipSettlementTypesLib.Settlement settlement);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the count of settlements
function settlementsCount()
public
view
returns (uint256)
{
return settlements.length;
}
/// @notice Get the count of settlements for given wallet
/// @param wallet The address for which to return settlement count
/// @return count of settlements for the provided wallet
function settlementsCountByWallet(address wallet)
public
view
returns (uint256)
{
return walletSettlementIndices[wallet].length;
}
/// @notice Get settlement of given wallet and index
/// @param wallet The address for which to return settlement
/// @param index The wallet's settlement index
/// @return settlement for the provided wallet and index
function settlementByWalletAndIndex(address wallet, uint256 index)
public
view
returns (DriipSettlementTypesLib.Settlement memory)
{
require(walletSettlementIndices[wallet].length > index, "Index out of bounds [DriipSettlementState.sol:107]");
return settlements[walletSettlementIndices[wallet][index] - 1];
}
/// @notice Get settlement of given wallet and wallet nonce
/// @param wallet The address for which to return settlement
/// @param nonce The wallet's nonce
/// @return settlement for the provided wallet and index
function settlementByWalletAndNonce(address wallet, uint256 nonce)
public
view
returns (DriipSettlementTypesLib.Settlement memory)
{
require(0 != walletNonceSettlementIndex[wallet][nonce], "No settlement found for wallet and nonce [DriipSettlementState.sol:120]");
return settlements[walletNonceSettlementIndex[wallet][nonce] - 1];
}
/// @notice Initialize settlement, i.e. create one if no such settlement exists
/// for the double pair of wallets and nonces
/// @param settledKind The kind of driip of the settlement
/// @param settledHash The hash of driip of the settlement
/// @param originWallet The address of the origin wallet
/// @param originNonce The wallet nonce of the origin wallet
/// @param targetWallet The address of the target wallet
/// @param targetNonce The wallet nonce of the target wallet
function initSettlement(string memory settledKind, bytes32 settledHash, address originWallet,
uint256 originNonce, address targetWallet, uint256 targetNonce)
public
onlyEnabledServiceAction(INIT_SETTLEMENT_ACTION)
{
if (
0 == walletNonceSettlementIndex[originWallet][originNonce] &&
0 == walletNonceSettlementIndex[targetWallet][targetNonce]
) {
// Create new settlement
settlements.length++;
// Get the 0-based index
uint256 index = settlements.length - 1;
// Update settlement
settlements[index].settledKind = settledKind;
settlements[index].settledHash = settledHash;
settlements[index].origin.nonce = originNonce;
settlements[index].origin.wallet = originWallet;
settlements[index].target.nonce = targetNonce;
settlements[index].target.wallet = targetWallet;
// Emit event
emit InitSettlementEvent(settlements[index]);
// Store 1-based index value
index++;
walletSettlementIndices[originWallet].push(index);
walletSettlementIndices[targetWallet].push(index);
walletNonceSettlementIndex[originWallet][originNonce] = index;
walletNonceSettlementIndex[targetWallet][targetNonce] = index;
}
}
/// @notice Set the done of the given settlement role in the given settlement
/// @param wallet The address of the concerned wallet
/// @param nonce The nonce of the concerned wallet
/// @param settlementRole The settlement role
/// @param done The done flag
function completeSettlementParty(address wallet, uint256 nonce,
DriipSettlementTypesLib.SettlementRole settlementRole, bool done)
public
onlyEnabledServiceAction(SET_SETTLEMENT_ROLE_DONE_ACTION)
{
// Get the 1-based index of the settlement
uint256 index = walletNonceSettlementIndex[wallet][nonce];
// Require the existence of settlement
require(0 != index, "No settlement found for wallet and nonce [DriipSettlementState.sol:181]");
// Get the settlement party
DriipSettlementTypesLib.SettlementParty storage party =
DriipSettlementTypesLib.SettlementRole.Origin == settlementRole ?
settlements[index - 1].origin :
settlements[index - 1].target;
// Update party done and done block number properties
party.done = done;
party.doneBlockNumber = done ? block.number : 0;
// Emit event
emit CompleteSettlementPartyEvent(wallet, nonce, settlementRole, done, party.doneBlockNumber);
}
/// @notice Gauge whether the settlement is done wrt the given wallet and nonce
/// @param wallet The address of the concerned wallet
/// @param nonce The nonce of the concerned wallet
/// @return True if settlement is done for role, else false
function isSettlementPartyDone(address wallet, uint256 nonce)
public
view
returns (bool)
{
// Get the 1-based index of the settlement
uint256 index = walletNonceSettlementIndex[wallet][nonce];
// Return false if settlement does not exist
if (0 == index)
return false;
// Return done
return (
wallet == settlements[index - 1].origin.wallet ?
settlements[index - 1].origin.done :
settlements[index - 1].target.done
);
}
/// @notice Gauge whether the settlement is done wrt the given wallet, nonce
/// and settlement role
/// @param wallet The address of the concerned wallet
/// @param nonce The nonce of the concerned wallet
/// @param settlementRole The settlement role
/// @return True if settlement is done for role, else false
function isSettlementPartyDone(address wallet, uint256 nonce,
DriipSettlementTypesLib.SettlementRole settlementRole)
public
view
returns (bool)
{
// Get the 1-based index of the settlement
uint256 index = walletNonceSettlementIndex[wallet][nonce];
// Return false if settlement does not exist
if (0 == index)
return false;
// Get the settlement party
DriipSettlementTypesLib.SettlementParty storage settlementParty =
DriipSettlementTypesLib.SettlementRole.Origin == settlementRole ?
settlements[index - 1].origin : settlements[index - 1].target;
// Require that wallet is party of the right role
require(wallet == settlementParty.wallet, "Wallet has wrong settlement role [DriipSettlementState.sol:246]");
// Return done
return settlementParty.done;
}
/// @notice Get the done block number of the settlement party with the given wallet and nonce
/// @param wallet The address of the concerned wallet
/// @param nonce The nonce of the concerned wallet
/// @return The done block number of the settlement wrt the given settlement role
function settlementPartyDoneBlockNumber(address wallet, uint256 nonce)
public
view
returns (uint256)
{
// Get the 1-based index of the settlement
uint256 index = walletNonceSettlementIndex[wallet][nonce];
// Require the existence of settlement
require(0 != index, "No settlement found for wallet and nonce [DriipSettlementState.sol:265]");
// Return done block number
return (
wallet == settlements[index - 1].origin.wallet ?
settlements[index - 1].origin.doneBlockNumber :
settlements[index - 1].target.doneBlockNumber
);
}
/// @notice Get the done block number of the settlement party with the given wallet, nonce and settlement role
/// @param wallet The address of the concerned wallet
/// @param nonce The nonce of the concerned wallet
/// @param settlementRole The settlement role
/// @return The done block number of the settlement wrt the given settlement role
function settlementPartyDoneBlockNumber(address wallet, uint256 nonce,
DriipSettlementTypesLib.SettlementRole settlementRole)
public
view
returns (uint256)
{
// Get the 1-based index of the settlement
uint256 index = walletNonceSettlementIndex[wallet][nonce];
// Require the existence of settlement
require(0 != index, "No settlement found for wallet and nonce [DriipSettlementState.sol:290]");
// Get the settlement party
DriipSettlementTypesLib.SettlementParty storage settlementParty =
DriipSettlementTypesLib.SettlementRole.Origin == settlementRole ?
settlements[index - 1].origin : settlements[index - 1].target;
// Require that wallet is party of the right role
require(wallet == settlementParty.wallet, "Wallet has wrong settlement role [DriipSettlementState.sol:298]");
// Return done block number
return settlementParty.doneBlockNumber;
}
/// @notice Set the max (driip) nonce
/// @param _maxDriipNonce The max nonce
function setMaxDriipNonce(uint256 _maxDriipNonce)
public
onlyEnabledServiceAction(SET_MAX_NONCE_ACTION)
{
maxDriipNonce = _maxDriipNonce;
// Emit event
emit SetMaxDriipNonceEvent(maxDriipNonce);
}
/// @notice Update the max driip nonce property from CommunityVote contract
function updateMaxDriipNonceFromCommunityVote()
public
{
uint256 _maxDriipNonce = communityVote.getMaxDriipNonce();
if (0 == _maxDriipNonce)
return;
maxDriipNonce = _maxDriipNonce;
// Emit event
emit UpdateMaxDriipNonceFromCommunityVoteEvent(maxDriipNonce);
}
/// @notice Get the max nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The max nonce
function maxNonceByWalletAndCurrency(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
return walletCurrencyMaxNonce[wallet][currency.ct][currency.id];
}
/// @notice Set the max nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @param maxNonce The max nonce
function setMaxNonceByWalletAndCurrency(address wallet, MonetaryTypesLib.Currency memory currency,
uint256 maxNonce)
public
onlyEnabledServiceAction(SET_MAX_NONCE_ACTION)
{
// Update max nonce value
walletCurrencyMaxNonce[wallet][currency.ct][currency.id] = maxNonce;
// Emit event
emit SetMaxNonceByWalletAndCurrencyEvent(wallet, currency, maxNonce);
}
/// @notice Get the total fee payed by the given wallet to the given beneficiary and destination
/// in the given currency
/// @param wallet The address of the concerned wallet
/// @param beneficiary The concerned beneficiary
/// @param destination The concerned destination
/// @param currency The concerned currency
/// @return The total fee
function totalFee(address wallet, Beneficiary beneficiary, address destination,
MonetaryTypesLib.Currency memory currency)
public
view
returns (MonetaryTypesLib.NoncedAmount memory)
{
return totalFeesMap[wallet][address(beneficiary)][destination][currency.ct][currency.id];
}
/// @notice Set the total fee payed by the given wallet to the given beneficiary and destination
/// in the given currency
/// @param wallet The address of the concerned wallet
/// @param beneficiary The concerned beneficiary
/// @param destination The concerned destination
/// @param _totalFee The total fee
function setTotalFee(address wallet, Beneficiary beneficiary, address destination,
MonetaryTypesLib.Currency memory currency, MonetaryTypesLib.NoncedAmount memory _totalFee)
public
onlyEnabledServiceAction(SET_FEE_TOTAL_ACTION)
{
// Update total fees value
totalFeesMap[wallet][address(beneficiary)][destination][currency.ct][currency.id] = _totalFee;
// Emit event
emit SetTotalFeeEvent(wallet, beneficiary, destination, currency, _totalFee);
}
/// @notice Freeze all future settlement upgrades
/// @dev This operation can not be undone
function freezeUpgrades()
public
onlyDeployer
{
// Freeze upgrade
upgradesFrozen = true;
// Emit event
emit FreezeUpgradesEvent();
}
/// @notice Upgrade settlement from other driip settlement state instance
function upgradeSettlement(string memory settledKind, bytes32 settledHash,
address originWallet, uint256 originNonce, bool originDone, uint256 originDoneBlockNumber,
address targetWallet, uint256 targetNonce, bool targetDone, uint256 targetDoneBlockNumber)
public
onlyDeployer
{
// Require that upgrades have not been frozen
require(!upgradesFrozen, "Upgrades have been frozen [DriipSettlementState.sol:413]");
// Require that settlement has not been initialized/upgraded already
require(0 == walletNonceSettlementIndex[originWallet][originNonce], "Settlement exists for origin wallet and nonce [DriipSettlementState.sol:416]");
require(0 == walletNonceSettlementIndex[targetWallet][targetNonce], "Settlement exists for target wallet and nonce [DriipSettlementState.sol:417]");
// Create new settlement
settlements.length++;
// Get the 0-based index
uint256 index = settlements.length - 1;
// Update settlement
settlements[index].settledKind = settledKind;
settlements[index].settledHash = settledHash;
settlements[index].origin.nonce = originNonce;
settlements[index].origin.wallet = originWallet;
settlements[index].origin.done = originDone;
settlements[index].origin.doneBlockNumber = originDoneBlockNumber;
settlements[index].target.nonce = targetNonce;
settlements[index].target.wallet = targetWallet;
settlements[index].target.done = targetDone;
settlements[index].target.doneBlockNumber = targetDoneBlockNumber;
// Emit event
emit UpgradeSettlementEvent(settlements[index]);
// Store 1-based index value
index++;
walletSettlementIndices[originWallet].push(index);
walletSettlementIndices[targetWallet].push(index);
walletNonceSettlementIndex[originWallet][originNonce] = index;
walletNonceSettlementIndex[targetWallet][targetNonce] = index;
}
} | index is 0-based Require that index is within bounds Execute transfer Add to active Add to full deposit history Emit event | function _receiveTokensTo(uint256 index, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
private
{
require(index < partners.length, "Some error message when require fails [PartnerFund.sol:794]");
require(amount.isNonZeroPositiveInt256(), "Some error message when require fails [PartnerFund.sol:796]");
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId
)
);
require(success, "Some error message when require fails [PartnerFund.sol:805]");
partners[index].active.add(amount, currencyCt, currencyId);
partners[index].txHistory.addDeposit(amount, currencyCt, currencyId);
partners[index].fullBalanceHistory.push(
FullBalanceHistory(
partners[index].txHistory.depositsCount() - 1,
partners[index].active.get(currencyCt, currencyId),
block.number
)
);
emit ReceiveEvent(msg.sender, amount, currencyCt, currencyId);
}
| 1,006,081 |
./partial_match/42/0xb857846E0b8bd03cC0e542c6A7970b4cD625862B/sources/PriceBetting.sol | console.log("[solc] withdraw amount:", amount); | function withdraw(uint256 amount) public {
require(amount > 0, "amount cannot be 0");
_totalSupply = _totalSupply.sub(amount);
lpBalances[msg.sender] = lpBalances[msg.sender].sub(amount);
lpToken.safeTransfer(msg.sender, amount);
emit Withdrawn(msg.sender, amount);
}
| 3,450,498 |
/**
*Submitted for verification at Etherscan.io on 2021-06-09
*/
pragma solidity >0.4.24;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity >0.4.24;
/**
* @title ReailtioSafeMath256
* @dev Math operations with safety checks that throw on error
*/
library RealitioSafeMath256 {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// 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;
}
}
pragma solidity >0.4.24;
/**
* @title RealitioSafeMath32
* @dev Math operations with safety checks that throw on error
* @dev Copy of SafeMath but for uint32 instead of uint256
* @dev Deleted functions we don't use
*/
library RealitioSafeMath32 {
function add(uint32 a, uint32 b) internal pure returns (uint32) {
uint32 c = a + b;
assert(c >= a);
return c;
}
}
pragma solidity >0.4.18;
contract BalanceHolder {
IERC20 public token;
mapping(address => uint256) public balanceOf;
event LogWithdraw(
address indexed user,
uint256 amount
);
function withdraw()
public {
uint256 bal = balanceOf[msg.sender];
balanceOf[msg.sender] = 0;
require(token.transfer(msg.sender, bal));
emit LogWithdraw(msg.sender, bal);
}
}
pragma solidity >0.4.24;
contract RealitioERC20 is BalanceHolder {
using RealitioSafeMath256 for uint256;
using RealitioSafeMath32 for uint32;
address constant NULL_ADDRESS = address(0);
// History hash when no history is created, or history has been cleared
bytes32 constant NULL_HASH = bytes32(0);
// An unitinalized finalize_ts for a question will indicate an unanswered question.
uint32 constant UNANSWERED = 0;
// An unanswered reveal_ts for a commitment will indicate that it does not exist.
uint256 constant COMMITMENT_NON_EXISTENT = 0;
// Commit->reveal timeout is 1/8 of the question timeout (rounded down).
uint32 constant COMMITMENT_TIMEOUT_RATIO = 8;
event LogSetQuestionFee(
address arbitrator,
uint256 amount
);
event LogNewTemplate(
uint256 indexed template_id,
address indexed user,
string question_text
);
event LogNewQuestion(
bytes32 indexed question_id,
address indexed user,
uint256 template_id,
string question,
bytes32 indexed content_hash,
address arbitrator,
uint32 timeout,
uint32 opening_ts,
uint256 nonce,
uint256 created
);
event LogFundAnswerBounty(
bytes32 indexed question_id,
uint256 bounty_added,
uint256 bounty,
address indexed user
);
event LogNewAnswer(
bytes32 answer,
bytes32 indexed question_id,
bytes32 history_hash,
address indexed user,
uint256 bond,
uint256 ts,
bool is_commitment
);
event LogAnswerReveal(
bytes32 indexed question_id,
address indexed user,
bytes32 indexed answer_hash,
bytes32 answer,
uint256 nonce,
uint256 bond
);
event LogNotifyOfArbitrationRequest(
bytes32 indexed question_id,
address indexed user
);
event LogFinalize(
bytes32 indexed question_id,
bytes32 indexed answer
);
event LogClaim(
bytes32 indexed question_id,
address indexed user,
uint256 amount
);
struct Question {
bytes32 content_hash;
address arbitrator;
uint32 opening_ts;
uint32 timeout;
uint32 finalize_ts;
bool is_pending_arbitration;
uint256 bounty;
bytes32 best_answer;
bytes32 history_hash;
uint256 bond;
}
// Stored in a mapping indexed by commitment_id, a hash of commitment hash, question, bond.
struct Commitment {
uint32 reveal_ts;
bool is_revealed;
bytes32 revealed_answer;
}
// Only used when claiming more bonds than fits into a transaction
// Stored in a mapping indexed by question_id.
struct Claim {
address payee;
uint256 last_bond;
uint256 queued_funds;
}
uint256 nextTemplateID = 0;
mapping(uint256 => uint256) public templates;
mapping(uint256 => bytes32) public template_hashes;
mapping(bytes32 => Question) public questions;
mapping(bytes32 => Claim) public question_claims;
mapping(bytes32 => Commitment) public commitments;
mapping(address => uint256) public arbitrator_question_fees;
modifier onlyArbitrator(bytes32 question_id) {
require(msg.sender == questions[question_id].arbitrator, "msg.sender must be arbitrator");
_;
}
modifier stateAny() {
_;
}
modifier stateNotCreated(bytes32 question_id) {
require(questions[question_id].timeout == 0, "question must not exist");
_;
}
modifier stateOpen(bytes32 question_id) {
require(questions[question_id].timeout > 0, "question must exist");
require(!questions[question_id].is_pending_arbitration, "question must not be pending arbitration");
uint32 finalize_ts = questions[question_id].finalize_ts;
require(finalize_ts == UNANSWERED || finalize_ts > uint32(now), "finalization deadline must not have passed");
uint32 opening_ts = questions[question_id].opening_ts;
require(opening_ts == 0 || opening_ts <= uint32(now), "opening date must have passed");
_;
}
modifier statePendingArbitration(bytes32 question_id) {
require(questions[question_id].is_pending_arbitration, "question must be pending arbitration");
_;
}
modifier stateOpenOrPendingArbitration(bytes32 question_id) {
require(questions[question_id].timeout > 0, "question must exist");
uint32 finalize_ts = questions[question_id].finalize_ts;
require(finalize_ts == UNANSWERED || finalize_ts > uint32(now), "finalization dealine must not have passed");
uint32 opening_ts = questions[question_id].opening_ts;
require(opening_ts == 0 || opening_ts <= uint32(now), "opening date must have passed");
_;
}
modifier stateFinalized(bytes32 question_id) {
require(isFinalized(question_id), "question must be finalized");
_;
}
modifier bondMustDouble(bytes32 question_id, uint256 tokens) {
require(tokens > 0, "bond must be positive");
require(tokens >= (questions[question_id].bond.mul(2)), "bond must be double at least previous bond");
_;
}
modifier previousBondMustNotBeatMaxPrevious(bytes32 question_id, uint256 max_previous) {
if (max_previous > 0) {
require(questions[question_id].bond <= max_previous, "bond must exceed max_previous");
}
_;
}
function setToken(IERC20 _token)
public
{
require(token == IERC20(0x0), "Token can only be initialized once");
token = _token;
}
/// @notice Constructor, sets up some initial templates
/// @dev Creates some generalized templates for different question types used in the DApp.
constructor()
public {
createTemplate('{"title": "%s", "type": "bool", "category": "%s", "lang": "%s"}');
createTemplate('{"title": "%s", "type": "uint", "decimals": 18, "category": "%s", "lang": "%s"}');
createTemplate('{"title": "%s", "type": "single-select", "outcomes": [%s], "category": "%s", "lang": "%s"}');
createTemplate('{"title": "%s", "type": "multiple-select", "outcomes": [%s], "category": "%s", "lang": "%s"}');
createTemplate('{"title": "%s", "type": "datetime", "category": "%s", "lang": "%s"}');
}
/// @notice Function for arbitrator to set an optional per-question fee.
/// @dev The per-question fee, charged when a question is asked, is intended as an anti-spam measure.
/// @param fee The fee to be charged by the arbitrator when a question is asked
function setQuestionFee(uint256 fee)
stateAny()
external {
arbitrator_question_fees[msg.sender] = fee;
emit LogSetQuestionFee(msg.sender, fee);
}
/// @notice Create a reusable template, which should be a JSON document.
/// Placeholders should use gettext() syntax, eg %s.
/// @dev Template data is only stored in the event logs, but its block number is kept in contract storage.
/// @param content The template content
/// @return The ID of the newly-created template, which is created sequentially.
function createTemplate(string memory content)
stateAny()
public returns (uint256) {
uint256 id = nextTemplateID;
templates[id] = block.number;
template_hashes[id] = keccak256(abi.encodePacked(content));
emit LogNewTemplate(id, msg.sender, content);
nextTemplateID = id.add(1);
return id;
}
/// @notice Create a new reusable template and use it to ask a question
/// @dev Template data is only stored in the event logs, but its block number is kept in contract storage.
/// @param content The template content
/// @param question A string containing the parameters that will be passed into the template to make the question
/// @param arbitrator The arbitration contract that will have the final word on the answer if there is a dispute
/// @param timeout How long the contract should wait after the answer is changed before finalizing on that answer
/// @param opening_ts If set, the earliest time it should be possible to answer the question.
/// @param nonce A user-specified nonce used in the question ID. Change it to repeat a question.
/// @return The ID of the newly-created template, which is created sequentially.
function createTemplateAndAskQuestion(
string memory content,
string memory question, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce
)
// stateNotCreated is enforced by the internal _askQuestion
public returns (bytes32) {
uint256 template_id = createTemplate(content);
return askQuestion(template_id, question, arbitrator, timeout, opening_ts, nonce);
}
/// @notice Ask a new question without a bounty and return the ID
/// @dev Template data is only stored in the event logs, but its block number is kept in contract storage.
/// @dev Calling without the token param will only work if there is no arbitrator-set question fee.
/// @dev This has the same function signature as askQuestion() in the non-ERC20 version, which is optionally payable.
/// @param template_id The ID number of the template the question will use
/// @param question A string containing the parameters that will be passed into the template to make the question
/// @param arbitrator The arbitration contract that will have the final word on the answer if there is a dispute
/// @param timeout How long the contract should wait after the answer is changed before finalizing on that answer
/// @param opening_ts If set, the earliest time it should be possible to answer the question.
/// @param nonce A user-specified nonce used in the question ID. Change it to repeat a question.
/// @return The ID of the newly-created question, created deterministically.
function askQuestion(uint256 template_id, string memory question, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce)
// stateNotCreated is enforced by the internal _askQuestion
public returns (bytes32) {
require(templates[template_id] > 0, "template must exist");
bytes32 content_hash = keccak256(abi.encodePacked(template_id, opening_ts, question));
bytes32 question_id = keccak256(abi.encodePacked(content_hash, arbitrator, timeout, msg.sender, nonce));
_askQuestion(question_id, content_hash, arbitrator, timeout, opening_ts, 0);
emit LogNewQuestion(question_id, msg.sender, template_id, question, content_hash, arbitrator, timeout, opening_ts, nonce, now);
return question_id;
}
/// @notice Ask a new question with a bounty and return the ID
/// @dev Template data is only stored in the event logs, but its block number is kept in contract storage.
/// @param template_id The ID number of the template the question will use
/// @param question A string containing the parameters that will be passed into the template to make the question
/// @param arbitrator The arbitration contract that will have the final word on the answer if there is a dispute
/// @param timeout How long the contract should wait after the answer is changed before finalizing on that answer
/// @param opening_ts If set, the earliest time it should be possible to answer the question.
/// @param nonce A user-specified nonce used in the question ID. Change it to repeat a question.
/// @param tokens The combined initial question bounty and question fee
/// @return The ID of the newly-created question, created deterministically.
function askQuestionERC20(uint256 template_id, string memory question, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce, uint256 tokens)
// stateNotCreated is enforced by the internal _askQuestion
public returns (bytes32) {
_deductTokensOrRevert(tokens);
require(templates[template_id] > 0, "template must exist");
bytes32 content_hash = keccak256(abi.encodePacked(template_id, opening_ts, question));
bytes32 question_id = keccak256(abi.encodePacked(content_hash, arbitrator, timeout, msg.sender, nonce));
_askQuestion(question_id, content_hash, arbitrator, timeout, opening_ts, tokens);
emit LogNewQuestion(question_id, msg.sender, template_id, question, content_hash, arbitrator, timeout, opening_ts, nonce, now);
return question_id;
}
function _deductTokensOrRevert(uint256 tokens)
internal {
if (tokens == 0) {
return;
}
uint256 bal = balanceOf[msg.sender];
// Deduct any tokens you have in your internal balance first
if (bal > 0) {
if (bal >= tokens) {
balanceOf[msg.sender] = bal.sub(tokens);
return;
} else {
tokens = tokens.sub(bal);
balanceOf[msg.sender] = 0;
}
}
// Now we need to charge the rest from
require(token.transferFrom(msg.sender, address(this), tokens), "Transfer of tokens failed, insufficient approved balance?");
return;
}
function _askQuestion(bytes32 question_id, bytes32 content_hash, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 tokens)
stateNotCreated(question_id)
internal {
uint256 bounty = tokens;
// A timeout of 0 makes no sense, and we will use this to check existence
require(timeout > 0, "timeout must be positive");
require(timeout < 365 days, "timeout must be less than 365 days");
require(arbitrator != NULL_ADDRESS, "arbitrator must be set");
// The arbitrator can set a fee for asking a question.
// This is intended as an anti-spam defence.
// The fee is waived if the arbitrator is asking the question.
// This allows them to set an impossibly high fee and make users proxy the question through them.
// This would allow more sophisticated pricing, question whitelisting etc.
if (msg.sender != arbitrator) {
uint256 question_fee = arbitrator_question_fees[arbitrator];
require(bounty >= question_fee, "Tokens provided must cover question fee");
bounty = bounty.sub(question_fee);
balanceOf[arbitrator] = balanceOf[arbitrator].add(question_fee);
}
questions[question_id].content_hash = content_hash;
questions[question_id].arbitrator = arbitrator;
questions[question_id].opening_ts = opening_ts;
questions[question_id].timeout = timeout;
questions[question_id].bounty = bounty;
}
/// @notice Add funds to the bounty for a question
/// @dev Add bounty funds after the initial question creation. Can be done any time until the question is finalized.
/// @param question_id The ID of the question you wish to fund
/// @param tokens The number of tokens to fund
function fundAnswerBountyERC20(bytes32 question_id, uint256 tokens)
stateOpen(question_id)
external {
_deductTokensOrRevert(tokens);
questions[question_id].bounty = questions[question_id].bounty.add(tokens);
emit LogFundAnswerBounty(question_id, tokens, questions[question_id].bounty, msg.sender);
}
/// @notice Submit an answer for a question.
/// @dev Adds the answer to the history and updates the current "best" answer.
/// May be subject to front-running attacks; Substitute submitAnswerCommitment()->submitAnswerReveal() to prevent them.
/// @param question_id The ID of the question
/// @param answer The answer, encoded into bytes32
/// @param max_previous If specified, reverts if a bond higher than this was submitted after you sent your transaction.
/// @param tokens The amount of tokens to submit
function submitAnswerERC20(bytes32 question_id, bytes32 answer, uint256 max_previous, uint256 tokens)
stateOpen(question_id)
bondMustDouble(question_id, tokens)
previousBondMustNotBeatMaxPrevious(question_id, max_previous)
external {
_deductTokensOrRevert(tokens);
_addAnswerToHistory(question_id, answer, msg.sender, tokens, false);
_updateCurrentAnswer(question_id, answer, questions[question_id].timeout);
}
// @notice Verify and store a commitment, including an appropriate timeout
// @param question_id The ID of the question to store
// @param commitment The ID of the commitment
function _storeCommitment(bytes32 question_id, bytes32 commitment_id)
internal
{
require(commitments[commitment_id].reveal_ts == COMMITMENT_NON_EXISTENT, "commitment must not already exist");
uint32 commitment_timeout = questions[question_id].timeout / COMMITMENT_TIMEOUT_RATIO;
commitments[commitment_id].reveal_ts = uint32(now).add(commitment_timeout);
}
/// @notice Submit the hash of an answer, laying your claim to that answer if you reveal it in a subsequent transaction.
/// @dev Creates a hash, commitment_id, uniquely identifying this answer, to this question, with this bond.
/// The commitment_id is stored in the answer history where the answer would normally go.
/// Does not update the current best answer - this is left to the later submitAnswerReveal() transaction.
/// @param question_id The ID of the question
/// @param answer_hash The hash of your answer, plus a nonce that you will later reveal
/// @param max_previous If specified, reverts if a bond higher than this was submitted after you sent your transaction.
/// @param _answerer If specified, the address to be given as the question answerer. Defaults to the sender.
/// @param tokens Number of tokens sent
/// @dev Specifying the answerer is useful if you want to delegate the commit-and-reveal to a third-party.
function submitAnswerCommitmentERC20(bytes32 question_id, bytes32 answer_hash, uint256 max_previous, address _answerer, uint256 tokens)
stateOpen(question_id)
bondMustDouble(question_id, tokens)
previousBondMustNotBeatMaxPrevious(question_id, max_previous)
external {
_deductTokensOrRevert(tokens);
bytes32 commitment_id = keccak256(abi.encodePacked(question_id, answer_hash, tokens));
address answerer = (_answerer == NULL_ADDRESS) ? msg.sender : _answerer;
_storeCommitment(question_id, commitment_id);
_addAnswerToHistory(question_id, commitment_id, answerer, tokens, true);
}
/// @notice Submit the answer whose hash you sent in a previous submitAnswerCommitment() transaction
/// @dev Checks the parameters supplied recreate an existing commitment, and stores the revealed answer
/// Updates the current answer unless someone has since supplied a new answer with a higher bond
/// msg.sender is intentionally not restricted to the user who originally sent the commitment;
/// For example, the user may want to provide the answer+nonce to a third-party service and let them send the tx
/// NB If we are pending arbitration, it will be up to the arbitrator to wait and see any outstanding reveal is sent
/// @param question_id The ID of the question
/// @param answer The answer, encoded as bytes32
/// @param nonce The nonce that, combined with the answer, recreates the answer_hash you gave in submitAnswerCommitment()
/// @param bond The bond that you paid in your submitAnswerCommitment() transaction
function submitAnswerReveal(bytes32 question_id, bytes32 answer, uint256 nonce, uint256 bond)
stateOpenOrPendingArbitration(question_id)
external {
bytes32 answer_hash = keccak256(abi.encodePacked(answer, nonce));
bytes32 commitment_id = keccak256(abi.encodePacked(question_id, answer_hash, bond));
require(!commitments[commitment_id].is_revealed, "commitment must not have been revealed yet");
require(commitments[commitment_id].reveal_ts > uint32(now), "reveal deadline must not have passed");
commitments[commitment_id].revealed_answer = answer;
commitments[commitment_id].is_revealed = true;
if (bond == questions[question_id].bond) {
_updateCurrentAnswer(question_id, answer, questions[question_id].timeout);
}
emit LogAnswerReveal(question_id, msg.sender, answer_hash, answer, nonce, bond);
}
function _addAnswerToHistory(bytes32 question_id, bytes32 answer_or_commitment_id, address answerer, uint256 bond, bool is_commitment)
internal
{
bytes32 new_history_hash = keccak256(abi.encodePacked(questions[question_id].history_hash, answer_or_commitment_id, bond, answerer, is_commitment));
// Update the current bond level, if there's a bond (ie anything except arbitration)
if (bond > 0) {
questions[question_id].bond = bond;
}
questions[question_id].history_hash = new_history_hash;
emit LogNewAnswer(answer_or_commitment_id, question_id, new_history_hash, answerer, bond, now, is_commitment);
}
function _updateCurrentAnswer(bytes32 question_id, bytes32 answer, uint32 timeout_secs)
internal {
questions[question_id].best_answer = answer;
questions[question_id].finalize_ts = uint32(now).add(timeout_secs);
}
/// @notice Notify the contract that the arbitrator has been paid for a question, freezing it pending their decision.
/// @dev The arbitrator contract is trusted to only call this if they've been paid, and tell us who paid them.
/// @param question_id The ID of the question
/// @param requester The account that requested arbitration
/// @param max_previous If specified, reverts if a bond higher than this was submitted after you sent your transaction.
function notifyOfArbitrationRequest(bytes32 question_id, address requester, uint256 max_previous)
onlyArbitrator(question_id)
stateOpen(question_id)
previousBondMustNotBeatMaxPrevious(question_id, max_previous)
external {
require(questions[question_id].bond > 0, "Question must already have an answer when arbitration is requested");
questions[question_id].is_pending_arbitration = true;
emit LogNotifyOfArbitrationRequest(question_id, requester);
}
/// @notice Submit the answer for a question, for use by the arbitrator.
/// @dev Doesn't require (or allow) a bond.
/// If the current final answer is correct, the account should be whoever submitted it.
/// If the current final answer is wrong, the account should be whoever paid for arbitration.
/// However, the answerer stipulations are not enforced by the contract.
/// @param question_id The ID of the question
/// @param answer The answer, encoded into bytes32
/// @param answerer The account credited with this answer for the purpose of bond claims
function submitAnswerByArbitrator(bytes32 question_id, bytes32 answer, address answerer)
onlyArbitrator(question_id)
statePendingArbitration(question_id)
external {
require(answerer != NULL_ADDRESS, "answerer must be provided");
emit LogFinalize(question_id, answer);
questions[question_id].is_pending_arbitration = false;
_addAnswerToHistory(question_id, answer, answerer, 0, false);
_updateCurrentAnswer(question_id, answer, 0);
}
/// @notice Report whether the answer to the specified question is finalized
/// @param question_id The ID of the question
/// @return Return true if finalized
function isFinalized(bytes32 question_id)
view public returns (bool) {
uint32 finalize_ts = questions[question_id].finalize_ts;
return ( !questions[question_id].is_pending_arbitration && (finalize_ts > UNANSWERED) && (finalize_ts <= uint32(now)) );
}
/// @notice (Deprecated) Return the final answer to the specified question, or revert if there isn't one
/// @param question_id The ID of the question
/// @return The answer formatted as a bytes32
function getFinalAnswer(bytes32 question_id)
stateFinalized(question_id)
external view returns (bytes32) {
return questions[question_id].best_answer;
}
/// @notice Return the final answer to the specified question, or revert if there isn't one
/// @param question_id The ID of the question
/// @return The answer formatted as a bytes32
function resultFor(bytes32 question_id)
stateFinalized(question_id)
external view returns (bytes32) {
return questions[question_id].best_answer;
}
/// @notice Return the final answer to the specified question, provided it matches the specified criteria.
/// @dev Reverts if the question is not finalized, or if it does not match the specified criteria.
/// @param question_id The ID of the question
/// @param content_hash The hash of the question content (template ID + opening time + question parameter string)
/// @param arbitrator The arbitrator chosen for the question (regardless of whether they are asked to arbitrate)
/// @param min_timeout The timeout set in the initial question settings must be this high or higher
/// @param min_bond The bond sent with the final answer must be this high or higher
/// @return The answer formatted as a bytes32
function getFinalAnswerIfMatches(
bytes32 question_id,
bytes32 content_hash, address arbitrator, uint32 min_timeout, uint256 min_bond
)
stateFinalized(question_id)
external view returns (bytes32) {
require(content_hash == questions[question_id].content_hash, "content hash must match");
require(arbitrator == questions[question_id].arbitrator, "arbitrator must match");
require(min_timeout <= questions[question_id].timeout, "timeout must be long enough");
require(min_bond <= questions[question_id].bond, "bond must be high enough");
return questions[question_id].best_answer;
}
/// @notice Assigns the winnings (bounty and bonds) to everyone who gave the accepted answer
/// Caller must provide the answer history, in reverse order
/// @dev Works up the chain and assign bonds to the person who gave the right answer
/// If someone gave the winning answer earlier, they must get paid from the higher bond
/// That means we can't pay out the bond added at n until we have looked at n-1
/// The first answer is authenticated by checking against the stored history_hash.
/// One of the inputs to history_hash is the history_hash before it, so we use that to authenticate the next entry, etc
/// Once we get to a null hash we'll know we're done and there are no more answers.
/// Usually you would call the whole thing in a single transaction, but if not then the data is persisted to pick up later.
/// @param question_id The ID of the question
/// @param history_hashes Second-last-to-first, the hash of each history entry. (Final one should be empty).
/// @param addrs Last-to-first, the address of each answerer or commitment sender
/// @param bonds Last-to-first, the bond supplied with each answer or commitment
/// @param answers Last-to-first, each answer supplied, or commitment ID if the answer was supplied with commit->reveal
function claimWinnings(
bytes32 question_id,
bytes32[] memory history_hashes, address[] memory addrs, uint256[] memory bonds, bytes32[] memory answers
)
stateFinalized(question_id)
public {
require(history_hashes.length > 0, "at least one history hash entry must be provided");
// These are only set if we split our claim over multiple transactions.
address payee = question_claims[question_id].payee;
uint256 last_bond = question_claims[question_id].last_bond;
uint256 queued_funds = question_claims[question_id].queued_funds;
// Starts as the hash of the final answer submitted. It'll be cleared when we're done.
// If we're splitting the claim over multiple transactions, it'll be the hash where we left off last time
bytes32 last_history_hash = questions[question_id].history_hash;
bytes32 best_answer = questions[question_id].best_answer;
uint256 i;
for (i = 0; i < history_hashes.length; i++) {
// Check input against the history hash, and see which of 2 possible values of is_commitment fits.
bool is_commitment = _verifyHistoryInputOrRevert(last_history_hash, history_hashes[i], answers[i], bonds[i], addrs[i]);
queued_funds = queued_funds.add(last_bond);
(queued_funds, payee) = _processHistoryItem(
question_id, best_answer, queued_funds, payee,
addrs[i], bonds[i], answers[i], is_commitment);
// Line the bond up for next time, when it will be added to somebody's queued_funds
last_bond = bonds[i];
last_history_hash = history_hashes[i];
}
if (last_history_hash != NULL_HASH) {
// We haven't yet got to the null hash (1st answer), ie the caller didn't supply the full answer chain.
// Persist the details so we can pick up later where we left off later.
// If we know who to pay we can go ahead and pay them out, only keeping back last_bond
// (We always know who to pay unless all we saw were unrevealed commits)
if (payee != NULL_ADDRESS) {
_payPayee(question_id, payee, queued_funds);
queued_funds = 0;
}
question_claims[question_id].payee = payee;
question_claims[question_id].last_bond = last_bond;
question_claims[question_id].queued_funds = queued_funds;
} else {
// There is nothing left below us so the payee can keep what remains
_payPayee(question_id, payee, queued_funds.add(last_bond));
delete question_claims[question_id];
}
questions[question_id].history_hash = last_history_hash;
}
function _payPayee(bytes32 question_id, address payee, uint256 value)
internal {
balanceOf[payee] = balanceOf[payee].add(value);
emit LogClaim(question_id, payee, value);
}
function _verifyHistoryInputOrRevert(
bytes32 last_history_hash,
bytes32 history_hash, bytes32 answer, uint256 bond, address addr
)
internal pure returns (bool) {
if (last_history_hash == keccak256(abi.encodePacked(history_hash, answer, bond, addr, true)) ) {
return true;
}
if (last_history_hash == keccak256(abi.encodePacked(history_hash, answer, bond, addr, false)) ) {
return false;
}
revert("History input provided did not match the expected hash");
}
function _processHistoryItem(
bytes32 question_id, bytes32 best_answer,
uint256 queued_funds, address payee,
address addr, uint256 bond, bytes32 answer, bool is_commitment
)
internal returns (uint256, address) {
// For commit-and-reveal, the answer history holds the commitment ID instead of the answer.
// We look at the referenced commitment ID and switch in the actual answer.
if (is_commitment) {
bytes32 commitment_id = answer;
// If it's a commit but it hasn't been revealed, it will always be considered wrong.
if (!commitments[commitment_id].is_revealed) {
delete commitments[commitment_id];
return (queued_funds, payee);
} else {
answer = commitments[commitment_id].revealed_answer;
delete commitments[commitment_id];
}
}
if (answer == best_answer) {
if (payee == NULL_ADDRESS) {
// The entry is for the first payee we come to, ie the winner.
// They get the question bounty.
payee = addr;
queued_funds = queued_funds.add(questions[question_id].bounty);
questions[question_id].bounty = 0;
} else if (addr != payee) {
// Answerer has changed, ie we found someone lower down who needs to be paid
// The lower answerer will take over receiving bonds from higher answerer.
// They should also be paid the takeover fee, which is set at a rate equivalent to their bond.
// (This is our arbitrary rule, to give consistent right-answerers a defence against high-rollers.)
// There should be enough for the fee, but if not, take what we have.
// There's an edge case involving weird arbitrator behaviour where we may be short.
uint256 answer_takeover_fee = (queued_funds >= bond) ? bond : queued_funds;
// Settle up with the old (higher-bonded) payee
_payPayee(question_id, payee, queued_funds.sub(answer_takeover_fee));
// Now start queued_funds again for the new (lower-bonded) payee
payee = addr;
queued_funds = answer_takeover_fee;
}
}
return (queued_funds, payee);
}
/// @notice Convenience function to assign bounties/bonds for multiple questions in one go, then withdraw all your funds.
/// Caller must provide the answer history for each question, in reverse order
/// @dev Can be called by anyone to assign bonds/bounties, but funds are only withdrawn for the user making the call.
/// @param question_ids The IDs of the questions you want to claim for
/// @param lengths The number of history entries you will supply for each question ID
/// @param hist_hashes In a single list for all supplied questions, the hash of each history entry.
/// @param addrs In a single list for all supplied questions, the address of each answerer or commitment sender
/// @param bonds In a single list for all supplied questions, the bond supplied with each answer or commitment
/// @param answers In a single list for all supplied questions, each answer supplied, or commitment ID
function claimMultipleAndWithdrawBalance(
bytes32[] memory question_ids, uint256[] memory lengths,
bytes32[] memory hist_hashes, address[] memory addrs, uint256[] memory bonds, bytes32[] memory answers
)
stateAny() // The finalization checks are done in the claimWinnings function
public {
uint256 qi;
uint256 i;
for (qi = 0; qi < question_ids.length; qi++) {
bytes32 qid = question_ids[qi];
uint256 ln = lengths[qi];
bytes32[] memory hh = new bytes32[](ln);
address[] memory ad = new address[](ln);
uint256[] memory bo = new uint256[](ln);
bytes32[] memory an = new bytes32[](ln);
uint256 j;
for (j = 0; j < ln; j++) {
hh[j] = hist_hashes[i];
ad[j] = addrs[i];
bo[j] = bonds[i];
an[j] = answers[i];
i++;
}
claimWinnings(qid, hh, ad, bo, an);
}
withdraw();
}
/// @notice Returns the questions's content hash, identifying the question content
/// @param question_id The ID of the question
function getContentHash(bytes32 question_id)
public view returns(bytes32) {
return questions[question_id].content_hash;
}
/// @notice Returns the arbitrator address for the question
/// @param question_id The ID of the question
function getArbitrator(bytes32 question_id)
public view returns(address) {
return questions[question_id].arbitrator;
}
/// @notice Returns the timestamp when the question can first be answered
/// @param question_id The ID of the question
function getOpeningTS(bytes32 question_id)
public view returns(uint32) {
return questions[question_id].opening_ts;
}
/// @notice Returns the timeout in seconds used after each answer
/// @param question_id The ID of the question
function getTimeout(bytes32 question_id)
public view returns(uint32) {
return questions[question_id].timeout;
}
/// @notice Returns the timestamp at which the question will be/was finalized
/// @param question_id The ID of the question
function getFinalizeTS(bytes32 question_id)
public view returns(uint32) {
return questions[question_id].finalize_ts;
}
/// @notice Returns whether the question is pending arbitration
/// @param question_id The ID of the question
function isPendingArbitration(bytes32 question_id)
public view returns(bool) {
return questions[question_id].is_pending_arbitration;
}
/// @notice Returns the current total unclaimed bounty
/// @dev Set back to zero once the bounty has been claimed
/// @param question_id The ID of the question
function getBounty(bytes32 question_id)
public view returns(uint256) {
return questions[question_id].bounty;
}
/// @notice Returns the current best answer
/// @param question_id The ID of the question
function getBestAnswer(bytes32 question_id)
public view returns(bytes32) {
return questions[question_id].best_answer;
}
/// @notice Returns the history hash of the question
/// @param question_id The ID of the question
/// @dev Updated on each answer, then rewound as each is claimed
function getHistoryHash(bytes32 question_id)
public view returns(bytes32) {
return questions[question_id].history_hash;
}
/// @notice Returns the highest bond posted so far for a question
/// @param question_id The ID of the question
function getBond(bytes32 question_id)
public view returns(uint256) {
return questions[question_id].bond;
}
} | Submit the answer for a question, for use by the arbitrator. Doesn't require (or allow) a bond. If the current final answer is correct, the account should be whoever submitted it. If the current final answer is wrong, the account should be whoever paid for arbitration. However, the answerer stipulations are not enforced by the contract. question_id The ID of the question answer The answer, encoded into bytes32 answerer The account credited with this answer for the purpose of bond claims | function submitAnswerByArbitrator(bytes32 question_id, bytes32 answer, address answerer)
onlyArbitrator(question_id)
statePendingArbitration(question_id)
external {
require(answerer != NULL_ADDRESS, "answerer must be provided");
emit LogFinalize(question_id, answer);
questions[question_id].is_pending_arbitration = false;
_addAnswerToHistory(question_id, answer, answerer, 0, false);
_updateCurrentAnswer(question_id, answer, 0);
}
| 1,537,589 |
pragma solidity ^0.4.24;
/*
*
* ____ ____ .__ _________ .__ .__
* \ \ / /____ | | __ __ ____ \_ ___ \| |__ _____ |__| ____
* \ Y /\__ \ | | | | \_/ __ \ / \ \/| | \\__ \ | |/ \
* \ / / __ \| |_| | /\ ___/ \ \___| Y \/ __ \| | | \
* \___/ (____ /____/____/ \___ > \______ /___| (____ /__|___| /
* \/ \/ \/ \/ \/ \/
*
*/
// Contract must have an owner
contract Owned {
address public owner;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function setOwner(address _owner) onlyOwner public {
owner = _owner;
}
}
// SafeMath methods
contract SafeMath {
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
assert(c >= _a);
return c;
}
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_a >= _b);
return _a - _b;
}
function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a * _b;
assert(_a == 0 || c / _a == _b);
return c;
}
}
// for safety methods
interface ERC20Token {
function transfer(address _to, uint256 _value) external returns (bool);
function balanceOf(address _addr) external view returns (uint256);
function decimals() external view returns (uint8);
}
// the main ERC20-compliant contract
contract Token is SafeMath, Owned {
uint256 private constant DAY_IN_SECONDS = 86400;
string public constant standard = "0.861057";
string public name = "";
string public symbol = "";
uint8 public decimals = 0;
uint256 public totalSupply = 0;
mapping (address => uint256) public balanceP;
mapping (address => mapping (address => uint256)) public allowance;
mapping (address => uint256[]) public lockTime;
mapping (address => uint256[]) public lockValue;
mapping (address => uint256) public lockNum;
mapping (address => bool) public locker;
uint256 public later = 0;
uint256 public earlier = 0;
// standard ERC20 events
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// timelock-related events
event TransferLocked(address indexed _from, address indexed _to, uint256 _time, uint256 _value);
event TokenUnlocked(address indexed _address, uint256 _value);
// safety method-related events
event WrongTokenEmptied(address indexed _token, address indexed _addr, uint256 _amount);
event WrongEtherEmptied(address indexed _addr, uint256 _amount);
// constructor for the ERC20 Token
constructor(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply) public {
require(bytes(_name).length > 0 && bytes(_symbol).length > 0);
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = _totalSupply;
balanceP[msg.sender] = _totalSupply;
}
modifier validAddress(address _address) {
require(_address != 0x0);
_;
}
// owner may add or remove a locker address for the contract
function addLocker(address _address) public validAddress(_address) onlyOwner {
locker[_address] = true;
}
function removeLocker(address _address) public validAddress(_address) onlyOwner {
locker[_address] = false;
}
// fast-forward the timelocks for all accounts
function setUnlockEarlier(uint256 _earlier) public onlyOwner {
earlier = add(earlier, _earlier);
}
// delay the timelocks for all accounts
function setUnlockLater(uint256 _later) public onlyOwner {
later = add(later, _later);
}
// show unlocked balance of an account
function balanceUnlocked(address _address) public view returns (uint256 _balance) {
_balance = balanceP[_address];
uint256 i = 0;
while (i < lockNum[_address]) {
if (add(now, earlier) >= add(lockTime[_address][i], later)) _balance = add(_balance, lockValue[_address][i]);
i++;
}
return _balance;
}
// show timelocked balance of an account
function balanceLocked(address _address) public view returns (uint256 _balance) {
_balance = 0;
uint256 i = 0;
while (i < lockNum[_address]) {
if (add(now, earlier) < add(lockTime[_address][i], later)) _balance = add(_balance, lockValue[_address][i]);
i++;
}
return _balance;
}
// standard ERC20 balanceOf with timelock added
function balanceOf(address _address) public view returns (uint256 _balance) {
_balance = balanceP[_address];
uint256 i = 0;
while (i < lockNum[_address]) {
_balance = add(_balance, lockValue[_address][i]);
i++;
}
return _balance;
}
// show timelocks in an account
function showTime(address _address) public view validAddress(_address) returns (uint256[] _time) {
uint i = 0;
uint256[] memory tempLockTime = new uint256[](lockNum[_address]);
while (i < lockNum[_address]) {
tempLockTime[i] = sub(add(lockTime[_address][i], later), earlier);
i++;
}
return tempLockTime;
}
// show values locked in an account's timelocks
function showValue(address _address) public view validAddress(_address) returns (uint256[] _value) {
return lockValue[_address];
}
// Calculate and process the timelock states of an account
function calcUnlock(address _address) private {
uint256 i = 0;
uint256 j = 0;
uint256[] memory currentLockTime;
uint256[] memory currentLockValue;
uint256[] memory newLockTime = new uint256[](lockNum[_address]);
uint256[] memory newLockValue = new uint256[](lockNum[_address]);
currentLockTime = lockTime[_address];
currentLockValue = lockValue[_address];
while (i < lockNum[_address]) {
if (add(now, earlier) >= add(currentLockTime[i], later)) {
balanceP[_address] = add(balanceP[_address], currentLockValue[i]);
emit TokenUnlocked(_address, currentLockValue[i]);
} else {
newLockTime[j] = currentLockTime[i];
newLockValue[j] = currentLockValue[i];
j++;
}
i++;
}
uint256[] memory trimLockTime = new uint256[](j);
uint256[] memory trimLockValue = new uint256[](j);
i = 0;
while (i < j) {
trimLockTime[i] = newLockTime[i];
trimLockValue[i] = newLockValue[i];
i++;
}
lockTime[_address] = trimLockTime;
lockValue[_address] = trimLockValue;
lockNum[_address] = j;
}
// standard ERC20 transfer
function transfer(address _to, uint256 _value) public validAddress(_to) returns (bool success) {
if (lockNum[msg.sender] > 0) calcUnlock(msg.sender);
require(balanceP[msg.sender] >= _value && _value >= 0);
balanceP[msg.sender] = sub(balanceP[msg.sender], _value);
balanceP[_to] = add(balanceP[_to], _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
// transfer Token with timelocks
function transferLocked(address _to, uint256[] _time, uint256[] _value) public validAddress(_to) returns (bool success) {
require(_value.length == _time.length);
if (lockNum[msg.sender] > 0) calcUnlock(msg.sender);
uint256 i = 0;
uint256 totalValue = 0;
while (i < _value.length) {
totalValue = add(totalValue, _value[i]);
i++;
}
require(balanceP[msg.sender] >= totalValue && totalValue >= 0);
i = 0;
while (i < _time.length) {
balanceP[msg.sender] = sub(balanceP[msg.sender], _value[i]);
lockTime[_to].length = lockNum[_to]+1;
lockValue[_to].length = lockNum[_to]+1;
lockTime[_to][lockNum[_to]] = add(now, _time[i]);
lockValue[_to][lockNum[_to]] = _value[i];
// emit custom TransferLocked event
emit TransferLocked(msg.sender, _to, lockTime[_to][lockNum[_to]], lockValue[_to][lockNum[_to]]);
// emit standard Transfer event for wallets
emit Transfer(msg.sender, _to, lockValue[_to][lockNum[_to]]);
lockNum[_to]++;
i++;
}
return true;
}
// lockers set by owners may transfer Token with timelocks
function transferLockedFrom(address _from, address _to, uint256[] _time, uint256[] _value) public
validAddress(_from) validAddress(_to) returns (bool success) {
require(locker[msg.sender]);
require(_value.length == _time.length);
if (lockNum[_from] > 0) calcUnlock(_from);
uint256 i = 0;
uint256 totalValue = 0;
while (i < _value.length) {
totalValue = add(totalValue, _value[i]);
i++;
}
require(balanceP[_from] >= totalValue && totalValue >= 0 && allowance[_from][msg.sender] >= totalValue);
i = 0;
while (i < _time.length) {
balanceP[_from] = sub(balanceP[_from], _value[i]);
allowance[_from][msg.sender] = sub(allowance[_from][msg.sender], _value[i]);
lockTime[_to].length = lockNum[_to]+1;
lockValue[_to].length = lockNum[_to]+1;
lockTime[_to][lockNum[_to]] = add(now, _time[i]);
lockValue[_to][lockNum[_to]] = _value[i];
// emit custom TransferLocked event
emit TransferLocked(_from, _to, lockTime[_to][lockNum[_to]], lockValue[_to][lockNum[_to]]);
// emit standard Transfer event for wallets
emit Transfer(_from, _to, lockValue[_to][lockNum[_to]]);
lockNum[_to]++;
i++;
}
return true;
}
// standard ERC20 transferFrom
function transferFrom(address _from, address _to, uint256 _value) public validAddress(_from) validAddress(_to) returns (bool success) {
if (lockNum[_from] > 0) calcUnlock(_from);
require(balanceP[_from] >= _value && _value >= 0 && allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] = sub(allowance[_from][msg.sender], _value);
balanceP[_from] = sub(balanceP[_from], _value);
balanceP[_to] = add(balanceP[_to], _value);
emit Transfer(_from, _to, _value);
return true;
}
// should only be called when first setting an allowance
function approve(address _spender, uint256 _value) public validAddress(_spender) returns (bool success) {
if (lockNum[msg.sender] > 0) calcUnlock(msg.sender);
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
// increase or decrease allowance
function increaseApproval(address _spender, uint _value) public returns (bool) {
allowance[msg.sender][_spender] = add(allowance[msg.sender][_spender], _value);
emit Approval(msg.sender, _spender, allowance[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _value) public returns (bool) {
if(_value >= allowance[msg.sender][_spender]) {
allowance[msg.sender][_spender] = 0;
} else {
allowance[msg.sender][_spender] = sub(allowance[msg.sender][_spender], _value);
}
emit Approval(msg.sender, _spender, allowance[msg.sender][_spender]);
return true;
}
// safety methods
function () public payable {
revert();
}
function emptyWrongToken(address _addr) onlyOwner public {
ERC20Token wrongToken = ERC20Token(_addr);
uint256 amount = wrongToken.balanceOf(address(this));
require(amount > 0);
require(wrongToken.transfer(msg.sender, amount));
emit WrongTokenEmptied(_addr, msg.sender, amount);
}
// shouldn't happen, just in case
function emptyWrongEther() onlyOwner public {
uint256 amount = address(this).balance;
require(amount > 0);
msg.sender.transfer(amount);
emit WrongEtherEmptied(msg.sender, amount);
}
} | standard ERC20 transferFrom | function transferFrom(address _from, address _to, uint256 _value) public validAddress(_from) validAddress(_to) returns (bool success) {
if (lockNum[_from] > 0) calcUnlock(_from);
require(balanceP[_from] >= _value && _value >= 0 && allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] = sub(allowance[_from][msg.sender], _value);
balanceP[_from] = sub(balanceP[_from], _value);
balanceP[_to] = add(balanceP[_to], _value);
emit Transfer(_from, _to, _value);
return true;
}
| 11,692,786 |
// SPDX-License-Identifer: MIT
// File: @openzeppelin/contracts/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;
}
// 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/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/introspection/IERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/access/AccessControl.sol
pragma solidity ^0.8.0;
/**
* @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());
}
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/security/Pausable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// File: @openzeppelin/contracts/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 make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: @openzeppelin/contracts/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);
}
// File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
pragma solidity ^0.8.0;
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// File: contracts/libraries/ERC20.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// File: contracts/SoulPower.sol
pragma solidity ^0.8.0;
contract SoulPower is ERC20('SoulPower', 'SOUL'), AccessControl {
address public supreme; // supreme divine
bytes32 public anunnaki; // admin role
bytes32 public thoth; // minter role
bytes32 public constant DOMAIN_TYPEHASH = // EIP-712 typehash for the contract's domain
keccak256('EIP712Domain(string name,uint chainId,address verifyingContract)');
bytes32 public constant DELEGATION_TYPEHASH = // EIP-712 typehash for the delegation struct used by the contract
keccak256('Delegation(address delegatee,uint nonce,uint expiry)');
// mappings for user accounts (address)
mapping(address => mapping(uint => Checkpoint)) public checkpoints; // vote checkpoints
mapping(address => uint) public numCheckpoints; // checkpoint count
mapping(address => uint) public nonces; // signing / validating states
mapping(address => address) internal _delegates; // each accounts' delegate
struct Checkpoint { // checkpoint for marking number of votes from a given timestamp
uint fromTime;
uint votes;
}
event NewSupreme(address supreme);
event Rethroned(bytes32 role, address oldAccount, address newAccount);
event DelegateChanged( // emitted when an account changes its delegate
address indexed delegator,
address indexed fromDelegate,
address indexed toDelegate
);
event DelegateVotesChanged( // emitted when a delegate account's vote balance changes
address indexed delegate,
uint previousBalance,
uint newBalance
);
// restricted to the house of the role passed as an object to obey
modifier obey(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
// channels the authority vested in anunnaki and thoth to the supreme
constructor() {
supreme = msg.sender; // WARNING: set to multi-sig when deploying
anunnaki = keccak256('anunnaki'); // alpha supreme
thoth = keccak256('thoth'); // god of wisdom and magic
_divinationRitual(DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_ROLE, supreme); // supreme as root admin
_divinationRitual(anunnaki, anunnaki, supreme); // anunnaki as admin of anunnaki
_divinationRitual(thoth, anunnaki, supreme); // anunnaki as admin of thoth
mint(supreme, 50_000_000 * 1e18); // mints initial supply of 50M
}
// solidifies roles (internal)
function _divinationRitual(bytes32 _role, bytes32 _adminRole, address _account) internal {
_setupRole(_role, _account);
_setRoleAdmin(_role, _adminRole);
}
// grants `role` to `newAccount` && renounces `role` from `oldAccount` (public role)
function rethroneRitual(bytes32 role, address oldAccount, address newAccount) public obey(role) {
require(oldAccount != newAccount, 'must be a new address');
grantRole(role, newAccount); // grants new account
renounceRole(role, oldAccount); // removes old account of role
emit Rethroned(role, oldAccount, newAccount);
}
// updates supreme address (public anunnaki)
function newSupreme(address _supreme) public obey(anunnaki) {
require(supreme != _supreme, 'make a change, be the change'); // prevents self-destruct
rethroneRitual(DEFAULT_ADMIN_ROLE, supreme, _supreme); // empowers new supreme
supreme = _supreme;
emit NewSupreme(supreme);
}
// checks whether sender has divine role (public view)
function hasDivineRole(bytes32 role) public view returns (bool) {
return hasRole(role, msg.sender);
}
// mints soul power as the house of thoth so wills (public thoth)
function mint(address _to, uint _amount) public obey(thoth) {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// destroys `amount` tokens from the caller (public)
function burn(uint amount) public {
_burn(_msgSender(), amount);
_moveDelegates(_delegates[_msgSender()], address(0), amount);
}
// destroys `amount` tokens from the `account` (public)
function burnFrom(address account, uint amount) public {
uint currentAllowance = allowance(account, _msgSender());
require(currentAllowance >= amount, 'burn amount exceeds allowance');
_approve(account, _msgSender(), currentAllowance - amount);
_burn(account, amount);
_moveDelegates(_delegates[account], address(0), amount);
}
// returns the address delegated by a given delegator (external view)
function delegates(address delegator) external view returns (address) {
return _delegates[delegator];
}
// delegates to the `delegatee` (external)
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
// delegates votes from signatory to `delegatee` (external)
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
) external {
bytes32 domainSeparator = keccak256(
abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this))
);
bytes32 structHash = keccak256(
abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)
);
bytes32 digest = keccak256(
abi.encodePacked('\x19\x01', domainSeparator, structHash)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), 'delegateBySig: invalid signature');
require(nonce == nonces[signatory]++, 'delegateBySig: invalid nonce');
require(block.timestamp <= expiry, 'delegateBySig: signature expired');
return _delegate(signatory, delegatee);
}
// returns current votes balance for `account` (external view)
function getCurrentVotes(address account) external view returns (uint) {
uint nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
// returns an account's prior vote count as of a given timestamp (external view)
function getPriorVotes(address account, uint blockTimestamp) external view returns (uint) {
require(blockTimestamp < block.timestamp, 'getPriorVotes: not yet determined');
uint nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) { return 0; }
// checks most recent balance
if (checkpoints[account][nCheckpoints - 1].fromTime <= blockTimestamp) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// checks implicit zero balance
if (checkpoints[account][0].fromTime > blockTimestamp) {
return 0;
}
uint lower = 0;
uint upper = nCheckpoints - 1;
while (upper > lower) {
uint center = upper - (upper - lower) / 2; // avoids overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromTime == blockTimestamp) {
return cp.votes;
} else if (cp.fromTime < blockTimestamp) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function safe256(uint n, string memory errorMessage) internal pure returns (uint) {
require(n < type(uint).max, errorMessage);
return uint(n);
}
function getChainId() internal view returns (uint) {
uint chainId;
assembly { chainId := chainid() }
return chainId;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = _delegates[delegator];
uint delegatorBalance = balanceOf(delegator); // balance of underlying SOUL (not scaled)
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decreases old representative
uint srcRepNum = numCheckpoints[srcRep];
uint srcRepOld = srcRepNum > 0
? checkpoints[srcRep][srcRepNum - 1].votes
: 0;
uint srcRepNew = srcRepOld - amount;
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increases new representative
uint dstRepNum = numCheckpoints[dstRep];
uint dstRepOld = dstRepNum > 0
? checkpoints[dstRep][dstRepNum - 1].votes
: 0;
uint dstRepNew = dstRepOld + amount;
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint nCheckpoints,
uint oldVotes,
uint newVotes
) internal {
uint blockTimestamp = safe256(block.timestamp, 'block timestamp exceeds 256 bits');
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromTime == blockTimestamp) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockTimestamp, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
}
// File: contracts/libraries/Operable.sol
pragma solidity ^0.8.0;
// --------------------------------------------------------------------------------------
// Allows multiple contracts to act as `owner`, from `Ownable.sol`, with `onlyOperator`.
// --------------------------------------------------------------------------------------
abstract contract Operable is Context, Ownable {
address[] public operators;
mapping(address => bool) public operator;
event OperatorUpdated(address indexed operator, bool indexed access);
constructor () {
address msgSender = _msgSender();
operator[msgSender] = true;
operators.push(msgSender);
emit OperatorUpdated(msgSender, true);
}
/**
* @dev Throws if called by any account other than the operator.
*/
modifier onlyOperator() {
address msgSender = _msgSender();
require(operator[msgSender], "Operator: caller is not an operator");
_;
}
/**
* @dev Leaves the contract without operator. It will not be possible to call
* `onlyOperator` functions anymore. Can only be called by an operator.
*/
function removeOperator(address removingOperator) public virtual onlyOperator {
require(operator[removingOperator], 'Operable: address is not an operator');
operator[removingOperator] = false;
for (uint8 i; i < operators.length; i++) {
if (operators[i] == removingOperator) {
operators[i] = operators[i+1];
operators.pop();
emit OperatorUpdated(removingOperator, false);
return;
}
}
}
/**
* @dev Adds address as operator of the contract.
* Can only be called by an operator.
*/
function addOperator(address newOperator) public virtual onlyOperator {
require(newOperator != address(0), "Operable: new operator is the zero address");
require(!operator[newOperator], 'Operable: address is already an operator');
operator[newOperator] = true;
operators.push(newOperator);
emit OperatorUpdated(newOperator, true);
}
}
// File: contracts/SeanceCircle.sol
pragma solidity ^0.8.0;
// SeanceCircle with Governance.
contract SeanceCircle is ERC20('SeanceCircle', 'SEANCE'), Ownable, Operable {
SoulPower public soul;
bool isInitialized;
function mint(address _to, uint256 _amount) public onlyOperator {
require(isInitialized, 'the circle has not yet begun');
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
function burn(address _from ,uint256 _amount) public onlyOperator {
_burn(_from, _amount);
_moveDelegates(_delegates[_from], address(0), _amount);
}
function initialize(SoulPower _soul) external onlyOwner {
require(!isInitialized, 'the circle has already begun');
soul = _soul;
isInitialized = true;
}
// safe soul transfer function, just in case if rounding error causes pool to not have enough SOUL.
function safeSoulTransfer(address _to, uint256 _amount) public onlyOperator {
uint256 soulBal = soul.balanceOf(address(this));
if (_amount > soulBal) {
soul.transfer(_to, soulBal);
} else {
soul.transfer(_to, _amount);
}
}
// record of each accounts delegate
mapping (address => address) internal _delegates;
// checkpoint for marking number of votes from a given block timestamp
struct Checkpoint {
uint256 fromTime;
uint256 votes;
}
// record of votes checkpoints for each account, by index
mapping (address => mapping (uint256 => Checkpoint)) public checkpoints;
// number of checkpoints for each account
mapping (address => uint256) public numCheckpoints;
// EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
// EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
// record of states for signing / validating signatures
mapping (address => uint) public nonces;
// emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
// emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
// returns the address delegated by a given delegator (external view)
function delegates(address delegator) external view returns (address) { return _delegates[delegator]; }
// delegates to the `delegatee` (external)
function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); }
// delegates votes from signatory to `delegatee` (external)
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "SOUL::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "SOUL::delegateBySig: invalid nonce");
require(block.timestamp <= expiry, "SOUL::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
// returns current votes balance for `account` (external view)
function getCurrentVotes(address account) external view returns (uint) {
uint nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
// returns an account's prior vote count as of a given timestamp (external view)
function getPriorVotes(address account, uint blockTimestamp) external view returns (uint256) {
require(blockTimestamp < block.timestamp, "SOUL::getPriorVotes: not yet determined");
uint256 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// checks most recent balance
if (checkpoints[account][nCheckpoints - 1].fromTime <= blockTimestamp) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// checks implicit zero balance
if (checkpoints[account][0].fromTime > blockTimestamp) {
return 0;
}
uint256 lower = 0;
uint256 upper = nCheckpoints - 1;
while (upper > lower) {
uint256 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromTime == blockTimestamp) {
return cp.votes;
} else if (cp.fromTime < blockTimestamp) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying SOUL (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint256 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld - amount;
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint256 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld + amount;
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint256 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint256 blockTimestamp = safe256(block.timestamp, "SOUL::_writeCheckpoint: block timestamp exceeds 256 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromTime == blockTimestamp) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockTimestamp, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe256(uint n, string memory errorMessage) internal pure returns (uint256) {
require(n < type(uint256).max, errorMessage);
return uint256(n);
}
function getChainId() internal view returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
function newSoul(SoulPower _soul) external onlyOperator {
require(soul != _soul, 'must be a new address');
soul = _soul;
}
}
// File: contracts/interfaces/IMigrator.sol
pragma solidity ^0.8.0;
interface IMigrator {
// Perform LP token migration from legacy.
// Take the current LP token address and return the new LP token address.
// Migrator should have full access to the caller's LP token.
// Return the new LP token address.
function migrate(IERC20 token) external returns (IERC20);
}
// File: contracts/SoulSummoner.sol
pragma solidity ^0.8.0;
// the summoner of souls | ownership transferred to a governance smart contract
// upon sufficient distribution + the community's desire to self-govern.
contract SoulSummoner is AccessControl, Ownable, Pausable, ReentrancyGuard {
// user info
struct Users {
uint amount; // total tokens user has provided.
uint rewardDebt; // reward debt (see below).
uint rewardDebtAtTime; // the last time user stake.
uint lastWithdrawTime; // the last time a user withdrew at.
uint firstDepositTime; // the last time a user deposited at.
uint timeDelta; // time passed since withdrawals.
uint lastDepositTime; // most recent deposit time.
// pending reward = (user.amount * pool.accSoulPerShare) - user.rewardDebt
// the following occurs when a user +/- tokens to a pool:
// 1. pool: `accSoulPerShare` and `lastRewardTime` update.
// 2. user: receives pending reward.
// 3. user: `amount` updates(+/-).
// 4. user: `rewardDebt` updates (+/-).
}
// pool info
struct Pools {
IERC20 lpToken; // lp token ierc20 contract.
uint allocPoint; // allocation points assigned to this pool | SOULs to distribute per second.
uint lastRewardTime; // most recent UNIX timestamp during which SOULs distribution occurred in the pool.
uint accSoulPerShare; // accumulated SOULs per share, times 1e12.
}
// soul power: our native utility token
address private soulAddress;
SoulPower public soul;
// seance circle: our governance token
address private seanceAddress;
SeanceCircle public seance;
address public team; // receives 1/8 soul supply
address public dao; // recieves 1/8 soul supply
// migrator contract | has lotsa power
IMigrator public migrator;
// blockchain variables accounting for share of overall emissions
uint public totalWeight;
uint public weight;
// soul x day x this.chain
uint public dailySoul; // = weight * 250K * 1e18;
// soul x second x this.chain
uint public soulPerSecond; // = dailySoul / 86400;
// bonus muliplier for early soul summoners
uint public bonusMultiplier = 1;
// timestamp when soul rewards began (initialized)
uint public startTime;
// ttl allocation points | must be the sum of all allocation points
uint public totalAllocPoint;
// summoner initialized state.
bool public isInitialized;
// decay rate on withdrawal fee of 1%.
uint public immutable dailyDecay = enWei(1);
// start rate for the withdrawal fee.
uint public startRate;
Pools[] public poolInfo; // pool info
mapping (uint => mapping (address => Users)) public userInfo; // staker data
// divinated roles
bytes32 public isis; // soul summoning goddess of magic
bytes32 public maat; // goddess of cosmic order
event RoleDivinated(bytes32 role, bytes32 supreme);
// restricted to the council of the role passed as an object to obey (role)
modifier obey(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
// prevents: early reward distribution
modifier isSummoned {
require(isInitialized, 'rewards have not yet begun');
_;
}
event Deposit(address indexed user, uint indexed pid, uint amount);
event Withdraw(address indexed user, uint indexed pid, uint amount, uint timeStamp);
event Initialized(address team, address dao, address soul, address seance, uint totalAllocPoint, uint weight);
event PoolAdded(uint pid, uint allocPoint, IERC20 lpToken, uint totalAllocPoint);
event PoolSet(uint pid, uint allocPoint);
event WeightUpdated(uint weight, uint totalWeight);
event RewardsUpdated(uint dailySoul, uint soulPerSecond);
event StartRateUpdated(uint startRate);
event AccountsUpdated(address dao, address team);
event TokensUpdated(address soul, address seance);
event DepositRevised(uint _pid, address _user, uint _time);
// validates: pool exists
modifier validatePoolByPid(uint pid) {
require(pid < poolInfo.length, 'pool does not exist');
_;
}
// channels the power of the isis and ma'at to the deployer (deployer)
constructor() {
team = msg.sender; // 0x81Dd37687c74Df8F957a370A9A4435D873F5e5A9;
dao = msg.sender; // 0x1C63C726926197BD3CB75d86bCFB1DaeBcD87250;
isis = keccak256("isis"); // goddess of magic who creates pools
maat = keccak256("maat"); // goddess of cosmic order who allocates emissions
_divinationCeremony(DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_ROLE, team);
_divinationCeremony(isis, isis, team); // isis role created -- owner divined admin
_divinationCeremony(maat, isis, dao); // maat role created -- isis divined admin
}
function _divinationCeremony(bytes32 _role, bytes32 _adminRole, address _account)
internal returns (bool) {
_setupRole(_role, _account);
_setRoleAdmin(_role, _adminRole);
return true;
}
// validate: pool uniqueness to eliminate duplication risk (internal view)
function checkPoolDuplicate(IERC20 _token) internal view {
uint length = poolInfo.length;
for (uint pid = 0; pid < length; ++pid) {
require(poolInfo[pid].lpToken != _token, 'duplicated pool');
}
}
// activates rewards (owner)
function initialize(
address _soulAddress,
address _seanceAddress,
uint _totalWeight,
uint _weight,
uint _stakingAlloc ,
uint _startRate
) external obey(isis) {
require(!isInitialized, 'already initialized');
soulAddress = _soulAddress;
seanceAddress = _seanceAddress;
startTime = block.timestamp;
totalWeight = _totalWeight + _weight;
weight = _weight;
startRate = enWei(_startRate);
uint allocPoint = _stakingAlloc;
soul = SoulPower(soulAddress);
seance = SeanceCircle(seanceAddress);
// updates dailySoul and soulPerSecond
updateRewards(weight, totalWeight);
// staking pool
poolInfo.push(Pools({
lpToken: soul,
allocPoint: allocPoint,
lastRewardTime: startTime,
accSoulPerShare: 0
}));
isInitialized = true; // triggers initialize state
totalAllocPoint += allocPoint; // kickstarts total allocation
emit Initialized(team, dao, soulAddress, seanceAddress, totalAllocPoint, weight);
}
// update: multiplier (maat)
function updateMultiplier(uint _bonusMultiplier) external obey(maat) {
bonusMultiplier = _bonusMultiplier;
}
// update: rewards (internal)
function updateRewards(uint _weight, uint _totalWeight) internal {
uint share = enWei(_weight) / _totalWeight; // share of ttl emissions for chain (chain % ttl emissions)
dailySoul = share * (250_000); // dailySoul (for this.chain) = share (%) x 250K (soul emissions constant)
soulPerSecond = dailySoul / 1 days; // updates: daily rewards expressed in seconds (1 days = 86,400 secs)
emit RewardsUpdated(dailySoul, soulPerSecond);
}
// update: startRate (maat)
function updateStartRate(uint _startRate) public obey(maat) {
require(startRate != enWei(_startRate));
startRate = enWei(_startRate);
emit StartRateUpdated(startRate);
}
// returns: amount of pools
function poolLength() external view returns (uint) {
return poolInfo.length;
}
// add: new pool (isis)
function addPool(uint _allocPoint, IERC20 _lpToken, bool _withUpdate)
public isSummoned obey(isis) { // isis: the soul summoning goddess whose power transcends them all
checkPoolDuplicate(_lpToken);
_addPool(_allocPoint, _lpToken, _withUpdate);
}
// add: new pool (internal)
function _addPool(uint _allocPoint, IERC20 _lpToken, bool _withUpdate) internal {
if (_withUpdate) { massUpdatePools(); }
totalAllocPoint += _allocPoint;
poolInfo.push(
Pools({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardTime: block.timestamp > startTime ? block.timestamp : startTime,
accSoulPerShare: 0
}));
updateStakingPool();
uint pid = poolInfo.length;
emit PoolAdded(pid, _allocPoint, _lpToken, totalAllocPoint);
}
// set: allocation points (maat)
function set(uint pid, uint allocPoint, bool withUpdate)
external isSummoned validatePoolByPid(pid) obey(maat) {
if (withUpdate) { massUpdatePools(); } // updates all pools
uint prevAllocPoint = poolInfo[pid].allocPoint;
poolInfo[pid].allocPoint = allocPoint;
if (prevAllocPoint != allocPoint) {
totalAllocPoint = totalAllocPoint - prevAllocPoint + allocPoint;
updateStakingPool(); // updates only selected pool
}
emit PoolSet(pid, allocPoint);
}
// update: weight (maat)
function updateWeights(uint _weight, uint _totalWeight) external obey(maat) {
require(weight != _weight || totalWeight != _totalWeight, 'must be at least one new value');
require(_totalWeight >= _weight, 'weight cannot exceed totalWeight');
weight = _weight;
totalWeight = _totalWeight;
updateRewards(weight, totalWeight);
emit WeightUpdated(weight, totalWeight);
}
// update: staking pool (internal)
function updateStakingPool() internal {
uint length = poolInfo.length;
uint points;
for (uint pid = 1; pid < length; ++pid) {
points = points + poolInfo[pid].allocPoint;
}
if (points != 0) {
points = points / 3;
totalAllocPoint = totalAllocPoint - poolInfo[0].allocPoint + points;
poolInfo[0].allocPoint = points;
}
}
// set: migrator contract (owner)
function setMigrator(IMigrator _migrator) external isSummoned obey(isis) {
migrator = _migrator;
}
// view: user delta
function userDelta(uint256 _pid, address _user) public view returns (uint256 delta) {
Users memory user = userInfo[_pid][_user];
return user.lastWithdrawTime > 0
? block.timestamp - user.lastWithdrawTime
: block.timestamp - user.firstDepositTime;
}
// migrate: lp tokens to another contract (migrator)
function migrate(uint pid) external isSummoned validatePoolByPid(pid) {
require(address(migrator) != address(0), 'no migrator set');
Pools storage pool = poolInfo[pid];
IERC20 lpToken = pool.lpToken;
uint bal = lpToken.balanceOf(address(this));
lpToken.approve(address(migrator), bal);
IERC20 _lpToken = migrator.migrate(lpToken);
require(bal == _lpToken.balanceOf(address(this)), "migrate: insufficient balance");
pool.lpToken = _lpToken;
}
// view: bonus multiplier (public)
function getMultiplier(uint from, uint to) public view returns (uint) {
return (to - from) * bonusMultiplier; // todo: minus parens
}
// returns: decay rate for a pid
function getFeeRate(uint pid, uint timeDelta) public view returns (uint feeRate) {
uint daysPassed = timeDelta < 1 days ? 0 : timeDelta / 1 days;
uint rateDecayed = enWei(daysPassed);
uint _rate = rateDecayed >= startRate ? 0 : startRate - rateDecayed;
// returns 0 for SAS
return pid == 0 ? 0 : _rate;
}
// returns: feeAmount and with withdrawableAmount for a given pid and amount
function getWithdrawable(uint pid, uint timeDelta, uint amount) public view returns (uint _feeAmount, uint _withdrawable) {
uint feeRate = fromWei(getFeeRate(pid, timeDelta));
uint feeAmount = (amount * feeRate) / 100;
uint withdrawable = amount - feeAmount;
return (feeAmount, withdrawable);
}
// view: pending soul rewards (external)
function pendingSoul(uint pid, address _user) external view returns (uint pendingAmount) {
Pools storage pool = poolInfo[pid];
Users storage user = userInfo[pid][_user];
uint accSoulPerShare = pool.accSoulPerShare;
uint lpSupply = pool.lpToken.balanceOf(address(this));
if (block.timestamp > pool.lastRewardTime && lpSupply != 0) {
uint multiplier = getMultiplier(pool.lastRewardTime, block.timestamp);
uint soulReward = multiplier * soulPerSecond * pool.allocPoint / totalAllocPoint;
accSoulPerShare = accSoulPerShare + soulReward * 1e12 / lpSupply;
}
return user.amount * accSoulPerShare / 1e12 - user.rewardDebt;
}
// update: rewards for all pools (public)
function massUpdatePools() public {
uint length = poolInfo.length;
for (uint pid = 0; pid < length; ++pid) { updatePool(pid); }
}
// update: rewards for a given pool id (public)
function updatePool(uint pid) public validatePoolByPid(pid) {
Pools storage pool = poolInfo[pid];
if (block.timestamp <= pool.lastRewardTime) { return; }
uint lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) { pool.lastRewardTime = block.timestamp; return; } // first staker in pool
uint multiplier = getMultiplier(pool.lastRewardTime, block.timestamp);
uint soulReward = multiplier * soulPerSecond * pool.allocPoint / totalAllocPoint;
uint divi = soulReward * 1e12 / 8e12; // 12.5% rewards
uint divis = divi * 2; // total divis
uint shares = soulReward - divis; // net shares
soul.mint(team, divi);
soul.mint(dao, divi);
soul.mint(address(seance), shares);
pool.accSoulPerShare = pool.accSoulPerShare + (soulReward * 1e12 / lpSupply);
pool.lastRewardTime = block.timestamp;
}
// deposit: lp tokens (lp owner)
function deposit(uint pid, uint amount) external nonReentrant validatePoolByPid(pid) whenNotPaused {
require (pid != 0, 'deposit SOUL by staking');
Pools storage pool = poolInfo[pid];
Users storage user = userInfo[pid][msg.sender];
updatePool(pid);
if (user.amount > 0) { // already deposited assets
uint pending = (user.amount * pool.accSoulPerShare) / 1e12 - user.rewardDebt;
if(pending > 0) { // sends pending rewards, if applicable
safeSoulTransfer(msg.sender, pending);
}
}
if (amount > 0) { // if adding more
pool.lpToken.transferFrom(address(msg.sender), address(this), amount);
user.amount += amount;
}
user.rewardDebt = user.amount * pool.accSoulPerShare / 1e12;
// marks timestamp for first deposit
user.firstDepositTime =
user.firstDepositTime > 0
? user.firstDepositTime
: block.timestamp;
emit Deposit(msg.sender, pid, amount);
}
// withdraw: lp tokens (external farmers)
function withdraw(uint pid, uint amount) external nonReentrant validatePoolByPid(pid) {
require (pid != 0, 'withdraw SOUL by unstaking');
Pools storage pool = poolInfo[pid];
Users storage user = userInfo[pid][msg.sender];
require(user.amount >= amount, 'withdraw not good');
updatePool(pid);
uint pending = user.amount * pool.accSoulPerShare / 1e12 - user.rewardDebt;
if(pending > 0) { safeSoulTransfer(msg.sender, pending); }
if(amount > 0) {
if(user.lastDepositTime > 0){
user.timeDelta = block.timestamp - user.lastDepositTime; }
else { user.timeDelta = block.timestamp - user.firstDepositTime; }
user.amount = user.amount - amount;
}
uint timeDelta = userInfo[pid][msg.sender].timeDelta;
(, uint withdrawable) = getWithdrawable(pid, timeDelta, amount); // removes feeAmount from amount
uint feeAmount = amount - withdrawable;
pool.lpToken.transfer(address(dao), feeAmount);
pool.lpToken.transfer(address(msg.sender), withdrawable);
user.rewardDebt = user.amount * pool.accSoulPerShare / 1e12;
user.lastWithdrawTime = block.timestamp;
emit Withdraw(msg.sender, pid, amount, block.timestamp);
}
// stake: soul into summoner (external)
function enterStaking(uint amount) external nonReentrant whenNotPaused {
Pools storage pool = poolInfo[0];
Users storage user = userInfo[0][msg.sender];
updatePool(0);
if (user.amount > 0) {
uint pending = user.amount * pool.accSoulPerShare / 1e12 - user.rewardDebt;
if(pending > 0) {
safeSoulTransfer(msg.sender, pending);
}
}
if(amount > 0) {
pool.lpToken.transferFrom(address(msg.sender), address(this), amount);
user.amount = user.amount + amount;
}
// marks timestamp for first deposit
user.firstDepositTime =
user.firstDepositTime > 0
? user.firstDepositTime
: block.timestamp;
user.rewardDebt = user.amount * pool.accSoulPerShare / 1e12;
seance.mint(msg.sender, amount);
emit Deposit(msg.sender, 0, amount);
}
// unstake: your soul (external staker)
function leaveStaking(uint amount) external nonReentrant {
Pools storage pool = poolInfo[0];
Users storage user = userInfo[0][msg.sender];
require(user.amount >= amount, "withdraw: not good");
updatePool(0);
uint pending = user.amount * pool.accSoulPerShare / 1e12 - user.rewardDebt;
if(pending > 0) {
safeSoulTransfer(msg.sender, pending);
}
if(amount > 0) {
user.amount = user.amount - amount;
pool.lpToken.transfer(address(msg.sender), amount);
}
user.rewardDebt = user.amount * pool.accSoulPerShare / 1e12;
user.lastWithdrawTime = block.timestamp;
seance.burn(msg.sender, amount);
emit Withdraw(msg.sender, 0, amount, block.timestamp);
}
// transfer: seance (internal)
function safeSoulTransfer(address account, uint amount) internal {
seance.safeSoulTransfer(account, amount);
}
// update accounts: dao and team addresses (owner)
function updateAccounts(address _dao, address _team) external obey(isis) {
require(dao != _dao || team != _team, 'must be a new account');
dao = _dao;
team = _team;
emit AccountsUpdated(dao, team);
}
// update tokens: soul and seance addresses (owner)
function updateTokens(address _soul, address _seance) external obey(isis) {
require(soul != IERC20(_soul) || seance != IERC20(_seance), 'must be a new token address');
soul = SoulPower(_soul);
seance = SeanceCircle(_seance);
emit TokensUpdated(_soul, _seance);
}
// manual override to reassign the first deposit time for a given (pid, account)
function reviseDeposit(uint _pid, address _user, uint256 _time) public obey(maat) {
Users storage user = userInfo[_pid][_user];
user.firstDepositTime = _time;
emit DepositRevised(_pid, _user, _time);
}
// helper functions to convert to wei and 1/100th
function enWei(uint amount) public pure returns (uint) { return amount * 1e18; }
function fromWei(uint amount) public pure returns (uint) { return amount / 1e18; }
}
| Destroys `amount` tokens from `account`, reducing the total supply. Emits a {Transfer} event with `to` set to the zero address. Requirements: - `account` cannot be the zero address. - `account` must have at least `amount` tokens./ | function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
| 13,076,078 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
abstract contract JungleStorage {
uint256 public startingIndexBlock;
uint256 public tokenPrice = 0.0000094 ether;
uint256 public accumulationRate = 1.36986 ether;
uint256 public startingIndex;
uint256 public emissionEnd = 86400 * 365 ;
uint256 public tokensForPublic = 5000000 ether;
uint256 public tokensForPublicAccrued=5000000 ether;
uint256 public tokensForTeams = 500000 ether;
uint256 public tokensForTeamsAfter365 =500000 ether;
uint256 public SECONDS_IN_A_DAY = 86400;
uint256 internal _totalSupply;
string internal _name;
string internal _symbol;
address public cardAddress;
uint8 internal _decimals;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) internal _allowances;
mapping (uint256 => uint256) public _lastClaim;
mapping (uint256 => uint256) public emissionStart;
}
contract JungleToken is IERC20,Ownable,JungleStorage {
using SafeMath for uint256;
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwnerModifier() {
address owner=owner();
require(tx.origin == owner, "JungleToken : caller is not the owner");
_;
}
event claimedAmount(uint256 claimedAmount);
/**
* @dev Permissioning not added because it is only callable once.
*/
function setNftCardAddress(address _cardAddress) onlyOwnerModifier public {
cardAddress = _cardAddress;
}
/**
* @dev When accumulated JungleTokens have last been claimed for a NFT index
*/
function lastClaim(uint256 tokenIndex) public view returns (uint256) {
require(IERC721Enumerable(cardAddress).ownerOf(tokenIndex) != address(0), "Owner cannot be 0 address");
require(tokenIndex < IERC721Enumerable(cardAddress).totalSupply(), "NFT at index has not been minted yet");
uint256 lastClaimed = uint256(_lastClaim[tokenIndex]) != 0 ? uint256(_lastClaim[tokenIndex]) : emissionStart[tokenIndex];
return lastClaimed;
}
/**
* @dev Claim mints accumulated JungleTokens and supports multiple token indices at once.
*/
function claim(uint256[] memory tokenIndices) public onlyOwnerModifier returns (uint256) {
uint256 totalClaimQty = 0;
for (uint i = 0; i < tokenIndices.length; i++) {
// Sanity check for non-minted index
require(tokenIndices[i] < IERC721Enumerable(cardAddress).totalSupply(), "NFT at index has not been minted yet");
// Duplicate token index check
for (uint j = i + 1; j < tokenIndices.length; j++) {
require(tokenIndices[i] != tokenIndices[j], "Duplicate token index");
}
uint tokenIndex = tokenIndices[i];
require(IERC721Enumerable(cardAddress).ownerOf(tokenIndex) != address(0), "Owner cannot be 0 address");
uint256 lastClaimed = lastClaim(tokenIndex);
require((block.timestamp -(emissionStart[tokenIndex]))>=SECONDS_IN_A_DAY,"Apply after one day to get accumulation amount for this/some token(s)!");
require(IERC721Enumerable(cardAddress).ownerOf(tokenIndex) == tx.origin, "Sender is not the owner");
uint256 accumulationPeriod = block.timestamp < emissionStart[tokenIndex].add(emissionEnd) ? block.timestamp : emissionStart[tokenIndex].add(emissionEnd); // Getting the min value of both
uint256 totalAccumulated = accumulationPeriod.sub(lastClaimed).mul(accumulationRate).div(SECONDS_IN_A_DAY);
emit claimedAmount(totalAccumulated);
if (totalAccumulated != 0) {
totalClaimQty = totalClaimQty.add(totalAccumulated);
_lastClaim[tokenIndex] = block.timestamp;
}
}
require(totalClaimQty != 0, "No accumulated Jungle tokens");
mintAccumulationAmt(tx.origin, totalClaimQty);
return totalClaimQty;
}
/*
*Mints accumulation amount when user calls claim(). to "to" address
*/
function mintAccumulationAmt(address to,uint256 totalClaimQty) private{
_mint(to, totalClaimQty);
tokensForPublicAccrued-=totalClaimQty;
}
/*
*Mints 500 tokens when user when user calls montNft for buying, Reduces supply by minted amount.
*/
function mintForPublic(address to,uint256 amount, uint256 mintIndex) external returns(bool){
require(msg.sender==cardAddress,"You are not authorized to call this function!");
_mint(to,amount);
emissionStart[mintIndex] = block.timestamp;
tokensForPublic-=amount;
return true;
}
/**
* @dev withdrawTokenForTeam sends 500000 token for team to owner address.
*/
function withdrawTokenForTeam() external onlyOwnerModifier{
require(tokensForTeams!=0,"token for teams already claimed!");
_mint(owner(),tokensForTeams);
tokensForTeams=0;
}
/**
* @dev withdrawTokenForTeamAfterYear sends 500000 jungle tokens to owner address after a year.
*/
function withdrawTokenForTeamAfterYear() external onlyOwnerModifier{
require(block.timestamp>=emissionEnd,"You can't claim tokens before 1 year completes!");
require(tokensForTeamsAfter365!=0,"token for teams already claimed!");
_mint(owner(),tokensForTeamsAfter365);
tokensForTeamsAfter365=0;
}
/*
*@dev Method for changing price of JungleToken, only callable by owner.
*/
function changePrice(uint256 newPrice) external onlyOwnerModifier {
require(newPrice> 0,"Price should be greater than zero!");
tokenPrice=newPrice;
}
/**
* @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);
// Approval check is skipped if the caller of transferFrom is the NftCard contract. For better UX.
if (msg.sender != cardAddress) {
_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 Burns a quantity of tokens held by the caller.
*
* Emits an {Transfer} event to 0 address
*
*/
function burn(address recipient,uint256 burnQuantity) public virtual returns (bool) {
require(msg.sender==cardAddress,"You are not authorized to call this function!");
_burn(recipient, burnQuantity);
return true;
}
/** @dev Creates `mintQuantity` tokens and assigns them to `recipient`, increasing
* the total supply.
* Emits an {Transfer} event to 0 address
*/
function mint(address recipient,uint256 mintQuantity) public virtual returns (bool) {
require(msg.sender==cardAddress,"You are not authorized to call this function!");
_mint(recipient, mintQuantity);
return true;
}
// ++
/** @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 { }
}
| 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`./ Approval check is skipped if the caller of transferFrom is the NftCard contract. For better UX. | function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
if (msg.sender != cardAddress) {
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
}
return true;
}
| 952,156 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../interfaces/IUniswapV2Pair.sol";
import "../../libraries/UniswapV2Library.sol";
import "../../BaseAdapter.sol";
import "./IMasterChef.sol";
interface ISushiBar is IERC20 {
function enter(uint256 amount) external;
}
contract SushiAdapter is BaseAdapter {
using SafeMath for uint256;
IMasterChef constant SUSHI_MASTER_CHEF = IMasterChef(0xc2EdaD668740f1aA35E4D8f227fB8E17dcA888Cd);
address immutable MASTER_VAMPIRE;
address constant DEV_FUND = 0xa896e4bd97a733F049b23d2AcEB091BcE01f298d;
IERC20 constant SUSHI = IERC20(0x6B3595068778DD592e39A122f4f5a5cF09C90fE2);
ISushiBar constant SUSHI_BAR = ISushiBar(0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272);
IUniswapV2Pair constant SUSHI_WETH_PAIR = IUniswapV2Pair(0x795065dCc9f64b5614C407a6EFDC400DA6221FB0);
uint256 constant BLOCKS_PER_YEAR = 2336000;
uint256 constant DEV_SHARE = 20; // 2%
// token 0 - SUSHI
// token 1 - WETH
constructor(address _weth, address _factory, address _masterVampire)
BaseAdapter(_weth, _factory)
{
MASTER_VAMPIRE = _masterVampire;
}
// Victim info
function rewardToken(uint256) public pure override returns (IERC20) {
return SUSHI;
}
function poolCount() external view override returns (uint256) {
return SUSHI_MASTER_CHEF.poolLength();
}
function sellableRewardAmount(uint256) external pure override returns (uint256) {
return uint256(-1);
}
// Victim actions, requires impersonation via delegatecall
function sellRewardForWeth(address, uint256, uint256 rewardAmount, address to) external override returns(uint256) {
uint256 devAmt = rewardAmount.mul(DEV_SHARE).div(1000);
SUSHI.approve(address(SUSHI_BAR), devAmt);
SUSHI_BAR.enter(devAmt);
SUSHI_BAR.transfer(DEV_FUND, SUSHI_BAR.balanceOf(address(this)));
rewardAmount = rewardAmount.sub(devAmt);
SUSHI.transfer(address(SUSHI_WETH_PAIR), rewardAmount);
(uint sushiReserve, uint wethReserve,) = SUSHI_WETH_PAIR.getReserves();
uint amountOutput = UniswapV2Library.getAmountOut(rewardAmount, sushiReserve, wethReserve);
SUSHI_WETH_PAIR.swap(uint(0), amountOutput, to, new bytes(0));
return amountOutput;
}
// Pool info
function lockableToken(uint256 victimPID) external view override returns (IERC20) {
(IERC20 lpToken,,,) = SUSHI_MASTER_CHEF.poolInfo(victimPID);
return lpToken;
}
function lockedAmount(address user, uint256 victimPID) external view override returns (uint256) {
(uint256 amount,) = SUSHI_MASTER_CHEF.userInfo(victimPID, user);
return amount;
}
function pendingReward(address, uint256, uint256 victimPID) external view override returns (uint256) {
return SUSHI_MASTER_CHEF.pendingSushi(victimPID, MASTER_VAMPIRE);
}
// Pool actions, requires impersonation via delegatecall
function deposit(address _adapter, uint256 victimPID, uint256 amount) external override returns (uint256) {
IVampireAdapter adapter = IVampireAdapter(_adapter);
adapter.lockableToken(victimPID).approve(address(SUSHI_MASTER_CHEF), uint256(-1));
SUSHI_MASTER_CHEF.deposit(victimPID, amount);
return 0;
}
function withdraw(address, uint256 victimPID, uint256 amount) external override returns (uint256) {
SUSHI_MASTER_CHEF.withdraw(victimPID, amount);
return 0;
}
function claimReward(address, uint256, uint256 victimPID) external override {
SUSHI_MASTER_CHEF.deposit(victimPID, 0);
}
function emergencyWithdraw(address, uint256 victimPID) external override {
SUSHI_MASTER_CHEF.emergencyWithdraw(victimPID);
}
// Service methods
function poolAddress(uint256) external pure override returns (address) {
return address(SUSHI_MASTER_CHEF);
}
function rewardToWethPool() external pure override returns (address) {
return address(SUSHI_WETH_PAIR);
}
function lockedValue(address user, uint256 victimPID) external override view returns (uint256) {
SushiAdapter adapter = SushiAdapter(this);
return adapter.lpTokenValue(adapter.lockedAmount(user, victimPID),IUniswapV2Pair(address(adapter.lockableToken(victimPID))));
}
function totalLockedValue(uint256 victimPID) external override view returns (uint256) {
SushiAdapter adapter = SushiAdapter(this);
IUniswapV2Pair lockedToken = IUniswapV2Pair(address(adapter.lockableToken(victimPID)));
return adapter.lpTokenValue(lockedToken.balanceOf(adapter.poolAddress(victimPID)), lockedToken);
}
function normalizedAPY(uint256 victimPID) external override view returns (uint256) {
SushiAdapter adapter = SushiAdapter(this);
(,uint256 allocationPoints,,) = SUSHI_MASTER_CHEF.poolInfo(victimPID);
uint256 sushiPerBlock = SUSHI_MASTER_CHEF.sushiPerBlock();
uint256 totalAllocPoint = SUSHI_MASTER_CHEF.totalAllocPoint();
uint256 multiplier = SUSHI_MASTER_CHEF.getMultiplier(block.number - 1, block.number);
uint256 rewardPerBlock = multiplier.mul(sushiPerBlock).mul(allocationPoints).div(totalAllocPoint);
(uint256 sushiReserve, uint256 wethReserve,) = SUSHI_WETH_PAIR.getReserves();
uint256 valuePerYear = rewardPerBlock.mul(wethReserve).mul(BLOCKS_PER_YEAR).div(sushiReserve);
return valuePerYear.mul(1 ether).div(adapter.totalLockedValue(victimPID));
}
}
// 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;
/**
* @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.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "../interfaces/IUniswapV2Pair.sol";
import "./SafeMath.sol";
library UniswapV2Library {
using SafeMathUniswap 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, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: 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'e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303' // 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);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(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, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: 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, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
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, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
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, 'UniswapV2Library: 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, 'UniswapV2Library: 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);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./interfaces/IUniswapV2Factory.sol";
import "./libraries/UniswapV2Library.sol";
import "./IVampireAdapter.sol";
abstract contract BaseAdapter is IVampireAdapter {
using SafeMath for uint256;
IERC20 immutable weth;
IUniswapV2Factory immutable factory;
constructor(address _weth, address _factory) {
weth = IERC20(_weth);
factory = IUniswapV2Factory(_factory);
}
/**
* @notice Calculates the WETH value of an LP token
*/
function lpTokenValue(uint256 amount, IUniswapV2Pair lpToken) public virtual override view returns(uint256) {
(uint256 token0Reserve, uint256 token1Reserve,) = lpToken.getReserves();
address token0 = lpToken.token0();
address token1 = lpToken.token1();
if (token0 == address(weth)) {
return amount.mul(token0Reserve).mul(2).div(lpToken.totalSupply());
}
if (token1 == address(weth)) {
return amount.mul(token1Reserve).mul(2).div(lpToken.totalSupply());
}
if (IUniswapV2Factory(lpToken.factory()).getPair(token0, address(weth)) != address(0)) {
(uint256 wethReserve0, uint256 token0ToWethReserve0) = UniswapV2Library.getReserves(lpToken.factory(), address(weth), token0);
uint256 tmp0 = amount.mul(token0Reserve).mul(wethReserve0).mul(2);
return tmp0.div(token0ToWethReserve0).div(lpToken.totalSupply());
}
require(
IUniswapV2Factory(lpToken.factory()).getPair(token1, address(weth)) != address(0),
"Neither token0-weth nor token1-weth pair exists");
(uint256 wethReserve1, uint256 token1ToWethReserve1) = UniswapV2Library.getReserves(lpToken.factory(), address(weth), token1);
uint256 tmp1 = amount.mul(token1Reserve).mul(wethReserve1).mul(2);
return tmp1.div(token1ToWethReserve1).div(lpToken.totalSupply());
}
/**
* @notice Calculates the WETH value for an amount of pool reward token
*/
function rewardValue(uint256 poolId, uint256 amount) external virtual override view returns(uint256) {
address token = address(rewardToken(poolId));
IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(address(token), address(weth)));
if (address(pair) != address(0)) {
(uint tokenReserve0, uint wethReserve0,) = pair.getReserves();
return UniswapV2Library.getAmountOut(amount, tokenReserve0, wethReserve0);
}
pair = IUniswapV2Pair(factory.getPair(address(weth), address(token)));
require(
address(pair) != address(0),
"Neither token-weth nor weth-token pair exists");
(uint wethReserve1, uint tokenReserve1,) = pair.getReserves();
return UniswapV2Library.getAmountOut(amount, tokenReserve1, wethReserve1);
}
function rewardToken(uint256) public virtual override view returns (IERC20) {
return IERC20(0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IMasterChef{
function poolInfo(uint256) external view returns (IERC20,uint256,uint256,uint256);
function userInfo(uint256, address) external view returns (uint256,uint256);
function poolLength() external view returns (uint256);
function deposit(uint256 _pid, uint256 _amount) external;
function withdraw(uint256 _pid, uint256 _amount) external;
function emergencyWithdraw(uint256 _pid) external;
function getMultiplier(uint256 _from, uint256 _to) external view returns (uint256);
function sushiPerBlock() external view returns (uint256);
function totalAllocPoint() external view returns (uint256);
function pendingSushi(uint256 _pid, address _user) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMathUniswap {
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");
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./interfaces/IUniswapV2Pair.sol";
interface IVampireAdapter {
// Victim info
function rewardToken(uint256 poolId) external view returns (IERC20);
function rewardValue(uint256 poolId, uint256 amount) external view returns(uint256);
function poolCount() external view returns (uint256);
function sellableRewardAmount(uint256 poolId) external view returns (uint256);
// Victim actions, requires impersonation via delegatecall
function sellRewardForWeth(address adapter, uint256 poolId, uint256 rewardAmount, address to) external returns(uint256);
// Pool info
function lockableToken(uint256 poolId) external view returns (IERC20);
function lockedAmount(address user, uint256 poolId) external view returns (uint256);
function pendingReward(address adapter, uint256 poolId, uint256 victimPoolId) external view returns (uint256);
// Pool actions, requires impersonation via delegatecall
function deposit(address adapter, uint256 poolId, uint256 amount) external returns (uint256);
function withdraw(address adapter, uint256 poolId, uint256 amount) external returns (uint256);
function claimReward(address adapter, uint256 poolId, uint256 victimPoolId) external;
function emergencyWithdraw(address adapter, uint256 poolId) external;
// Service methods
function poolAddress(uint256 poolId) external view returns (address);
function rewardToWethPool() external view returns (address);
// Governance info methods
function lpTokenValue(uint256 amount, IUniswapV2Pair lpToken) external view returns(uint256);
function lockedValue(address user, uint256 poolId) external view returns (uint256);
function totalLockedValue(uint256 poolId) external view returns (uint256);
function normalizedAPY(uint256 poolId) external view returns (uint256);
}
| Victim info Victim actions, requires impersonation via delegatecall Pool info Pool actions, requires impersonation via delegatecall Service methods Governance info methods | interface IVampireAdapter {
function rewardToken(uint256 poolId) external view returns (IERC20);
function rewardValue(uint256 poolId, uint256 amount) external view returns(uint256);
function poolCount() external view returns (uint256);
function sellableRewardAmount(uint256 poolId) external view returns (uint256);
function sellRewardForWeth(address adapter, uint256 poolId, uint256 rewardAmount, address to) external returns(uint256);
function lockableToken(uint256 poolId) external view returns (IERC20);
function lockedAmount(address user, uint256 poolId) external view returns (uint256);
function pendingReward(address adapter, uint256 poolId, uint256 victimPoolId) external view returns (uint256);
function deposit(address adapter, uint256 poolId, uint256 amount) external returns (uint256);
function withdraw(address adapter, uint256 poolId, uint256 amount) external returns (uint256);
function claimReward(address adapter, uint256 poolId, uint256 victimPoolId) external;
function emergencyWithdraw(address adapter, uint256 poolId) external;
function poolAddress(uint256 poolId) external view returns (address);
function rewardToWethPool() external view returns (address);
function lpTokenValue(uint256 amount, IUniswapV2Pair lpToken) external view returns(uint256);
function lockedValue(address user, uint256 poolId) external view returns (uint256);
function totalLockedValue(uint256 poolId) external view returns (uint256);
function normalizedAPY(uint256 poolId) external view returns (uint256);
}
| 397,099 |
./partial_match/1/0x8ABb6cc2810c22Df468E5fC491AB693F0901c927/sources/PriceOracle.sol | add a and b and then subtract c/ | function addThenSub(
uint256 a,
uint256 b,
uint256 c
) internal pure returns (Error, uint256) {
(Error err0, uint256 sum) = add(a, b);
if (err0 != Error.NO_ERROR) {
return (err0, 0);
}
return sub(sum, c);
}
| 3,661,587 |
./partial_match/1/0xC7e63B18dEDF226b1C1a7A436953a63c518bd442/sources/ENSRegistry.sol | Sets the resolver address for the specified node. _node The node to update. _resolver The address of the resolver./ | function setResolver(bytes32 _node, address _resolver) public authorised(_node) {
emit NewResolver(_node, _resolver);
records[_node].resolver = _resolver;
}
| 4,141,564 |
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.1;
interface IMoonCatReference {
function doc (address contractAddress) external view returns (string memory name, string memory description, string memory details);
function setDoc (address contractAddress, string calldata name, string calldata description) external;
}
interface IMoonCatTraits {
function kTraitsOf (bytes5 catId) external view returns (bool genesis, bool pale, uint8 facing, uint8 expression, uint8 pattern, uint8 pose);
}
interface IMoonCatColors {
function BasePalette (uint index) external view returns (uint8);
function colorsOf (bytes5 catId) external view returns (uint8[24] memory);
function accessoryColorsOf (bytes5 catId) external view returns (uint8[45] memory);
function colorAlpha (uint8 id) external pure returns (uint8);
}
interface IMoonCatSVGs {
function flip (bytes memory svgData) external pure returns (bytes memory);
function getPixelData (uint8 facing, uint8 expression, uint8 pose, uint8 pattern, uint8[24] memory colors) external view returns (bytes memory);
function boundingBox (uint8 facing, uint8 pose) external view returns (uint8 x, uint8 y, uint8 width, uint8 height);
function glowGroup (bytes memory pixels, uint8 r, uint8 g, uint8 b) external pure returns (bytes memory);
function svgTag (uint8 x, uint8 y, uint8 w, uint8 h) external pure returns (bytes memory);
function uint2str (uint value) external pure returns (string memory);
}
interface IMoonCatRescue {
function rescueOrder(uint256 tokenId) external view returns (bytes5);
function catOwners(bytes5 catId) external view returns (address);
}
interface IMoonCatAccessories {
function accessoryImageData (uint256 accessoryId) external view returns (bytes2[4] memory positions,
bytes8[7] memory palettes,
uint8 width,
uint8 height,
uint8 meta,
bytes memory IDAT);
function doesMoonCatOwnAccessory (uint256 rescueOrder, uint256 accessoryId) external view returns (bool);
function balanceOf (uint256 rescueOrder) external view returns (uint256);
struct OwnedAccessory {
uint232 accessoryId;
uint8 paletteIndex;
uint16 zIndex;
}
function ownedAccessoryByIndex (uint256 rescueOrder, uint256 ownedAccessoryIndex) external view returns (OwnedAccessory memory);
}
interface IMoonCatSVGS {
function imageOfExtended (bytes5 catId, bytes memory pre, bytes memory post) external view returns (string memory);
}
interface IReverseResolver {
function claim(address owner) external returns (bytes32);
}
interface IERC20 {
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
}
interface IERC721 {
function safeTransferFrom(address from, address to, uint256 tokenId) external;
function ownerOf(uint256 tokenId) external view returns (address);
}
library Base64 {
bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/// @notice Encodes some bytes to the base64 representation
function encode(bytes memory data) internal pure returns (string memory) {
uint256 len = data.length;
if (len == 0) return "";
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((len + 2) / 3);
// Add some extra buffer at the end
bytes memory result = new bytes(encodedLen + 32);
bytes memory table = TABLE;
assembly {
let tablePtr := add(table, 1)
let resultPtr := add(result, 32)
for {
let i := 0
} lt(i, len) {
} {
i := add(i, 3)
let input := and(mload(add(data, i)), 0xffffff)
let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF))
out := shl(224, out)
mstore(resultPtr, out)
resultPtr := add(resultPtr, 4)
}
switch mod(len, 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
mstore(result, encodedLen)
}
return string(result);
}
}
/**
* @title AccessoryPNGs
* @notice On Chain MoonCat Accessory Image Generation
* @dev Builds PNGs of MoonCat Accessories
*/
contract MoonCatAccessoryImages {
/* External Contracts */
IMoonCatRescue MoonCatRescue = IMoonCatRescue(0x60cd862c9C687A9dE49aecdC3A99b74A4fc54aB6);
IMoonCatAccessories MoonCatAccessories = IMoonCatAccessories(0x8d33303023723dE93b213da4EB53bE890e747C63);
IMoonCatReference MoonCatReference;
IMoonCatTraits MoonCatTraits;
IMoonCatColors MoonCatColors;
IMoonCatSVGs MoonCatSVGs;
address MoonCatAcclimatorAddress = 0xc3f733ca98E0daD0386979Eb96fb1722A1A05E69;
/* CRC */
uint32[256] CRCTable = [0x0,0x77073096,0xee0e612c,0x990951ba,0x76dc419,0x706af48f,0xe963a535,0x9e6495a3,0xedb8832,0x79dcb8a4,0xe0d5e91e,0x97d2d988,0x9b64c2b,0x7eb17cbd,0xe7b82d07,0x90bf1d91,0x1db71064,0x6ab020f2,0xf3b97148,0x84be41de,0x1adad47d,0x6ddde4eb,0xf4d4b551,0x83d385c7,0x136c9856,0x646ba8c0,0xfd62f97a,0x8a65c9ec,0x14015c4f,0x63066cd9,0xfa0f3d63,0x8d080df5,0x3b6e20c8,0x4c69105e,0xd56041e4,0xa2677172,0x3c03e4d1,0x4b04d447,0xd20d85fd,0xa50ab56b,0x35b5a8fa,0x42b2986c,0xdbbbc9d6,0xacbcf940,0x32d86ce3,0x45df5c75,0xdcd60dcf,0xabd13d59,0x26d930ac,0x51de003a,0xc8d75180,0xbfd06116,0x21b4f4b5,0x56b3c423,0xcfba9599,0xb8bda50f,0x2802b89e,0x5f058808,0xc60cd9b2,0xb10be924,0x2f6f7c87,0x58684c11,0xc1611dab,0xb6662d3d,0x76dc4190,0x1db7106,0x98d220bc,0xefd5102a,0x71b18589,0x6b6b51f,0x9fbfe4a5,0xe8b8d433,0x7807c9a2,0xf00f934,0x9609a88e,0xe10e9818,0x7f6a0dbb,0x86d3d2d,0x91646c97,0xe6635c01,0x6b6b51f4,0x1c6c6162,0x856530d8,0xf262004e,0x6c0695ed,0x1b01a57b,0x8208f4c1,0xf50fc457,0x65b0d9c6,0x12b7e950,0x8bbeb8ea,0xfcb9887c,0x62dd1ddf,0x15da2d49,0x8cd37cf3,0xfbd44c65,0x4db26158,0x3ab551ce,0xa3bc0074,0xd4bb30e2,0x4adfa541,0x3dd895d7,0xa4d1c46d,0xd3d6f4fb,0x4369e96a,0x346ed9fc,0xad678846,0xda60b8d0,0x44042d73,0x33031de5,0xaa0a4c5f,0xdd0d7cc9,0x5005713c,0x270241aa,0xbe0b1010,0xc90c2086,0x5768b525,0x206f85b3,0xb966d409,0xce61e49f,0x5edef90e,0x29d9c998,0xb0d09822,0xc7d7a8b4,0x59b33d17,0x2eb40d81,0xb7bd5c3b,0xc0ba6cad,0xedb88320,0x9abfb3b6,0x3b6e20c,0x74b1d29a,0xead54739,0x9dd277af,0x4db2615,0x73dc1683,0xe3630b12,0x94643b84,0xd6d6a3e,0x7a6a5aa8,0xe40ecf0b,0x9309ff9d,0xa00ae27,0x7d079eb1,0xf00f9344,0x8708a3d2,0x1e01f268,0x6906c2fe,0xf762575d,0x806567cb,0x196c3671,0x6e6b06e7,0xfed41b76,0x89d32be0,0x10da7a5a,0x67dd4acc,0xf9b9df6f,0x8ebeeff9,0x17b7be43,0x60b08ed5,0xd6d6a3e8,0xa1d1937e,0x38d8c2c4,0x4fdff252,0xd1bb67f1,0xa6bc5767,0x3fb506dd,0x48b2364b,0xd80d2bda,0xaf0a1b4c,0x36034af6,0x41047a60,0xdf60efc3,0xa867df55,0x316e8eef,0x4669be79,0xcb61b38c,0xbc66831a,0x256fd2a0,0x5268e236,0xcc0c7795,0xbb0b4703,0x220216b9,0x5505262f,0xc5ba3bbe,0xb2bd0b28,0x2bb45a92,0x5cb36a04,0xc2d7ffa7,0xb5d0cf31,0x2cd99e8b,0x5bdeae1d,0x9b64c2b0,0xec63f226,0x756aa39c,0x26d930a,0x9c0906a9,0xeb0e363f,0x72076785,0x5005713,0x95bf4a82,0xe2b87a14,0x7bb12bae,0xcb61b38,0x92d28e9b,0xe5d5be0d,0x7cdcefb7,0xbdbdf21,0x86d3d2d4,0xf1d4e242,0x68ddb3f8,0x1fda836e,0x81be16cd,0xf6b9265b,0x6fb077e1,0x18b74777,0x88085ae6,0xff0f6a70,0x66063bca,0x11010b5c,0x8f659eff,0xf862ae69,0x616bffd3,0x166ccf45,0xa00ae278,0xd70dd2ee,0x4e048354,0x3903b3c2,0xa7672661,0xd06016f7,0x4969474d,0x3e6e77db,0xaed16a4a,0xd9d65adc,0x40df0b66,0x37d83bf0,0xa9bcae53,0xdebb9ec5,0x47b2cf7f,0x30b5ffe9,0xbdbdf21c,0xcabac28a,0x53b39330,0x24b4a3a6,0xbad03605,0xcdd70693,0x54de5729,0x23d967bf,0xb3667a2e,0xc4614ab8,0x5d681b02,0x2a6f2b94,0xb40bbe37,0xc30c8ea1,0x5a05df1b,0x2d02ef8d];
/**
* @dev Create a cyclic redundancy check (CRC) value for a given set of data.
*
* This is the error-detecting code used for the PNG data format to validate each chunk of data within the file. This Solidity implementation
* is needed to be able to dynamically create PNG files piecemeal.
*/
function crc32 (bytes memory data) public view returns (uint32) {
uint32 crc = type(uint32).max;
for (uint i = 0; i < data.length; i++) {
uint8 byt;
assembly {
byt := mload(add(add(data, 0x1), i))
}
crc = (crc >> 8) ^ CRCTable[(crc & 255) ^ byt];
}
return ~crc;
}
/* accessoryPNGs */
uint64 constant public PNGHeader = 0x89504e470d0a1a0a;
uint96 constant public PNGFooter = 0x0000000049454e44ae426082;
uint40 constant internal IHDRDetails = 0x0803000000;
/**
* @dev Assemble a block of data into a valid PNG file chunk.
*/
function generatePNGChunk (string memory typeCode, bytes memory data) public view returns (bytes memory) {
uint32 crc = crc32(abi.encodePacked(typeCode, data));
return abi.encodePacked(uint32(data.length),
typeCode,
data,
crc);
}
/**
* @dev Take metadata about an individual Accessory and the MoonCat wearing it, and render the Accessory as a PNG image.
*/
function assemblePNG (uint8[45] memory accessoryColors, bytes8 palette, uint8 width, uint8 height, bytes memory IDAT)
internal
view
returns (bytes memory)
{
bytes memory colors = new bytes(27);
bytes memory alphas = new bytes(9);
for (uint i = 0; i < 8; i++) {
uint256 colorIndex = uint256(uint8(palette[i]));
alphas[i + 1] = bytes1(MoonCatColors.colorAlpha(uint8(colorIndex)));
if (colorIndex > 113) {
colorIndex = (colorIndex - 113) * 3;
colors[i * 3 + 3] = bytes1(accessoryColors[colorIndex]);
colors[i * 3 + 4] = bytes1(accessoryColors[colorIndex + 1]);
colors[i * 3 + 5] = bytes1(accessoryColors[colorIndex + 2]);
} else {
colorIndex = colorIndex * 3;
colors[i * 3 + 3] = bytes1(MoonCatColors.BasePalette(colorIndex));
colors[i * 3 + 4] = bytes1(MoonCatColors.BasePalette(colorIndex + 1));
colors[i * 3 + 5] = bytes1(MoonCatColors.BasePalette(colorIndex + 2));
}
}
return abi.encodePacked(PNGHeader,
generatePNGChunk("IHDR", abi.encodePacked(uint32(width), uint32(height), IHDRDetails)),
generatePNGChunk("PLTE", colors),//abi.encodePacked(colors)),
generatePNGChunk("tRNS", alphas),
generatePNGChunk("IDAT", IDAT),
PNGFooter);
}
/**
* @dev For a given MoonCat rescue order and Accessory ID and palette ID, render as PNG.
* The PNG output is converted to a base64-encoded blob, which is the format used for encoding into an SVG or inline HTML.
*/
function accessoryPNG (uint256 rescueOrder, uint256 accessoryId, uint16 paletteIndex) public view returns (string memory) {
require(rescueOrder < 25440, "Invalid Rescue Order");
bytes5 catId = MoonCatRescue.rescueOrder(rescueOrder);
uint8[45] memory accessoryColors = MoonCatColors.accessoryColorsOf(catId);
(,bytes8[7] memory palettes, uint8 width, uint8 height,,bytes memory IDAT) = MoonCatAccessories.accessoryImageData(accessoryId);
return string(abi.encodePacked("data:image/png;base64,",
Base64.encode(assemblePNG(accessoryColors, palettes[paletteIndex], width, height, IDAT))));
}
/* Composite */
struct PreppedAccessory {
uint16 zIndex;
uint8 offsetX;
uint8 offsetY;
uint8 width;
uint8 height;
bool mirror;
bool background;
bytes8 palette;
bytes IDAT;
}
/**
* @dev Given a list of accessories, sort them by z-index.
*/
function sortAccessories(PreppedAccessory[] memory pas) internal pure {
for (uint i = 1; i < pas.length; i++) {
PreppedAccessory memory pa = pas[i];
uint key = pa.zIndex;
uint j = i;
while (j > 0 && pas[j - 1].zIndex > key) {
pas[j] = pas[j - 1];
j--;
}
pas[j] = pa;
}
}
/**
* @dev Given a MoonCat and accessory's basic information, derive colors and other metadata for them.
*/
function prepAccessory (uint8 facing, uint8 pose, bool allowUnverified, IMoonCatAccessories.OwnedAccessory memory accessory)
internal
view
returns (PreppedAccessory memory)
{
(bytes2[4] memory positions,
bytes8[7] memory palettes,
uint8 width, uint8 height,
uint8 meta,
bytes memory IDAT) = MoonCatAccessories.accessoryImageData(accessory.accessoryId);
bytes2 position = positions[pose];
uint8 offsetX = uint8(position[0]);
uint8 offsetY = uint8(position[1]);
bool mirror;
if (facing == 1) {
mirror = ((meta >> 1) & 1) == 1;
if (((meta >> 2) & 1) == 1) { // mirrorPlacement
if (!mirror) {
offsetX = 128 - offsetX - width;
}
} else if (mirror) {
offsetX = 128 - offsetX - width;
}
}
uint16 zIndex = accessory.zIndex;
if (!allowUnverified) {
zIndex = zIndex * (meta >> 7); // check for approval
}
return PreppedAccessory(zIndex,
offsetX, offsetY,
width, height,
mirror,
(meta & 1) == 1, // background
palettes[accessory.paletteIndex],
IDAT);
}
/**
* @dev Given a MoonCat and a set of basic Accessories' information, derive their metadata and split into foreground/background lists.
*/
function prepAccessories (uint256 rescueOrder, uint8 facing, uint8 pose, bool allowUnverified, IMoonCatAccessories.OwnedAccessory[] memory accessories) public view returns (PreppedAccessory[] memory, PreppedAccessory[] memory) {
PreppedAccessory[] memory preppedAccessories = new PreppedAccessory[](accessories.length);
uint bgCount = 0;
uint fgCount = 0;
for (uint i = 0; i < accessories.length; i++) {
IMoonCatAccessories.OwnedAccessory memory accessory = accessories[i];
require(MoonCatAccessories.doesMoonCatOwnAccessory(rescueOrder, accessory.accessoryId), "Accessory Not Owned By MoonCat");
if (accessory.zIndex > 0) {
preppedAccessories[i] = prepAccessory(facing, pose, allowUnverified, accessory);
if (preppedAccessories[i].background) {
bgCount++;
} else {
fgCount++;
}
}
}
PreppedAccessory[] memory background = new PreppedAccessory[](bgCount);
PreppedAccessory[] memory foreground = new PreppedAccessory[](fgCount);
bgCount = 0;
fgCount = 0;
for (uint i = 0; i < preppedAccessories.length; i++) {
if (preppedAccessories[i].zIndex > 0) {
if (preppedAccessories[i].background) {
background[bgCount] = preppedAccessories[i];
bgCount++;
} else {
foreground[fgCount] = preppedAccessories[i];
fgCount++;
}
}
}
sortAccessories(background);
sortAccessories(foreground);
return (background, foreground);
}
/**
* @dev Convert a MoonCat facing and pose trait information into an SVG viewBox definition to set that canvas size.
*/
function initialBoundingBox (uint8 facing, uint8 pose) internal view returns (uint8, uint8, uint8, uint8) {
(uint8 x1, uint8 y1, uint8 width, uint8 height) = MoonCatSVGs.boundingBox(facing, pose);
return (x1, y1, x1 + width, y1 + height);
}
/**
* @dev Given a MoonCat's pose information and a list of Accessories, calculate a bounding box that will cover them all.
*/
function getBoundingBox (uint8 facing, uint8 pose, PreppedAccessory[] memory background, PreppedAccessory[] memory foreground)
internal
view
returns (uint8, uint8, uint8, uint8)
{
(uint8 x1, uint8 y1, uint8 x2, uint8 y2) = initialBoundingBox(facing, pose);
uint8 offsetX;
for (uint i = 0; i < background.length; i++) {
PreppedAccessory memory pa = background[i];
if (pa.zIndex > 0) {
if (pa.mirror) {
offsetX = 128 - pa.offsetX - pa.width;
} else {
offsetX = pa.offsetX;
}
if (offsetX < x1) x1 = offsetX;
if (pa.offsetY < y1) y1 = pa.offsetY;
if ((offsetX + pa.width) > x2) x2 = offsetX + pa.width;
if ((pa.offsetY + pa.height) > y2) y2 = pa.offsetY + pa.height;
}
}
for (uint i = 0; i < foreground.length; i++) {
PreppedAccessory memory pa = foreground[i];
if (pa.zIndex > 0) {
if (pa.mirror) {
offsetX = 128 - pa.offsetX - pa.width;
} else {
offsetX = pa.offsetX;
}
if (offsetX < x1) x1 = offsetX;
if (pa.offsetY < y1) y1 = pa.offsetY;
if ((offsetX + pa.width) > x2) x2 = offsetX + pa.width;
if ((pa.offsetY + pa.height) > y2) y2 = pa.offsetY + pa.height;
}
}
return (x1, y1, x2 - x1, y2 - y1);
}
/**
* @dev Given an Accessory's metadata, generate a PNG image of that Accessory and wrap in an SVG image object.
*/
function accessorySVGSnippet (PreppedAccessory memory pa, uint8[45] memory accessoryColors)
internal
view
returns (bytes memory)
{
bytes memory img = assemblePNG(accessoryColors, pa.palette, pa.width, pa.height, pa.IDAT);
bytes memory snippet = abi.encodePacked("<image x=\"", MoonCatSVGs.uint2str(pa.offsetX),
"\" y=\"", MoonCatSVGs.uint2str(pa.offsetY),
"\" width=\"", MoonCatSVGs.uint2str(pa.width),
"\" height=\"", MoonCatSVGs.uint2str(pa.height),
"\" href=\"data:image/png;base64,", Base64.encode(img),
"\"/>");
if (pa.mirror) {
return MoonCatSVGs.flip(snippet);
}
return snippet;
}
/**
* @dev Given a set of metadata about MoonCat and desired Accessories to render on it, generate an SVG of that appearance.
*/
function assembleSVG (uint8 x,
uint8 y,
uint8 width,
uint8 height,
bytes memory mooncatPixelData,
uint8[45] memory accessoryColors,
PreppedAccessory[] memory background,
PreppedAccessory[] memory foreground,
uint8 glowLevel)
internal
view
returns (string memory)
{
bytes memory bg;
bytes memory fg;
for (uint i = background.length; i >= 1; i--) {
bg = abi.encodePacked(bg, accessorySVGSnippet(background[i - 1], accessoryColors));
}
for (uint i = 0; i < foreground.length; i++) {
fg = abi.encodePacked(fg, accessorySVGSnippet(foreground[i], accessoryColors));
}
if (glowLevel == 0) {
return string(abi.encodePacked(MoonCatSVGs.svgTag(x, y, width, height),
bg,
mooncatPixelData,
fg,
"</svg>"));
} else if (glowLevel == 1) {
return string(abi.encodePacked(MoonCatSVGs.svgTag(x, y, width, height),
MoonCatSVGs.glowGroup(mooncatPixelData,
accessoryColors[0],
accessoryColors[1],
accessoryColors[2]),
bg,
mooncatPixelData,
fg,
"</svg>"));
} else {
return string(abi.encodePacked(MoonCatSVGs.svgTag(x, y, width, height),
MoonCatSVGs.glowGroup(abi.encodePacked(bg,
mooncatPixelData,
fg),
accessoryColors[0],
accessoryColors[1],
accessoryColors[2]),
"</svg>"));
}
}
/**
* @dev Given a set of metadata about MoonCat and desired Accessories to render on it, generate an SVG of that appearance.
*/
function assembleSVG (uint8 facing,
uint8 pose,
bytes memory mooncatPixelData,
uint8[45] memory accessoryColors,
PreppedAccessory[] memory background,
PreppedAccessory[] memory foreground,
uint8 glowLevel)
internal
view
returns (string memory)
{
(uint8 x, uint8 y, uint8 width, uint8 height) = getBoundingBox(facing, pose, background, foreground);
return assembleSVG(x, y, width, height, mooncatPixelData, accessoryColors, background, foreground, glowLevel);
}
/**
* @dev Given a MoonCat Rescue Order and a list of Accessories they own, render an SVG of them wearing those accessories.
*/
function accessorizedImageOf (uint256 rescueOrder, IMoonCatAccessories.OwnedAccessory[] memory accessories, uint8 glowLevel, bool allowUnverified)
public
view
returns (string memory)
{
uint8 facing;
uint8 pose;
bytes memory mooncatPixelData;
uint8[45] memory accessoryColors;
{
require(rescueOrder < 25440, "Invalid Rescue Order");
bytes5 catId = MoonCatRescue.rescueOrder(rescueOrder);
uint8[24] memory colors = MoonCatColors.colorsOf(catId);
{
uint8 expression;
uint8 pattern;
(,, facing, expression, pattern, pose) = MoonCatTraits.kTraitsOf(catId);
mooncatPixelData = MoonCatSVGs.getPixelData(facing, expression, pose, pattern, colors);
}
accessoryColors = MoonCatColors.accessoryColorsOf(catId);
}
(PreppedAccessory[] memory background, PreppedAccessory[] memory foreground) = prepAccessories(rescueOrder, facing, pose, allowUnverified, accessories);
return assembleSVG(facing, pose, mooncatPixelData, accessoryColors, background, foreground, glowLevel);
}
/**
* @dev Given a MoonCat Rescue Order, look up what Accessories they are currently wearing, and render an SVG of them wearing those accessories.
*/
function accessorizedImageOf (uint256 rescueOrder, uint8 glowLevel, bool allowUnverified)
public
view
returns (string memory)
{
uint accessoryCount = MoonCatAccessories.balanceOf(rescueOrder);
IMoonCatAccessories.OwnedAccessory[] memory accessories = new IMoonCatAccessories.OwnedAccessory[](accessoryCount);
for (uint i = 0; i < accessoryCount; i++) {
accessories[i] = MoonCatAccessories.ownedAccessoryByIndex(rescueOrder, i);
}
return accessorizedImageOf(rescueOrder, accessories, glowLevel, allowUnverified);
}
/**
* @dev Given a MoonCat Rescue Order, look up what verified Accessories they are currently wearing, and render an SVG of them wearing those accessories.
*/
function accessorizedImageOf (uint256 rescueOrder, uint8 glowLevel)
public
view
returns (string memory)
{
return accessorizedImageOf(rescueOrder, glowLevel, false);
}
/**
* @dev Given a MoonCat Rescue Order, look up what verified Accessories they are currently wearing, and render an unglowing SVG of them wearing those accessories.
*/
function accessorizedImageOf (uint256 rescueOrder)
public
view
returns (string memory)
{
return accessorizedImageOf(rescueOrder, 0, false);
}
/**
* @dev Given a MoonCat Rescue Order and an Accessory ID, return the bounding box of the Accessory, relative to the MoonCat.
*/
function placementOf (uint256 rescueOrder, uint256 accessoryId)
public
view
returns (uint8 offsetX, uint8 offsetY, uint8 width, uint8 height, bool mirror, bool background)
{
bytes5 catId = MoonCatRescue.rescueOrder(rescueOrder);
(,, uint8 facing,,, uint8 pose) = MoonCatTraits.kTraitsOf(catId);
bytes2[4] memory positions;
uint8 meta;
(positions,, width, height, meta,) = MoonCatAccessories.accessoryImageData(accessoryId);
bytes2 position = positions[pose];
background = (meta & 1) == 1;
bool mirrorPlacement;
if (facing == 1) {
mirror = ((meta >> 1) & 1) == 1;
mirrorPlacement = ((meta >> 2) & 1) == 1;
}
offsetX = uint8(position[0]);
offsetY = uint8(position[1]);
if (mirrorPlacement) {
offsetX = 128 - offsetX - width;
}
}
/* General */
/**
* @dev Get documentation about this contract.
*/
function doc() public view returns (string memory name, string memory description, string memory details) {
return MoonCatReference.doc(address(this));
}
constructor (address MoonCatReferenceAddress, address MoonCatTraitsAddress, address MoonCatColorsAddress, address MoonCatSVGsAddress) {
owner = payable(msg.sender);
// https://docs.ens.domains/contract-api-reference/reverseregistrar#claim-address
IReverseResolver(0x084b1c3C81545d370f3634392De611CaaBFf8148).claim(msg.sender);
MoonCatReference = IMoonCatReference(MoonCatReferenceAddress);
MoonCatTraits = IMoonCatTraits(MoonCatTraitsAddress);
MoonCatColors = IMoonCatColors(MoonCatColorsAddress);
MoonCatSVGs = IMoonCatSVGs(MoonCatSVGsAddress);
}
address payable public owner;
modifier onlyOwner () {
require(msg.sender == owner, "Only Owner");
_;
}
/**
* @dev Allow current `owner` to transfer ownership to another address.
*/
function transferOwnership (address payable newOwner) public onlyOwner {
owner = newOwner;
}
/**
* @dev Update the location of the Reference Contract.
*/
function setReferenceContract (address referenceContract) public onlyOwner {
MoonCatReference = IMoonCatReference(referenceContract);
}
/**
* @dev Rescue ERC20 assets sent directly to this contract.
*/
function withdrawForeignERC20(address tokenContract) public onlyOwner {
IERC20 token = IERC20(tokenContract);
token.transfer(owner, token.balanceOf(address(this)));
}
/**
* @dev Rescue ERC721 assets sent directly to this contract.
*/
function withdrawForeignERC721(address tokenContract, uint256 tokenId) public onlyOwner {
IERC721(tokenContract).safeTransferFrom(address(this), owner, tokenId);
}
} | Given a MoonCat Rescue Order and a list of Accessories they own, render an SVG of them wearing those accessories./ | {
uint8 facing;
uint8 pose;
bytes memory mooncatPixelData;
uint8[45] memory accessoryColors;
function assembleSVG (uint8 facing,
uint8 pose,
bytes memory mooncatPixelData,
uint8[45] memory accessoryColors,
PreppedAccessory[] memory background,
PreppedAccessory[] memory foreground,
uint8 glowLevel)
internal
view
returns (string memory)
}
function accessorizedImageOf (uint256 rescueOrder, IMoonCatAccessories.OwnedAccessory[] memory accessories, uint8 glowLevel, bool allowUnverified)
public
view
returns (string memory)
{
require(rescueOrder < 25440, "Invalid Rescue Order");
bytes5 catId = MoonCatRescue.rescueOrder(rescueOrder);
uint8[24] memory colors = MoonCatColors.colorsOf(catId);
{
uint8 expression;
uint8 pattern;
(,, facing, expression, pattern, pose) = MoonCatTraits.kTraitsOf(catId);
mooncatPixelData = MoonCatSVGs.getPixelData(facing, expression, pose, pattern, colors);
}
accessoryColors = MoonCatColors.accessoryColorsOf(catId);
}
(PreppedAccessory[] memory background, PreppedAccessory[] memory foreground) = prepAccessories(rescueOrder, facing, pose, allowUnverified, accessories);
return assembleSVG(facing, pose, mooncatPixelData, accessoryColors, background, foreground, glowLevel);
function assembleSVG (uint8 facing,
uint8 pose,
bytes memory mooncatPixelData,
uint8[45] memory accessoryColors,
PreppedAccessory[] memory background,
PreppedAccessory[] memory foreground,
uint8 glowLevel)
internal
view
returns (string memory)
}
function accessorizedImageOf (uint256 rescueOrder, IMoonCatAccessories.OwnedAccessory[] memory accessories, uint8 glowLevel, bool allowUnverified)
public
view
returns (string memory)
{
require(rescueOrder < 25440, "Invalid Rescue Order");
bytes5 catId = MoonCatRescue.rescueOrder(rescueOrder);
uint8[24] memory colors = MoonCatColors.colorsOf(catId);
{
uint8 expression;
uint8 pattern;
(,, facing, expression, pattern, pose) = MoonCatTraits.kTraitsOf(catId);
mooncatPixelData = MoonCatSVGs.getPixelData(facing, expression, pose, pattern, colors);
}
accessoryColors = MoonCatColors.accessoryColorsOf(catId);
}
(PreppedAccessory[] memory background, PreppedAccessory[] memory foreground) = prepAccessories(rescueOrder, facing, pose, allowUnverified, accessories);
return assembleSVG(facing, pose, mooncatPixelData, accessoryColors, background, foreground, glowLevel);
}
| 13,788,017 |
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity =0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "./interfaces/Uniswap/IUniswapV2Factory.sol";
import "./interfaces/Uniswap/IUniswapV2Pair.sol";
import "./interfaces/Uniswap/IUniswapV2Router02.sol";
import "./interfaces/IDigitalReserve.sol";
/**
* @dev Implementation of Digital Reserve contract.
* Digital Reserve contract converts user's DRC into a set of SoV assets using the Uniswap router,
* and hold these assets for it's users.
* When users initiate a withdrawal action, the contract converts a share of the vault,
* that the user is requesting, to DRC and sends it back to their wallet.
*/
contract DigitalReserve is IDigitalReserve, ERC20, Ownable {
using SafeMath for uint256;
struct StategyToken {
address tokenAddress;
uint8 tokenPercentage;
}
/**
* @dev Set Uniswap router address, DRC token address, DR name.
*/
constructor(
address _router,
address _drcAddress,
string memory _name,
string memory _symbol
) public ERC20(_name, _symbol) {
drcAddress = _drcAddress;
uniswapRouter = IUniswapV2Router02(_router);
}
StategyToken[] private _strategyTokens;
uint8 private _feeFraction = 1;
uint8 private _feeBase = 100;
uint8 private constant _priceDecimals = 18;
address private drcAddress;
bool private depositEnabled = false;
IUniswapV2Router02 private immutable uniswapRouter;
/**
* @dev See {IDigitalReserve-strategyTokenCount}.
*/
function strategyTokenCount() public view override returns (uint256) {
return _strategyTokens.length;
}
/**
* @dev See {IDigitalReserve-strategyTokens}.
*/
function strategyTokens(uint8 index) external view override returns (address, uint8) {
return (_strategyTokens[index].tokenAddress, _strategyTokens[index].tokenPercentage);
}
/**
* @dev See {IDigitalReserve-withdrawalFee}.
*/
function withdrawalFee() external view override returns (uint8, uint8) {
return (_feeFraction, _feeBase);
}
/**
* @dev See {IDigitalReserve-priceDecimals}.
*/
function priceDecimals() external view override returns (uint8) {
return _priceDecimals;
}
/**
* @dev See {IDigitalReserve-totalTokenStored}.
*/
function totalTokenStored() public view override returns (uint256[] memory) {
uint256[] memory amounts = new uint256[](strategyTokenCount());
for (uint8 i = 0; i < strategyTokenCount(); i++) {
amounts[i] = IERC20(_strategyTokens[i].tokenAddress).balanceOf(address(this));
}
return amounts;
}
/**
* @dev See {IDigitalReserve-getUserVaultInDrc}.
*/
function getUserVaultInDrc(
address user,
uint8 percentage
) public view override returns (uint256, uint256, uint256) {
uint256[] memory userStrategyTokens = _getStrategyTokensByPodAmount(balanceOf(user).mul(percentage).div(100));
uint256 userVaultWorthInEth = _getEthAmountByStrategyTokensAmount(userStrategyTokens, true);
uint256 userVaultWorthInEthAfterSwap = _getEthAmountByStrategyTokensAmount(userStrategyTokens, false);
uint256 drcAmountBeforeFees = _getTokenAmountByEthAmount(userVaultWorthInEth, drcAddress, true);
uint256 fees = userVaultWorthInEthAfterSwap.mul(_feeFraction).div(_feeBase + _feeFraction);
uint256 drcAmountAfterFees = _getTokenAmountByEthAmount(userVaultWorthInEthAfterSwap.sub(fees), drcAddress, false);
return (drcAmountBeforeFees, drcAmountAfterFees, fees);
}
/**
* @dev See {IDigitalReserve-getProofOfDepositPrice}.
*/
function getProofOfDepositPrice() public view override returns (uint256) {
uint256 proofOfDepositPrice = 0;
if (totalSupply() > 0) {
proofOfDepositPrice = _getEthAmountByStrategyTokensAmount(totalTokenStored(), true).mul(1e18).div(totalSupply());
}
return proofOfDepositPrice;
}
/**
* @dev See {IDigitalReserve-depositPriceImpact}.
*/
function depositPriceImpact(uint256 drcAmount) public view override returns (uint256) {
uint256 ethWorth = _getEthAmountByTokenAmount(drcAmount, drcAddress, false);
return _getEthToStrategyTokensPriceImpact(ethWorth);
}
/**
* @dev See {IDigitalReserve-depositDrc}.
*/
function depositDrc(uint256 drcAmount, uint32 deadline) external override {
require(strategyTokenCount() >= 1, "Strategy hasn't been set.");
require(depositEnabled, "Deposit is disabled.");
require(IERC20(drcAddress).allowance(msg.sender, address(this)) >= drcAmount, "Contract is not allowed to spend user's DRC.");
require(IERC20(drcAddress).balanceOf(msg.sender) >= drcAmount, "Attempted to deposit more than balance.");
uint256 swapPriceImpact = depositPriceImpact(drcAmount);
uint256 feeImpact = (_feeFraction * 10000) / (_feeBase + _feeFraction);
require(swapPriceImpact <= 100 + feeImpact, "Price impact on this swap is larger than 1% plus fee percentage.");
SafeERC20.safeTransferFrom(IERC20(drcAddress), msg.sender, address(this), drcAmount);
// Get current unit price before adding tokens to vault
uint256 currentPodUnitPrice = getProofOfDepositPrice();
uint256 ethConverted = _convertTokenToEth(drcAmount, drcAddress, deadline);
_convertEthToStrategyTokens(ethConverted, deadline);
uint256 podToMint = 0;
if (totalSupply() == 0) {
podToMint = drcAmount.mul(1e15);
} else {
uint256 vaultTotalInEth = _getEthAmountByStrategyTokensAmount(totalTokenStored(), true);
uint256 newPodTotal = vaultTotalInEth.mul(1e18).div(currentPodUnitPrice);
podToMint = newPodTotal.sub(totalSupply());
}
_mint(msg.sender, podToMint);
emit Deposit(msg.sender, drcAmount, podToMint, totalSupply(), totalTokenStored());
}
/**
* @dev See {IDigitalReserve-withdrawDrc}.
*/
function withdrawDrc(uint256 drcAmount, uint32 deadline) external override {
require(balanceOf(msg.sender) > 0, "Vault balance is 0");
address[] memory path = new address[](2);
path[0] = uniswapRouter.WETH();
path[1] = drcAddress;
uint256 ethNeeded = uniswapRouter.getAmountsIn(drcAmount, path)[0];
uint256 ethNeededPlusFee = ethNeeded.mul(_feeBase + _feeFraction).div(_feeBase);
uint256[] memory userStrategyTokens = _getStrategyTokensByPodAmount(balanceOf(msg.sender));
uint256 userVaultWorth = _getEthAmountByStrategyTokensAmount(userStrategyTokens, false);
require(userVaultWorth >= ethNeededPlusFee, "Attempt to withdraw more than user's holding.");
uint256 amountFraction = ethNeededPlusFee.mul(1e10).div(userVaultWorth);
uint256 podToBurn = balanceOf(msg.sender).mul(amountFraction).div(1e10);
_withdrawProofOfDeposit(podToBurn, deadline);
}
/**
* @dev See {IDigitalReserve-withdrawPercentage}.
*/
function withdrawPercentage(uint8 percentage, uint32 deadline) external override {
require(balanceOf(msg.sender) > 0, "Vault balance is 0");
require(percentage <= 100, "Attempt to withdraw more than 100% of the asset");
uint256 podToBurn = balanceOf(msg.sender).mul(percentage).div(100);
_withdrawProofOfDeposit(podToBurn, deadline);
}
/**
* @dev Enable or disable deposit.
* @param status Deposit allowed or not
* Disable deposit if it is to protect users' fund if there's any security issue or assist DR upgrade.
*/
function changeDepositStatus(bool status) external onlyOwner {
depositEnabled = status;
}
/**
* @dev Change withdrawal fee percentage.
* If 1%, then input (1,100)
* If 0.5%, then input (5,1000)
* @param withdrawalFeeFraction_ Fraction of withdrawal fee based on withdrawalFeeBase_
* @param withdrawalFeeBase_ Fraction of withdrawal fee base
*/
function changeFee(uint8 withdrawalFeeFraction_, uint8 withdrawalFeeBase_) external onlyOwner {
require(withdrawalFeeFraction_ <= withdrawalFeeBase_, "Fee fraction exceeded base.");
uint8 percentage = (withdrawalFeeFraction_ * 100) / withdrawalFeeBase_;
require(percentage <= 2, "Attempt to set percentage higher than 2%."); // Requested by community
_feeFraction = withdrawalFeeFraction_;
_feeBase = withdrawalFeeBase_;
}
/**
* @dev Set or change DR strategy tokens and allocations.
* @param strategyTokens_ Array of strategy tokens.
* @param tokenPercentage_ Array of strategy tokens' percentage allocations.
* @param deadline Unix timestamp after which the transaction will revert.
*/
function changeStrategy(
address[] calldata strategyTokens_,
uint8[] calldata tokenPercentage_,
uint32 deadline
) external onlyOwner {
require(strategyTokens_.length >= 1, "Setting strategy to 0 tokens.");
require(strategyTokens_.length <= 5, "Setting strategy to more than 5 tokens.");
require(strategyTokens_.length == tokenPercentage_.length, "Strategy tokens length doesn't match token percentage length.");
uint256 totalPercentage = 0;
for (uint8 i = 0; i < tokenPercentage_.length; i++) {
totalPercentage = totalPercentage.add(tokenPercentage_[i]);
}
require(totalPercentage == 100, "Total token percentage is not 100%.");
address[] memory oldTokens = new address[](strategyTokenCount());
uint8[] memory oldPercentage = new uint8[](strategyTokenCount());
for (uint8 i = 0; i < strategyTokenCount(); i++) {
oldTokens[i] = _strategyTokens[i].tokenAddress;
oldPercentage[i] = _strategyTokens[i].tokenPercentage;
}
// Before mutate strategyTokens, convert current strategy tokens to ETH
uint256 ethConverted = _convertStrategyTokensToEth(totalTokenStored(), deadline);
delete _strategyTokens;
for (uint8 i = 0; i < strategyTokens_.length; i++) {
_strategyTokens.push(StategyToken(strategyTokens_[i], tokenPercentage_[i]));
}
_convertEthToStrategyTokens(ethConverted, deadline);
emit StrategyChange(oldTokens, oldPercentage, strategyTokens_, tokenPercentage_, totalTokenStored());
}
/**
* @dev Realigning the weighting of a portfolio of assets to the strategy allocation that is defined.
* Only convert the amount that's necessory to convert to not be charged 0.3% uniswap fee for everything.
* This in total saves 0.6% fee for majority of the assets.
* @param deadline Unix timestamp after which the transaction will revert.
*/
function rebalance(uint32 deadline) external onlyOwner {
require(strategyTokenCount() > 0, "Strategy hasn't been set");
// Get each tokens worth and the total worth in ETH
uint256 totalWorthInEth = 0;
uint256[] memory tokensWorthInEth = new uint256[](strategyTokenCount());
for (uint8 i = 0; i < strategyTokenCount(); i++) {
address currentToken = _strategyTokens[i].tokenAddress;
uint256 tokenWorth = _getEthAmountByTokenAmount(IERC20(currentToken).balanceOf(address(this)), currentToken, true);
totalWorthInEth = totalWorthInEth.add(tokenWorth);
tokensWorthInEth[i] = tokenWorth;
}
address[] memory strategyTokensArray = new address[](strategyTokenCount()); // Get percentages for event param
uint8[] memory percentageArray = new uint8[](strategyTokenCount()); // Get percentages for event param
uint256 totalInEthToConvert = 0; // Get total token worth in ETH needed to be converted
uint256 totalEthConverted = 0; // Get total token worth in ETH needed to be converted
uint256[] memory tokenInEthNeeded = new uint256[](strategyTokenCount()); // Get token worth need to be filled
for (uint8 i = 0; i < strategyTokenCount(); i++) {
strategyTokensArray[i] = _strategyTokens[i].tokenAddress;
percentageArray[i] = _strategyTokens[i].tokenPercentage;
uint256 tokenShouldWorth = totalWorthInEth.mul(_strategyTokens[i].tokenPercentage).div(100);
if (tokensWorthInEth[i] <= tokenShouldWorth) {
// If token worth less than should be, calculate the diff and store as needed
tokenInEthNeeded[i] = tokenShouldWorth.sub(tokensWorthInEth[i]);
totalInEthToConvert = totalInEthToConvert.add(tokenInEthNeeded[i]);
} else {
tokenInEthNeeded[i] = 0;
// If token worth more than should be, convert the overflowed amount to ETH
uint256 tokenInEthOverflowed = tokensWorthInEth[i].sub(tokenShouldWorth);
uint256 tokensToConvert = _getTokenAmountByEthAmount(tokenInEthOverflowed, _strategyTokens[i].tokenAddress, true);
uint256 ethConverted = _convertTokenToEth(tokensToConvert, _strategyTokens[i].tokenAddress, deadline);
totalEthConverted = totalEthConverted.add(ethConverted);
}
// Need the total value to help calculate how to distributed the converted ETH
}
// Distribute newly converted ETH by portion of each token to be converted to, and convert to that token needed.
// Note: totalEthConverted would be a bit smaller than totalInEthToConvert due to Uniswap fee.
// Converting everything is another way of rebalancing, but Uniswap would take 0.6% fee on everything.
// In this method we reach the closest number with the lowest possible swapping fee.
if(totalInEthToConvert > 0) {
for (uint8 i = 0; i < strategyTokenCount(); i++) {
uint256 ethToConvert = totalEthConverted.mul(tokenInEthNeeded[i]).div(totalInEthToConvert);
_convertEthToToken(ethToConvert, _strategyTokens[i].tokenAddress, deadline);
}
}
emit Rebalance(strategyTokensArray, percentageArray, totalTokenStored());
}
/**
* @dev Withdraw DRC by DR-POD amount to burn.
* @param podToBurn Amount of DR-POD to burn in exchange for DRC.
* @param deadline Unix timestamp after which the transaction will revert.
*/
function _withdrawProofOfDeposit(uint256 podToBurn, uint32 deadline) private {
uint256[] memory strategyTokensToWithdraw = _getStrategyTokensByPodAmount(podToBurn);
_burn(msg.sender, podToBurn);
uint256 ethConverted = _convertStrategyTokensToEth(strategyTokensToWithdraw, deadline);
uint256 fees = ethConverted.mul(_feeFraction).div(_feeBase + _feeFraction);
uint256 drcAmount = _convertEthToToken(ethConverted.sub(fees), drcAddress, deadline);
SafeERC20.safeTransfer(IERC20(drcAddress), msg.sender, drcAmount);
SafeERC20.safeTransfer(IERC20(uniswapRouter.WETH()), owner(), fees);
emit Withdraw(msg.sender, drcAmount, fees, podToBurn, totalSupply(), totalTokenStored());
}
/**
* @dev Get ETH worth of a certain amount of a token.
* @param _amount Amount of token to convert.
* @param _fromAddress Address of token to convert from.
* @param _toAddress Address of token to convert to.
* @param excludeFees If uniswap fees is considered.
*/
function _getAAmountByBAmount(
uint256 _amount,
address _fromAddress,
address _toAddress,
bool excludeFees
) private view returns (uint256) {
address[] memory path = new address[](2);
path[0] = _fromAddress;
path[1] = _toAddress;
if (path[0] == path[1] || _amount == 0) {
return _amount;
}
uint256 amountOut = uniswapRouter.getAmountsOut(_amount, path)[1];
if (excludeFees) {
return amountOut.mul(1000).div(997);
} else {
return amountOut;
}
}
/**
* @dev Get the worth in a token of a certain amount of ETH.
* @param _amount Amount of ETH to convert.
* @param _tokenAddress Address of the token to convert to.
* @param excludeFees If uniswap fees is considered.
*/
function _getTokenAmountByEthAmount(
uint256 _amount,
address _tokenAddress,
bool excludeFees
) private view returns (uint256) {
return _getAAmountByBAmount(_amount, uniswapRouter.WETH(), _tokenAddress, excludeFees);
}
/**
* @dev Get ETH worth of a certain amount of a token.
* @param _amount Amount of token to convert.
* @param _tokenAddress Address of token to convert from.
* @param excludeFees If uniswap fees is considered.
*/
function _getEthAmountByTokenAmount(
uint256 _amount,
address _tokenAddress,
bool excludeFees
) private view returns (uint256) {
return _getAAmountByBAmount(_amount, _tokenAddress, uniswapRouter.WETH(), excludeFees);
}
/**
* @dev Get ETH worth of an array of strategy tokens.
* @param strategyTokensBalance_ Array amounts of strategy tokens to convert.
* @param excludeFees If uniswap fees is considered.
*/
function _getEthAmountByStrategyTokensAmount(
uint256[] memory strategyTokensBalance_,
bool excludeFees
) private view returns (uint256) {
uint256 amountOut = 0;
address[] memory path = new address[](2);
path[1] = uniswapRouter.WETH();
for (uint8 i = 0; i < strategyTokenCount(); i++) {
address tokenAddress = _strategyTokens[i].tokenAddress;
path[0] = tokenAddress;
uint256 tokenAmount = strategyTokensBalance_[i];
uint256 tokenAmountInEth = _getEthAmountByTokenAmount(tokenAmount, tokenAddress, excludeFees);
amountOut = amountOut.add(tokenAmountInEth);
}
return amountOut;
}
/**
* @dev Get DR-POD worth in an array of strategy tokens.
* @param _amount Amount of DR-POD to convert.
*/
function _getStrategyTokensByPodAmount(uint256 _amount) private view returns (uint256[] memory) {
uint256[] memory strategyTokenAmount = new uint256[](strategyTokenCount());
uint256 podFraction = 0;
if(totalSupply() > 0){
podFraction = _amount.mul(1e10).div(totalSupply());
}
for (uint8 i = 0; i < strategyTokenCount(); i++) {
strategyTokenAmount[i] = IERC20(_strategyTokens[i].tokenAddress).balanceOf(address(this)).mul(podFraction).div(1e10);
}
return strategyTokenAmount;
}
/**
* @dev Get price impact when swap ETH to a token via the Uniswap router.
* @param _amount Amount of eth to swap.
* @param _tokenAddress Address of token to swap to.
*/
function _getEthToTokenPriceImpact(uint256 _amount, address _tokenAddress) private view returns (uint256) {
if(_tokenAddress == uniswapRouter.WETH() || _amount == 0) {
return 0;
}
address factory = uniswapRouter.factory();
address pair = IUniswapV2Factory(factory).getPair(uniswapRouter.WETH(), _tokenAddress);
(uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pair).getReserves();
uint256 reserveEth = 0;
if(IUniswapV2Pair(pair).token0() == uniswapRouter.WETH()) {
reserveEth = reserve0;
} else {
reserveEth = reserve1;
}
return 10000 - reserveEth.mul(10000).div(reserveEth.add(_amount));
}
/**
* @dev Get price impact when swap ETH to strategy tokens via the Uniswap router.
* @param _amount Amount of eth to swap.
*/
function _getEthToStrategyTokensPriceImpact(uint256 _amount) private view returns (uint256) {
uint256 priceImpact = 0;
for (uint8 i = 0; i < strategyTokenCount(); i++) {
uint8 tokenPercentage = _strategyTokens[i].tokenPercentage;
uint256 amountToConvert = _amount.mul(tokenPercentage).div(100);
uint256 tokenSwapPriceImpact = _getEthToTokenPriceImpact(amountToConvert, _strategyTokens[i].tokenAddress);
priceImpact = priceImpact.add(tokenSwapPriceImpact.mul(tokenPercentage).div(100));
}
return priceImpact;
}
/**
* @dev Convert a token to WETH via the Uniswap router.
* @param _amount Amount of tokens to swap.
* @param _tokenAddress Address of token to swap.
* @param deadline Unix timestamp after which the transaction will revert.
*/
function _convertTokenToEth(
uint256 _amount,
address _tokenAddress,
uint32 deadline
) private returns (uint256) {
if (_tokenAddress == uniswapRouter.WETH() || _amount == 0) {
return _amount;
}
address[] memory path = new address[](2);
path[0] = _tokenAddress;
path[1] = uniswapRouter.WETH();
SafeERC20.safeApprove(IERC20(path[0]), address(uniswapRouter), _amount);
uint256 amountOut = uniswapRouter.getAmountsOut(_amount, path)[1];
uint256 amountOutWithFeeTolerance = amountOut.mul(999).div(1000);
uint256 ethBeforeSwap = IERC20(path[1]).balanceOf(address(this));
uniswapRouter.swapExactTokensForTokensSupportingFeeOnTransferTokens(_amount, amountOutWithFeeTolerance, path, address(this), deadline);
uint256 ethAfterSwap = IERC20(path[1]).balanceOf(address(this));
return ethAfterSwap - ethBeforeSwap;
}
/**
* @dev Convert ETH to another token via the Uniswap router.
* @param _amount Amount of WETH to swap.
* @param _tokenAddress Address of token to swap to.
* @param deadline Unix timestamp after which the transaction will revert.
*/
function _convertEthToToken(
uint256 _amount,
address _tokenAddress,
uint32 deadline
) private returns (uint256) {
if (_tokenAddress == uniswapRouter.WETH() || _amount == 0) {
return _amount;
}
address[] memory path = new address[](2);
path[0] = uniswapRouter.WETH();
path[1] = _tokenAddress;
SafeERC20.safeApprove(IERC20(path[0]), address(uniswapRouter), _amount);
uint256 amountOut = uniswapRouter.getAmountsOut(_amount, path)[1];
uniswapRouter.swapExactTokensForTokens(_amount, amountOut, path, address(this), deadline);
return amountOut;
}
/**
* @dev Convert ETH to strategy tokens of DR in their allocation percentage.
* @param amount Amount of WETH to swap.
* @param deadline Unix timestamp after which the transaction will revert.
*/
function _convertEthToStrategyTokens(
uint256 amount,
uint32 deadline
) private returns (uint256[] memory) {
for (uint8 i = 0; i < strategyTokenCount(); i++) {
uint256 amountToConvert = amount.mul(_strategyTokens[i].tokenPercentage).div(100);
_convertEthToToken(amountToConvert, _strategyTokens[i].tokenAddress, deadline);
}
}
/**
* @dev Convert strategy tokens to WETH.
* @param amountToConvert Array of the amounts of strategy tokens to swap.
* @param deadline Unix timestamp after which the transaction will revert.
*/
function _convertStrategyTokensToEth(
uint256[] memory amountToConvert,
uint32 deadline
) private returns (uint256) {
uint256 ethConverted = 0;
for (uint8 i = 0; i < strategyTokenCount(); i++) {
uint256 amountConverted = _convertTokenToEth(amountToConvert[i], _strategyTokens[i].tokenAddress, deadline);
ethConverted = ethConverted.add(amountConverted);
}
return ethConverted;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity =0.6.12;
/**
* @dev Interface of Digital Reserve contract.
*/
interface IDigitalReserve {
/**
* @dev Returns length of the portfolio asset tokens.
* Can be used to get token addresses and percentage allocations.
*/
function strategyTokenCount() external view returns (uint256);
/**
* @dev Returns a strategy token address.
* @param index The index of a strategy token
*/
function strategyTokens(uint8 index) external view returns (address, uint8);
/**
* @dev Returns withdrawal withdrawal fee.
* @return The first value is fraction, the second one is fraction base
*/
function withdrawalFee() external view returns (uint8, uint8);
/**
* @dev Returns Proof of Deposit price decimal.
* Price should be displayed as `price / (10 ** priceDecimals)`.
*/
function priceDecimals() external view returns (uint8);
/**
* @dev Returns total strategy tokens stored in an array.
* The output amount sequence is the strategyTokens() array sequence.
*/
function totalTokenStored() external view returns (uint256[] memory);
/**
* @dev Returns how much user's vault share in DRC amount.
* @param user Address of a DR user
* @param percentage Percentage of user holding
* @return The first output is total worth in DRC,
* second one is total DRC could withdraw (exclude fees),
* and last output is fees in wei.
*/
function getUserVaultInDrc(address user, uint8 percentage) external view returns (uint256, uint256, uint256);
/**
* @dev Get deposit price impact
* @param drcAmount DRC amount user want to deposit.
* @return The price impact on the base of 10000,
*/
function depositPriceImpact(uint256 drcAmount) external view returns (uint256);
/**
* @dev Proof of Deposit net unit worth.
*/
function getProofOfDepositPrice() external view returns (uint256);
/**
* @dev Deposit DRC to DR.
* @param drcAmount DRC amount user want to deposit.
* @param deadline Unix timestamp after which the transaction will revert.
*/
function depositDrc(uint256 drcAmount, uint32 deadline) external;
/**
* @dev Withdraw DRC from DR.
* @param drcAmount DRC amount user want to withdraw.
* @param deadline Unix timestamp after which the transaction will revert.
*/
function withdrawDrc(uint256 drcAmount, uint32 deadline) external;
/**
* @dev Withdraw a percentage of holding from DR.
* @param percentage Percentage of holding user want to withdraw.
* @param deadline Unix timestamp after which the transaction will revert.
*/
function withdrawPercentage(uint8 percentage, uint32 deadline) external;
/**
* @dev Emit when strategy set or change function is called by owner.
* @param oldTokens Pervious strategy's token addresses.
* @param oldPercentage Pervious strategy's token allocation percentages.
* @param newTokens New strategy's token addresses.
* @param newPercentage New strategy's token allocation percentages.
* @param tokensStored How much each token is stored.
*/
event StrategyChange(
address[] oldTokens,
uint8[] oldPercentage,
address[] newTokens,
uint8[] newPercentage,
uint256[] tokensStored
);
/**
* @dev Emit each time a rebalance function is called by owner.
* @param strategyTokens Strategy token addresses.
* @param tokenPercentage Strategy token allocation percentages.
* @param tokensStored How much each token is stored.
*/
event Rebalance(
address[] strategyTokens,
uint8[] tokenPercentage,
uint256[] tokensStored
);
/**
* @dev Emit each time a deposit action happened.
* @param user Address made the deposit.
* @param amount DRC amount deposited.
* @param podMinted New DR-POD minted.
* @param podTotalSupply New DR-POD total supply.
* @param tokensStored How much each token is stored.
*/
event Deposit(
address indexed user,
uint256 amount,
uint256 podMinted,
uint256 podTotalSupply,
uint256[] tokensStored
);
/**
* @dev Emit each time a withdraw action happened.
* @param user Address made the withdrawal.
* @param amount DRC amount withdrawn.
* @param fees Withdrawal fees charged in wei.
* @param podBurned DR-POD burned.
* @param podTotalSupply New DR-POD total supply.
* @param tokensStored How much each token is stored.
*/
event Withdraw(
address indexed user,
uint256 amount,
uint256 fees,
uint256 podBurned,
uint256 podTotalSupply,
uint256[] tokensStored
);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity =0.6.12;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity =0.6.12;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity =0.6.12;
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);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity =0.6.12;
import './IUniswapV2Router01.sol';
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;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../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 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
pragma solidity >=0.6.0 <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 () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
} | Change withdrawal fee percentage. If 1%, then input (1,100) If 0.5%, then input (5,1000) withdrawalFeeFraction_ Fraction of withdrawal fee based on withdrawalFeeBase_ withdrawalFeeBase_ Fraction of withdrawal fee base/ | function changeFee(uint8 withdrawalFeeFraction_, uint8 withdrawalFeeBase_) external onlyOwner {
require(withdrawalFeeFraction_ <= withdrawalFeeBase_, "Fee fraction exceeded base.");
uint8 percentage = (withdrawalFeeFraction_ * 100) / withdrawalFeeBase_;
_feeFraction = withdrawalFeeFraction_;
_feeBase = withdrawalFeeBase_;
}
| 12,155,553 |
pragma solidity >=0.4.22 <0.6.0;
contract BusinessPartnershipContract {
address payable public partnerOne; // First Business partner address
address payable public partnerTwo; // Second Business partner address
bool public signed = false;
bool public separated = false;
mapping(address => bool) private hasSeparated; // mapping to track end of partnership
mapping(address => bool) private hasSigned; // mapping to track if contract signed for partnership by both the partners
struct Item {
string data; // item details
uint partnerOneShare; // percentage share of partner one
uint partnerTwoShare; // percentage share of partner two
bool added;
bool removed;
mapping (address => bool) hasApprovedAdd; // mapping to track approval of partners
mapping (address => bool) hasApprovedRemove; // mapping to track approval of partners
}
Item[] public items; // array to store the item structs.
uint[] public itemIds; // array to track the item index in items array
event FundsAdded(uint _timestamp, address _wallet, uint _amount);
event FundsSent(uint _timestamp, address _wallet, uint _amount);
event SeparationApproved(uint _timestamp, address _wallet);
event Separated(uint _timestamp);
event InPartnership(uint _timestamp);
event Signed(uint _timestamp, address _wallet);
event ItemProposed(uint _timestamp,string _data, address _wallet);
event ItemAddApproved(uint _timestamp,string _data, address _wallet);
event ItemAdded(uint _timestamp,string _data);
event ItemRemoved(uint _timestamp,string _data);
constructor(address payable _partnerOne, address payable _partnerTwo) public {
require(_partnerOne != address(0), "Partner address must not be zero!");
require(_partnerTwo != address(0), "Partner address must not be zero!");
require(_partnerOne != _partnerTwo, "Partner address should not be equal!");
partnerOne = _partnerOne;
partnerTwo = _partnerTwo;
}
modifier onlyPartner() {
require(msg.sender == partnerOne || msg.sender == partnerTwo, "Only business partners are allowed to perform this transaction!");
_;
}
modifier isSigned() {
require(signed == true, "Contract has not been signed by both partners yet!");
_;
}
modifier areNotSeparated() {
require(separated == false, "Transaction cannot be done as partners are separated!");
_;
}
// Before carrying out any transaction partnership agreement needs to be signed by both the partners.
function signContract() external onlyPartner {
require(hasSigned[msg.sender] == false, "Partner has already signed the contract!");
hasSigned[msg.sender] = true;
emit Signed(now, msg.sender);
if (hasSigned[partnerOne] && hasSigned[partnerTwo]) {
signed = true;
emit InPartnership(now);
}
}
// propose an item required to be added
function proposeItem(string calldata _data, uint _partnerOneShare, uint _partnerTwoShare) external onlyPartner isSigned areNotSeparated {
require(_partnerOneShare >= 0, "PartnerOne share invalid!");
require(_partnerTwoShare >= 0, "PartnerTwo share invalid!");
require((_partnerOneShare + _partnerTwoShare) == 100, "Total share must be equal to 100%!");
// Adding new item
Item memory newItem = Item({
data: _data,
partnerOneShare: _partnerOneShare,
partnerTwoShare: _partnerTwoShare,
added: false,
removed: false
});
uint newItemId = items.push(newItem);
emit ItemProposed(now, _data, msg.sender);
itemIds.push(newItemId - 1);
Item storage item = items[newItemId - 1];
//approve it by the sender
item.hasApprovedAdd[msg.sender] = true;
emit ItemAddApproved(now, _data, msg.sender);
}
// approve an item so that it gets added
function approveItem(uint _itemId) external onlyPartner isSigned areNotSeparated {
require(_itemId > 0 && _itemId <= items.length, "Invalid Item id!");
Item storage item = items[_itemId];
require(item.added == false, "Item has already been added!");
require(item.removed == false, "Item has already been removed!");
require(item.hasApprovedAdd[msg.sender] == false, "Item is already approved by sender!");
item.hasApprovedAdd[msg.sender] = true;
if (item.hasApprovedAdd[partnerOne] && item.hasApprovedAdd[partnerTwo]) {
item.added = true;
emit ItemAdded(now, item.data);
}
}
// approve the removal of an item
function removeItem(uint _itemId) external onlyPartner isSigned areNotSeparated {
require(_itemId > 0 && _itemId <= items.length, "Invalid item id!");
Item storage item = items[_itemId];
require(item.added, "Item has not been added yet!");
require(item.removed == false, "Item has already been removed!");
require(item.hasApprovedRemove[msg.sender] == false, "Removing the item has already been approved by the sender!");
item.hasApprovedRemove[msg.sender] = true;
if (item.hasApprovedRemove[partnerOne] && item.hasApprovedRemove[partnerTwo]) {
item.removed = true;
emit ItemRemoved(now, item.data);
}
}
// adding funds to the contract
function() external payable isSigned areNotSeparated {
emit FundsAdded(now, msg.sender, msg.value);
}
// payment to any external account by either of partners
function pay(address payable _to, uint _amount) external onlyPartner isSigned areNotSeparated {
require(_amount <= address(this).balance, "Not enough balance available!");
_to.transfer(_amount);
emit FundsSent(now, _to, _amount);
}
// end the partnership & divide the contract stored fund equally.
function getSeparated() external onlyPartner isSigned areNotSeparated {
require(hasSeparated[msg.sender] == false, "Sender has already approved to end partnership!");
hasSeparated[msg.sender] = true;
emit SeparationApproved(now, msg.sender);
// Check if both partners have approved to end the partnership
if (hasSeparated[partnerOne] && hasSeparated[partnerTwo]) {
separated = true;
emit Separated(now);
uint balance = address(this).balance;
// Split the remaining balance half-half
if (balance != 0) {
uint balancePerPartner = balance / 2;
partnerOne.transfer(balancePerPartner);
emit FundsSent(now, partnerOne, balancePerPartner);
partnerTwo.transfer(balancePerPartner);
emit FundsSent(now, partnerTwo, balancePerPartner);
}
}
}
// returns the array of item indexes.
function getItemIds() external view returns (uint[] memory) {
return itemIds;
}
} | adding funds to the contract | function() external payable isSigned areNotSeparated {
emit FundsAdded(now, msg.sender, msg.value);
}
| 15,814,967 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC1155.sol";
/**
* @dev ERC1155 token where the admin can control what's approvable
*/
abstract contract ERC1155Approvable is ERC1155 {
bool private _approved = true;
/**
* @dev Returns true if approvable
*/
function isApprovable() public virtual view returns(bool) {
return _approved;
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual override {
if (!_approved) revert InvalidCall();
super._setApprovalForAll(owner, operator, approved);
}
/**
* @dev Allows or denies tokens to be approvable
*/
function _approvable(bool yes) internal virtual {
_approved = yes;
}
}
| Approve `operator` to operate on all of `owner` tokens Emits a {ApprovalForAll} event./ | function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual override {
if (!_approved) revert InvalidCall();
super._setApprovalForAll(owner, operator, approved);
}
| 6,485,052 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/**
╭━━━╮╱╱╱╱╱╱╱╱╱╱╱╱╱╭━━━╮
┃╭━╮┃╱╱╱╱╱╱╱╱╱╱╱╱╱┃╭━╮┃
┃┃╱╰╋━━┳━━┳╮╭┳┳━━╮┃┃╱╰╋━━┳━━┳━━╮
┃┃╱╭┫╭╮┃━━┫╰╯┣┫╭━╯┃┃╱╭┫╭╮┃╭╮┃━━┫
┃╰━╯┃╰╯┣━━┃┃┃┃┃╰━╮┃╰━╯┃╭╮┃╰╯┣━━┃
╰━━━┻━━┻━━┻┻┻┻┻━━╯╰━━━┻╯╰┫╭━┻━━╯
╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱┃┃
╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╰╯
credit to DerpyBirbs contract and team
Cosmic Caps are fungi from far out in the shroomiverse, and they want to chill with you!
*/
contract CosmicCaps is Context, ERC721Enumerable, ERC721Burnable, Ownable {
uint internal constant MAX_MINTS_PER_TRANSACTION = 32;
// uint internal constant TOKEN_LIMIT = 10;
uint internal constant TOKEN_LIMIT = 10000;
uint private nonce = 0;
uint[TOKEN_LIMIT] private indices;
uint private numTokens = 0;
uint256 internal _mintPrice = 0;
// REMOVE TESTNET ADDRESSES BEFORE DEPLOYMENT ON MAINNET
address payable internal jukabo = payable(0xfF190a4CC92b154635140335791D3779F60DC311);
// REMOVE TESTNET ADDRESSES BEFORE DEPLOYMENT ON MAINNET
string internal _baseTokenURI;
bool internal saleStarted = false;
bool internal URISet = false;
uint internal devSupplyAwarded = 0;
/**
* Token URIs will be autogenerated based on `baseURI` and their token IDs.
* See {ERC721-tokenURI}.
*/
constructor(string memory name, string memory symbol,string memory baseTokenURI) ERC721(name, symbol) {
_baseTokenURI = baseTokenURI;
//dont call awardDevs() here, initial supply here, too much gas for one transaction
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
/**
* Can only be called twice. Gives 64 total Shrooms to devs for giveaways, marketing purposes and team members.
* 28 of these will go to Treasure Chests holders.
*/
function give32TokensToDevs() external onlyOwner {
require(saleStarted == false,"Sale has already started");
require(devSupplyAwarded < 64,"Dev supply has already been awarded");
uint i;
uint id;
for(i = 0; i < 32; i++){
id = randomIndex();
_mint(jukabo, id);
numTokens = numTokens + 1;
}
devSupplyAwarded = devSupplyAwarded+1;
}
/**
* Credits to LarvaLabs Meebits contract
*/
function randomIndex() internal returns (uint) {
uint totalSize = TOKEN_LIMIT - numTokens;
uint index = uint(keccak256(abi.encodePacked(nonce, msg.sender, block.difficulty, block.timestamp))) % totalSize;
uint value = 0;
if (indices[index] != 0) {
value = indices[index];
} else {
value = index;
}
// Move last value to selected position
if (indices[totalSize - 1] == 0) {
// Array position not initialized, so use position
indices[index] = totalSize - 1;
} else {
// Array position holds a value so use that
indices[index] = indices[totalSize - 1];
}
nonce++;
// Don't allow a zero index, start counting at 1
return value+1;
}
/**
* @dev Creates a new token. 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.
*
* See {ERC721-_mint}.
*
*/
function mint(address to, uint amount) external payable{
//check sale start
require(saleStarted == true, "Sale has not started yet.");
//only 9999 Cosmic Caps
require(numTokens < TOKEN_LIMIT, "Mint request exceeds total supply!");
//mint at least one
require(amount > 0, "Must mint at least one.");
//32 max per transaction
require(amount <= MAX_MINTS_PER_TRANSACTION, "Mint exceeds limit per call.");
//dont overmint
require(amount <= TOKEN_LIMIT-numTokens,"Mint request exceeds current supply!");
//check payment
require(msg.value == _mintPrice * amount, "msg.value invalid");
uint id;
uint i;
for(i = 0; i < amount; i++){
id = randomIndex();
_mint(to, id);
numTokens = numTokens + 1;
}
}
/**
* @dev Withdraws funds to dev and art teams
*
*/
function withdrawFunds() external virtual {
uint256 balance = address(this).balance;
jukabo.transfer(balance);
}
/**
* Devs cant change URI after the sale begins
*/
function setBaseURI(string memory baseTokenURI) external onlyOwner {
require(saleStarted == false,"Can't change metadata after the sale has started");
_baseTokenURI = baseTokenURI;
URISet = true;
}
/**
* Start the sale (cant be stopped later)
*/
function startSale(uint256 mintPrice) external virtual onlyOwner {
require(saleStarted == false,"Sale has already started");
require(URISet == true, "URI not set");
mintPrice = 0.06 ether;
require(mintPrice > 0.01 ether,"Price too low");
_mintPrice = mintPrice;
saleStarted = true;
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) {
return super.supportsInterface(interfaceId);
}
function getAmountMinted() external view returns (uint256) {
return numTokens;
}
function getMaxSupply() external pure returns (uint256) {
return TOKEN_LIMIT;
}
function getMintPrice() external view returns (uint256) {
return _mintPrice;
}
function hasSaleStarted() external view returns (bool) {
return saleStarted;
}
}
// 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 "../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 "../ERC721.sol";
import "../../../utils/Context.sol";
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
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);
}
}
// 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 Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// 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);
}
| Credits to LarvaLabs Meebits contract/ Move last value to selected position Array position not initialized, so use position Array position holds a value so use that | function randomIndex() internal returns (uint) {
uint totalSize = TOKEN_LIMIT - numTokens;
uint index = uint(keccak256(abi.encodePacked(nonce, msg.sender, block.difficulty, block.timestamp))) % totalSize;
uint value = 0;
if (indices[index] != 0) {
value = indices[index];
value = index;
}
if (indices[totalSize - 1] == 0) {
indices[index] = totalSize - 1;
indices[index] = indices[totalSize - 1];
}
nonce++;
}
| 1,289,034 |